diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000..1ce2a87611 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,114 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# IntelliJ +.idea +# Goland's output filename can not be set manually +/go_build_* + +# MS VSCode +.vscode +__debug_bin + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof + +*coverage.out +coverage.all +cpu.out + +/modules/migration/bindata.go +/modules/migration/bindata.go.hash +/modules/options/bindata.go +/modules/options/bindata.go.hash +/modules/public/bindata.go +/modules/public/bindata.go.hash +/modules/templates/bindata.go +/modules/templates/bindata.go.hash + +*.db +*.log + +/gitea +/gitea-vet +/debug +/integrations.test + +/bin +/dist +/custom/* +!/custom/conf +/custom/conf/* +!/custom/conf/app.example.ini +/data +/indexers +/log +/public/img/avatar +/tests/integration/gitea-integration-* +/tests/integration/indexers-* +/tests/e2e/gitea-e2e-* +/tests/e2e/indexers-* +/tests/e2e/reports +/tests/e2e/test-artifacts +/tests/e2e/test-snapshots +/tests/*.ini +/node_modules +/yarn.lock +/yarn-error.log +/npm-debug.log* +/public/js +/public/serviceworker.js +/public/css +/public/fonts +/public/img/webpack +/vendor +/web_src/fomantic/node_modules +/web_src/fomantic/build/* +!/web_src/fomantic/build/semantic.js +!/web_src/fomantic/build/semantic.css +!/web_src/fomantic/build/themes +/web_src/fomantic/build/themes/* +!/web_src/fomantic/build/themes/default +/web_src/fomantic/build/themes/default/assets/* +!/web_src/fomantic/build/themes/default/assets/fonts +/web_src/fomantic/build/themes/default/assets/fonts/* +!/web_src/fomantic/build/themes/default/assets/fonts/icons.woff2 +!/web_src/fomantic/build/themes/default/assets/fonts/outline-icons.woff2 +/VERSION +/.air +/.go-licenses + +# Snapcraft +snap/.snapcraft/ +parts/ +stage/ +prime/ +*.snap +*.snap-build +*_source.tar.bz2 +.DS_Store + +# Make evidence files +/.make_evidence + +# Manpage +/man diff --git a/.drone.yml b/.drone.yml index f2b34ef7e3..1f92d87716 100644 --- a/.drone.yml +++ b/.drone.yml @@ -39,16 +39,6 @@ steps: - make lint-frontend depends_on: [deps-frontend] - - name: security-check - image: golang:1.19 - pull: always - commands: - - make security-check - depends_on: [deps-backend] - volumes: - - name: deps - path: /go - - name: lint-backend image: gitea/test_env:linux-amd64 # https://gitea.com/gitea/test-env pull: always @@ -561,7 +551,7 @@ steps: # TODO: We should probably build all dependencies into a test image - name: test-e2e - image: mcr.microsoft.com/playwright:v1.27.1-focal + image: mcr.microsoft.com/playwright:v1.28.0-focal commands: - curl -sLO https://go.dev/dl/go1.19.linux-amd64.tar.gz && tar -C /usr/local -xzf go1.19.linux-amd64.tar.gz - groupadd --gid 1001 gitea && useradd -m --gid 1001 --uid 1001 gitea @@ -610,7 +600,7 @@ steps: from_secret: crowdin_key - name: update - image: alpine:3.13 + image: alpine:3.17 pull: always commands: - ./build/update-locales.sh diff --git a/.eslintrc.yaml b/.eslintrc.yaml index cd86b680ee..5e5cda7dc8 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -199,7 +199,7 @@ rules: newline-per-chained-call: [0] no-alert: [0] no-array-constructor: [2] - no-async-promise-executor: [2] + no-async-promise-executor: [0] no-await-in-loop: [0] no-bitwise: [0] no-buffer-constructor: [0] @@ -229,6 +229,7 @@ rules: no-empty-character-class: [2] no-empty-function: [0] no-empty-pattern: [2] + no-empty-static-block: [2] no-empty: [2, {allowEmptyCatch: true}] no-eq-null: [2] no-eval: [2] @@ -269,6 +270,7 @@ rules: no-negated-condition: [0] no-nested-ternary: [0] no-new-func: [2] + no-new-native-nonconstructor: [2] no-new-object: [2] no-new-symbol: [2] no-new-wrappers: [2] @@ -443,6 +445,7 @@ rules: unicorn/no-invalid-remove-event-listener: [2] unicorn/no-keyword-prefix: [0] unicorn/no-lonely-if: [2] + unicorn/no-negated-condition: [0] unicorn/no-nested-ternary: [0] unicorn/no-new-array: [0] unicorn/no-new-buffer: [0] @@ -453,6 +456,7 @@ rules: unicorn/no-static-only-class: [2] unicorn/no-thenable: [2] unicorn/no-this-assignment: [2] + unicorn/no-typeof-undefined: [2] unicorn/no-unnecessary-await: [2] unicorn/no-unreadable-array-destructuring: [0] unicorn/no-unreadable-iife: [2] @@ -503,6 +507,7 @@ rules: unicorn/prefer-regexp-test: [2] unicorn/prefer-replace-all: [0] unicorn/prefer-set-has: [0] + unicorn/prefer-set-size: [2] unicorn/prefer-spread: [0] unicorn/prefer-starts-ends-with: [2] unicorn/prefer-string-slice: [0] diff --git a/.golangci.yml b/.golangci.yml index 99133badd9..130ad286b5 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,28 +1,28 @@ linters: enable: - - gosimple - - deadcode - - typecheck - - govet - - errcheck - - staticcheck - - unused - - structcheck - - varcheck - - dupl - #- gocyclo # The cyclomatic complexety of a lot of functions is too high, we should refactor those another time. - - gofmt - - gocritic - bidichk - - ineffassign - - revive - - gofumpt + # - deadcode # deprecated - https://github.com/golangci/golangci-lint/issues/1841 - depguard + - dupl + - errcheck + - gocritic + # - gocyclo # The cyclomatic complexety of a lot of functions is too high, we should refactor those another time. + - gofmt + - gofumpt + - gosimple + - govet + - ineffassign - nakedret - - unconvert - - wastedassign - nolintlint + - revive + - staticcheck + # - structcheck # deprecated - https://github.com/golangci/golangci-lint/issues/1841 - stylecheck + - typecheck + - unconvert + - unused + # - varcheck # deprecated - https://github.com/golangci/golangci-lint/issues/1841 + # - wastedassign # disabled - https://github.com/golangci/golangci-lint/issues/2649 enable-all: false disable-all: true fast: false diff --git a/.stylelintrc.yaml b/.stylelintrc.yaml index 342bf6a4e8..d51a08bf8e 100644 --- a/.stylelintrc.yaml +++ b/.stylelintrc.yaml @@ -1,8 +1,19 @@ extends: stylelint-config-standard +plugins: + - stylelint-declaration-strict-value + overrides: - files: ["**/*.less"] customSyntax: postcss-less + - files: ["**/*.less"] + rules: + scale-unlimited/declaration-strict-value: [color, { + ignoreValues: /^(inherit|transparent|unset|initial)$/ + }] + - files: ["**/chroma/*", "**/codemirror/*", "**/standalone/*", "**/console/*"] + rules: + scale-unlimited/declaration-strict-value: null rules: alpha-value-notation: null diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index dbe418c356..69363c415e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -440,8 +440,8 @@ Code that you contribute should use the standard copyright header: ``` // Copyright 2022 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. +// SPDX-License-Identifier: MIT + ``` Files in the repository contain copyright from the year they are added diff --git a/Dockerfile b/Dockerfile index d5d98e69a8..3ee474bb34 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,5 +1,5 @@ #Build stage -FROM golang:1.19-alpine3.16 AS build-env +FROM golang:1.19-alpine3.17 AS build-env ARG GOPROXY ENV GOPROXY ${GOPROXY:-direct} @@ -23,7 +23,7 @@ RUN if [ -n "${GITEA_VERSION}" ]; then git checkout "${GITEA_VERSION}"; fi \ # Begin env-to-ini build RUN go build contrib/environment-to-ini/environment-to-ini.go -FROM alpine:3.16 +FROM alpine:3.17 LABEL maintainer="maintainers@gitea.io" EXPOSE 22 3000 diff --git a/Dockerfile.rootless b/Dockerfile.rootless index 8c2b8e98c9..a43a63fa10 100644 --- a/Dockerfile.rootless +++ b/Dockerfile.rootless @@ -1,5 +1,5 @@ #Build stage -FROM golang:1.19-alpine3.16 AS build-env +FROM golang:1.19-alpine3.17 AS build-env ARG GOPROXY ENV GOPROXY ${GOPROXY:-direct} @@ -23,7 +23,7 @@ RUN if [ -n "${GITEA_VERSION}" ]; then git checkout "${GITEA_VERSION}"; fi \ # Begin env-to-ini build RUN go build contrib/environment-to-ini/environment-to-ini.go -FROM alpine:3.16 +FROM alpine:3.17 LABEL maintainer="maintainers@gitea.io" EXPOSE 2222 3000 @@ -31,6 +31,7 @@ EXPOSE 2222 3000 RUN apk --no-cache add \ bash \ ca-certificates \ + dumb-init \ gettext \ git \ curl \ @@ -68,6 +69,6 @@ ENV HOME "/var/lib/gitea/git" VOLUME ["/var/lib/gitea", "/etc/gitea"] WORKDIR /var/lib/gitea -ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"] +ENTRYPOINT ["/usr/bin/dumb-init", "--", "/usr/local/bin/docker-entrypoint.sh"] CMD [] diff --git a/MAINTAINERS b/MAINTAINERS index d383b8b164..74196d4bd8 100644 --- a/MAINTAINERS +++ b/MAINTAINERS @@ -44,8 +44,7 @@ Janis Estelmann (@KN4CK3R) Steven Kriegler (@justusbunsi) Jimmy Praet (@jpraet) Leon Hofmeister (@delvh) -silentcode (@silentcodeg) Wim (@42wim) -xinyu (@penlinux) +Xinyu Zhou (@xin-u) Jason Song (@wolfogre) Yarden Shoham (@yardenshoham) diff --git a/Makefile b/Makefile index 4ca346c63e..d1122984a7 100644 --- a/Makefile +++ b/Makefile @@ -26,15 +26,15 @@ COMMA := , XGO_VERSION := go-1.19.x AIR_PACKAGE ?= github.com/cosmtrek/air@v1.40.4 -EDITORCONFIG_CHECKER_PACKAGE ?= github.com/editorconfig-checker/editorconfig-checker/cmd/editorconfig-checker@2.5.0 -ERRCHECK_PACKAGE ?= github.com/kisielk/errcheck@v1.6.1 -GOFUMPT_PACKAGE ?= mvdan.cc/gofumpt@v0.3.1 -GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/cmd/golangci-lint@v1.47.0 +EDITORCONFIG_CHECKER_PACKAGE ?= github.com/editorconfig-checker/editorconfig-checker/cmd/editorconfig-checker@2.6.0 +ERRCHECK_PACKAGE ?= github.com/kisielk/errcheck@v1.6.2 +GOFUMPT_PACKAGE ?= mvdan.cc/gofumpt@v0.4.0 +GOLANGCI_LINT_PACKAGE ?= github.com/golangci/golangci-lint/cmd/golangci-lint@v1.50.1 GXZ_PAGAGE ?= github.com/ulikunitz/xz/cmd/gxz@v0.5.10 MISSPELL_PACKAGE ?= github.com/client9/misspell/cmd/misspell@v0.3.4 -SWAGGER_PACKAGE ?= github.com/go-swagger/go-swagger/cmd/swagger@v0.30.0 +SWAGGER_PACKAGE ?= github.com/go-swagger/go-swagger/cmd/swagger@v0.30.3 XGO_PACKAGE ?= src.techknowlogick.com/xgo@latest -GO_LICENSES_PACKAGE ?= github.com/google/go-licenses@v1.3.0 +GO_LICENSES_PACKAGE ?= github.com/google/go-licenses@v1.5.0 GOVULNCHECK_PACKAGE ?= golang.org/x/vuln/cmd/govulncheck@latest DOCKER_IMAGE ?= gitea/gitea @@ -333,7 +333,7 @@ checks: checks-frontend checks-backend checks-frontend: lockfile-check svg-check .PHONY: checks-backend -checks-backend: tidy-check swagger-check fmt-check misspell-check swagger-validate +checks-backend: tidy-check swagger-check fmt-check misspell-check swagger-validate security-check .PHONY: lint lint: lint-frontend lint-backend @@ -745,7 +745,7 @@ generate-go: $(TAGS_PREREQ) .PHONY: security-check security-check: - govulncheck -v ./... + go run $(GOVULNCHECK_PACKAGE) -v ./... $(EXECUTABLE): $(GO_SOURCES) $(TAGS_PREREQ) CGO_CFLAGS="$(CGO_CFLAGS)" $(GO) build $(GOFLAGS) $(EXTRA_GOFLAGS) -tags '$(TAGS)' -ldflags '-s -w $(LDFLAGS)' -o $@ diff --git a/build.go b/build.go index d379745c6d..d2e724a7f7 100644 --- a/build.go +++ b/build.go @@ -1,6 +1,6 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT + //go:build vendor diff --git a/build/code-batch-process.go b/build/code-batch-process.go index b6c4171ede..9cc47442b2 100644 --- a/build/code-batch-process.go +++ b/build/code-batch-process.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT //go:build ignore diff --git a/build/codeformat/formatimports.go b/build/codeformat/formatimports.go index 1076e3a0d1..c9fc2a27b4 100644 --- a/build/codeformat/formatimports.go +++ b/build/codeformat/formatimports.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package codeformat diff --git a/build/codeformat/formatimports_test.go b/build/codeformat/formatimports_test.go index 3db90cad7b..c66181d351 100644 --- a/build/codeformat/formatimports_test.go +++ b/build/codeformat/formatimports_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package codeformat diff --git a/build/generate-bindata.go b/build/generate-bindata.go index ab81dd8938..ecd5d5047c 100644 --- a/build/generate-bindata.go +++ b/build/generate-bindata.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build ignore diff --git a/build/generate-emoji.go b/build/generate-emoji.go index 4ad6649b2e..35c23aaf9e 100644 --- a/build/generate-emoji.go +++ b/build/generate-emoji.go @@ -1,7 +1,6 @@ // Copyright 2020 The Gitea Authors. All rights reserved. // Copyright 2015 Kenneth Shaw -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT //go:build ignore @@ -209,8 +208,8 @@ func generate() ([]byte, error) { const hdr = ` // Copyright 2020 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. +// SPDX-License-Identifier: MIT + package emoji diff --git a/build/generate-go-licenses.go b/build/generate-go-licenses.go index 87c773ed8b..ec8fc82a71 100644 --- a/build/generate-go-licenses.go +++ b/build/generate-go-licenses.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT //go:build ignore diff --git a/build/gocovmerge.go b/build/gocovmerge.go index dfe70efdad..c6f74ed85c 100644 --- a/build/gocovmerge.go +++ b/build/gocovmerge.go @@ -1,7 +1,6 @@ // Copyright 2020 The Gitea Authors. All rights reserved. // Copyright (c) 2015, Wade Simmons -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT // gocovmerge takes the results from multiple `go test -coverprofile` runs and // merges them into one profile diff --git a/cmd/admin.go b/cmd/admin.go index 525bc2cfcd..7463b21d81 100644 --- a/cmd/admin.go +++ b/cmd/admin.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2016 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. +// SPDX-License-Identifier: MIT package cmd @@ -413,9 +412,9 @@ var ( Usage: "SMTP Authentication Type (PLAIN/LOGIN/CRAM-MD5) default PLAIN", }, cli.StringFlag{ - Name: "addr", + Name: "host", Value: "", - Usage: "SMTP Addr", + Usage: "SMTP Host", }, cli.IntFlag{ Name: "port", @@ -666,7 +665,7 @@ func runDeleteUser(c *cli.Context) error { } else if c.IsSet("username") { user, err = user_model.GetUserByName(ctx, c.String("username")) } else { - user, err = user_model.GetUserByID(c.Int64("id")) + user, err = user_model.GetUserByID(ctx, c.Int64("id")) } if err != nil { return err @@ -727,7 +726,7 @@ func runRepoSyncReleases(_ *cli.Context) error { log.Trace("Synchronizing repository releases (this may take a while)") for page := 1; ; page++ { - repos, count, err := repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{ + repos, count, err := repo_model.SearchRepositoryByName(ctx, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{ PageSize: repo_model.RepositoryListDefaultPageSize, Page: page, @@ -779,6 +778,7 @@ func runRepoSyncReleases(_ *cli.Context) error { func getReleaseCount(id int64) (int64, error) { return repo_model.GetReleaseCountByRepoID( + db.DefaultContext, id, repo_model.FindReleasesOptions{ IncludeTags: true, @@ -955,8 +955,8 @@ func parseSMTPConfig(c *cli.Context, conf *smtp.Source) error { } conf.Auth = c.String("auth-type") } - if c.IsSet("addr") { - conf.Addr = c.String("addr") + if c.IsSet("host") { + conf.Host = c.String("host") } if c.IsSet("port") { conf.Port = c.Int("port") diff --git a/cmd/admin_auth_ldap.go b/cmd/admin_auth_ldap.go index 9040def822..91276f221f 100644 --- a/cmd/admin_auth_ldap.go +++ b/cmd/admin_auth_ldap.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/admin_auth_ldap_test.go b/cmd/admin_auth_ldap_test.go index 2180b24be5..65f53aaf4e 100644 --- a/cmd/admin_auth_ldap_test.go +++ b/cmd/admin_auth_ldap_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/cert.go b/cmd/cert.go index 162c4171bf..816659023c 100644 --- a/cmd/cert.go +++ b/cmd/cert.go @@ -1,8 +1,7 @@ // Copyright 2009 The Go Authors. All rights reserved. // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2016 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/cmd.go b/cmd/cmd.go index f20a936325..493519e135 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT // Package cmd provides subcommands to the gitea binary - such as "web" or // "admin". diff --git a/cmd/convert.go b/cmd/convert.go index 6d4d99a255..b9ed9f1627 100644 --- a/cmd/convert.go +++ b/cmd/convert.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/docs.go b/cmd/docs.go index 073c574973..901d0abd1c 100644 --- a/cmd/docs.go +++ b/cmd/docs.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/doctor.go b/cmd/doctor.go index d05a0a98d7..ceb6e3fbab 100644 --- a/cmd/doctor.go +++ b/cmd/doctor.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/dump.go b/cmd/dump.go index 6569fb6e36..672a8cdc9c 100644 --- a/cmd/dump.go +++ b/cmd/dump.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2016 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/dump_repo.go b/cmd/dump_repo.go index 5f41ab69a9..2e78877afe 100644 --- a/cmd/dump_repo.go +++ b/cmd/dump_repo.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/embedded.go b/cmd/embedded.go index b71ee6dfe7..118781895e 100644 --- a/cmd/embedded.go +++ b/cmd/embedded.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build bindata diff --git a/cmd/embedded_stub.go b/cmd/embedded_stub.go index 26228256f2..874df06f9d 100644 --- a/cmd/embedded_stub.go +++ b/cmd/embedded_stub.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !bindata diff --git a/cmd/generate.go b/cmd/generate.go index 35c77a815b..f72ee16390 100644 --- a/cmd/generate.go +++ b/cmd/generate.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2016 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/hook.go b/cmd/hook.go index 3970d27cf2..228b79f7f0 100644 --- a/cmd/hook.go +++ b/cmd/hook.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package cmd @@ -218,9 +217,9 @@ Gitea or set your environment appropriately.`, "") } } - supportProcRecive := false + supportProcReceive := false if git.CheckGitVersionAtLeast("2.29") == nil { - supportProcRecive = true + supportProcReceive = true } for scanner.Scan() { @@ -241,9 +240,9 @@ Gitea or set your environment appropriately.`, "") lastline++ // If the ref is a branch or tag, check if it's protected - // if supportProcRecive all ref should be checked because + // if supportProcReceive all ref should be checked because // permission check was delayed - if supportProcRecive || strings.HasPrefix(refFullName, git.BranchPrefix) || strings.HasPrefix(refFullName, git.TagPrefix) { + if supportProcReceive || strings.HasPrefix(refFullName, git.BranchPrefix) || strings.HasPrefix(refFullName, git.TagPrefix) { oldCommitIDs[count] = oldCommitID newCommitIDs[count] = newCommitID refFullNames[count] = refFullName diff --git a/cmd/hook_test.go b/cmd/hook_test.go index 92c7e82a9a..fe1f072a6f 100644 --- a/cmd/hook_test.go +++ b/cmd/hook_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/keys.go b/cmd/keys.go index 684aca64e2..74dc1cc68c 100644 --- a/cmd/keys.go +++ b/cmd/keys.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/mailer.go b/cmd/mailer.go index 35fcb302f8..af6613f159 100644 --- a/cmd/mailer.go +++ b/cmd/mailer.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/main_test.go b/cmd/main_test.go index 9cce0ef036..9aacdf7bba 100644 --- a/cmd/main_test.go +++ b/cmd/main_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/manager.go b/cmd/manager.go index 8fbfd1093c..cdfe509075 100644 --- a/cmd/manager.go +++ b/cmd/manager.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/manager_logging.go b/cmd/manager_logging.go index 761edf654c..d49675ce87 100644 --- a/cmd/manager_logging.go +++ b/cmd/manager_logging.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/migrate.go b/cmd/migrate.go index 49a13adeb5..2546fca21d 100644 --- a/cmd/migrate.go +++ b/cmd/migrate.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/migrate_storage.go b/cmd/migrate_storage.go index b6af5b96e8..0b8ebe7c8d 100644 --- a/cmd/migrate_storage.go +++ b/cmd/migrate_storage.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/migrate_storage_test.go b/cmd/migrate_storage_test.go index 0d264ef5a1..aae366c0cf 100644 --- a/cmd/migrate_storage_test.go +++ b/cmd/migrate_storage_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package cmd @@ -44,8 +43,9 @@ func TestMigratePackages(t *testing.T) { PackageFileInfo: packages_service.PackageFileInfo{ Filename: "a.go", }, - Data: buf, - IsLead: true, + Creator: creator, + Data: buf, + IsLead: true, }) assert.NoError(t, err) assert.NotNil(t, v) diff --git a/cmd/restore_repo.go b/cmd/restore_repo.go index 2256cc61ab..23932f821c 100644 --- a/cmd/restore_repo.go +++ b/cmd/restore_repo.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/serv.go b/cmd/serv.go index 06561f348a..346c918b18 100644 --- a/cmd/serv.go +++ b/cmd/serv.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2016 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/web.go b/cmd/web.go index 1b9f7e420a..49a0335615 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/web_acme.go b/cmd/web_acme.go index d8e550b321..90e4a02764 100644 --- a/cmd/web_acme.go +++ b/cmd/web_acme.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/web_graceful.go b/cmd/web_graceful.go index ba88cc59c2..996537be3b 100644 --- a/cmd/web_graceful.go +++ b/cmd/web_graceful.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/cmd/web_https.go b/cmd/web_https.go index aac11517a6..70d35cd40d 100644 --- a/cmd/web_https.go +++ b/cmd/web_https.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package cmd diff --git a/contrib/environment-to-ini/environment-to-ini.go b/contrib/environment-to-ini/environment-to-ini.go index ccda03fa92..b502c15cec 100644 --- a/contrib/environment-to-ini/environment-to-ini.go +++ b/contrib/environment-to-ini/environment-to-ini.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package main diff --git a/contrib/fixtures/fixture_generation.go b/contrib/fixtures/fixture_generation.go index 66ff5c54e3..210e0aae06 100644 --- a/contrib/fixtures/fixture_generation.go +++ b/contrib/fixtures/fixture_generation.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package main diff --git a/contrib/pr/checkout.go b/contrib/pr/checkout.go index 686a3ddffa..b31a4a8c68 100644 --- a/contrib/pr/checkout.go +++ b/contrib/pr/checkout.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package main diff --git a/custom/conf/app.example.ini b/custom/conf/app.example.ini index ef247fa788..d77936f259 100644 --- a/custom/conf/app.example.ini +++ b/custom/conf/app.example.ini @@ -7,6 +7,38 @@ ;; see https://docs.gitea.io/en-us/config-cheat-sheet/ for additional documentation. +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; Default Configuration (non-`app.ini` configuration) +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +;; +;; These values are environment-dependent but form the basis of a lot of values. They will be +;; reported as part of the default configuration when running `gitea --help` or on start-up. The order they are emitted there is slightly different but we will list them here in the order they are set-up. +;; +;; - _`AppPath`_: This is the absolute path of the running gitea binary. +;; - _`AppWorkPath`_: This refers to "working path" of the `gitea` binary. It is determined by using the first set thing in the following hierarchy: +;; - The `--work-path` flag passed to the binary +;; - The environment variable `$GITEA_WORK_DIR` +;; - A built-in value set at build time (see building from source) +;; - Otherwise it defaults to the directory of the _`AppPath`_ +;; - If any of the above are relative paths then they are made absolute against the +;; the directory of the _`AppPath`_ +;; - _`CustomPath`_: This is the base directory for custom templates and other options. +;; It is determined by using the first set thing in the following hierarchy: +;; - The `--custom-path` flag passed to the binary +;; - The environment variable `$GITEA_CUSTOM` +;; - A built-in value set at build time (see building from source) +;; - Otherwise it defaults to _`AppWorkPath`_`/custom` +;; - If any of the above are relative paths then they are made absolute against the +;; the directory of the _`AppWorkPath`_ +;; - _`CustomConf`_: This is the path to the `app.ini` file. +;; - The `--config` flag passed to the binary +;; - A built-in value set at build time (see building from source) +;; - Otherwise it defaults to _`CustomPath`_`/conf/app.ini` +;; - If any of the above are relative paths then they are made absolute against the +;; the directory of the _`CustomPath`_ +;; +;; In addition there is _`StaticRootPath`_ which can be set as a built-in at build time, but will otherwise default to _`AppWorkPath`_ + ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; General Settings ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -26,7 +58,7 @@ RUN_MODE = ; prod ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; -;; The protocol the server listens on. One of 'http', 'https', 'unix' or 'fcgi'. Defaults to 'http' +;; The protocol the server listens on. One of 'http', 'https', 'http+unix', 'fcgi' or 'fcgi+unix'. Defaults to 'http' ;PROTOCOL = http ;; ;; Expect PROXY protocol headers on connections @@ -51,6 +83,8 @@ RUN_MODE = ; prod ;STATIC_URL_PREFIX = ;; ;; The address to listen on. Either a IPv4/IPv6 address or the path to a unix socket. +;; If PROTOCOL is set to `http+unix` or `fcgi+unix`, this should be the name of the Unix socket file to use. +;; Relative paths will be made absolute against the _`AppWorkPath`_. ;HTTP_ADDR = 0.0.0.0 ;; ;; The port to listen on. Leave empty when using a unix socket. @@ -64,7 +98,7 @@ RUN_MODE = ; prod ;PORT_TO_REDIRECT = 80 ;; ;; expect PROXY protocol header on connections to https redirector. -;REDIRECTOR_USE_PROXY_PROTOCOL = %(USE_PROXY_PROTOCOL) +;REDIRECTOR_USE_PROXY_PROTOCOL = %(USE_PROXY_PROTOCOL)s ;; Minimum and maximum supported TLS versions ;SSL_MIN_VERSION=TLSv1.2 ;SSL_MAX_VERSION= @@ -91,7 +125,7 @@ RUN_MODE = ; prod ;LOCAL_ROOT_URL = %(PROTOCOL)s://%(HTTP_ADDR)s:%(HTTP_PORT)s/ ;; ;; When making local connections pass the PROXY protocol header. -;LOCAL_USE_PROXY_PROTOCOL = %(USE_PROXY_PROTOCOL) +;LOCAL_USE_PROXY_PROTOCOL = %(USE_PROXY_PROTOCOL)s ;; ;; Disable SSH feature when not available ;DISABLE_SSH = false @@ -145,7 +179,7 @@ RUN_MODE = ; prod ;; ;; For the built-in SSH server, choose the keypair to offer as the host key ;; The private key should be at SSH_SERVER_HOST_KEY and the public SSH_SERVER_HOST_KEY.pub -;; relative paths are made absolute relative to the APP_DATA_PATH +;; relative paths are made absolute relative to the %(APP_DATA_PATH)s ;SSH_SERVER_HOST_KEYS=ssh/gitea.rsa, ssh/gogs.rsa ;; ;; Directory to create temporary files in when testing public keys using ssh-keygen, @@ -241,10 +275,10 @@ RUN_MODE = ; prod ;; ;; Root directory containing templates and static files. ;; default is the path where Gitea is executed -;STATIC_ROOT_PATH = +;STATIC_ROOT_PATH = ; Will default to the built-in value _`StaticRootPath`_ ;; ;; Default path for App data -;APP_DATA_PATH = data +;APP_DATA_PATH = data ; relative paths will be made absolute with _`AppWorkPath`_ ;; ;; Enable gzip compression for runtime-generated content, static resources excluded ;ENABLE_GZIP = false @@ -255,7 +289,7 @@ RUN_MODE = ; prod ;ENABLE_PPROF = false ;; ;; PPROF_DATA_PATH, use an absolute path when you start gitea as service -;PPROF_DATA_PATH = data/tmp/pprof +;PPROF_DATA_PATH = data/tmp/pprof ; Path is relative to _`AppWorkPath`_ ;; ;; Landing page, can be "home", "explore", "organizations", "login", or any URL such as "/org/repo" or even "https://anotherwebsite.com" ;; The "login" choice is not a security measure but just a UI flow change, use REQUIRE_SIGNIN_VIEW to force users to log in. @@ -369,6 +403,9 @@ LOG_SQL = false ; if unset defaults to true ;; ;; Database maximum number of open connections, default is 0 meaning no maximum ;MAX_OPEN_CONNS = 0 +;; +;; Whether execute database models migrations automatically +;AUTO_MIGRATION = true ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -633,7 +670,7 @@ ROUTER = console ;PATH = ;; ;; The HOME directory for Git -;HOME_PATH = %(APP_DATA_PATH)/home +;HOME_PATH = %(APP_DATA_PATH)s/home ;; ;; Disables highlight of added and removed changes ;DISABLE_DIFF_HIGHLIGHT = false @@ -725,6 +762,9 @@ ROUTER = console ;; Enable captcha validation for registration ;ENABLE_CAPTCHA = false ;; +;; Enable this to require captcha validation for login +;REQUIRE_CAPTCHA_FOR_LOGIN = false +;; ;; Type of captcha you want to use. Options: image, recaptcha, hcaptcha, mcaptcha. ;CAPTCHA_TYPE = image ;; @@ -838,8 +878,8 @@ ROUTER = console ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;[repository] ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;; Root path for storing all repository data. By default, it is set to %(APP_DATA_PATH)/gitea-repositories. -;; A relative path is interpreted as %(GITEA_WORK_DIR)/%(ROOT) +;; Root path for storing all repository data. By default, it is set to %(APP_DATA_PATH)s/gitea-repositories. +;; A relative path is interpreted as _`AppWorkPath`_/%(ROOT)s ;ROOT = ;; ;; The script type this server supports. Usually this is `bash`, but some users report that only `sh` is available. @@ -1104,6 +1144,9 @@ ROUTER = console ;; allow request with credentials ;ALLOW_CREDENTIALS = false ;; +;; headers to permit +;HEADERS = Content-Type,User-Agent +;; ;; set X-FRAME-OPTIONS header ;X_FRAME_OPTIONS = SAMEORIGIN @@ -1296,7 +1339,7 @@ ROUTER = console ;ISSUE_INDEXER_TYPE = bleve ;; ;; Issue indexer storage path, available when ISSUE_INDEXER_TYPE is bleve -;ISSUE_INDEXER_PATH = indexers/issues.bleve +;ISSUE_INDEXER_PATH = indexers/issues.bleve ; Relative paths will be made absolute against _`AppWorkPath`_. ;; ;; Issue indexer connection string, available when ISSUE_INDEXER_TYPE is elasticsearch ;ISSUE_INDEXER_CONN_STR = http://elastic:changeme@localhost:9200 @@ -1314,7 +1357,7 @@ ROUTER = console ;; When ISSUE_INDEXER_QUEUE_TYPE is levelqueue, this will be the path where the queue will be saved. ;; This can be overridden by `ISSUE_INDEXER_QUEUE_CONN_STR`. ;; default is queues/common -;ISSUE_INDEXER_QUEUE_DIR = queues/common; **DEPRECATED** use settings in `[queue.issue_indexer]`. +;ISSUE_INDEXER_QUEUE_DIR = queues/common; **DEPRECATED** use settings in `[queue.issue_indexer]`. Relative paths will be made absolute against `%(APP_DATA_PATH)s`. ;; ;; When `ISSUE_INDEXER_QUEUE_TYPE` is `redis`, this will store the redis connection string. ;; When `ISSUE_INDEXER_QUEUE_TYPE` is `levelqueue`, this is a directory or additional options of @@ -1370,7 +1413,7 @@ ROUTER = console ;TYPE = persistable-channel ;; ;; data-dir for storing persistable queues and level queues, individual queues will default to `queues/common` meaning the queue is shared. -;DATADIR = queues/ +;DATADIR = queues/ ; Relative paths will be made absolute against `%(APP_DATA_PATH)s`. ;; ;; Default queue length before a channel queue will block ;LENGTH = 20 @@ -1550,7 +1593,7 @@ ROUTER = console ;; Prefix displayed before subject in mail ;SUBJECT_PREFIX = ;; -;; Mail server protocol. One of "smtp", "smtps", "smtp+startls", "smtp+unix", "sendmail", "dummy". +;; Mail server protocol. One of "smtp", "smtps", "smtp+starttls", "smtp+unix", "sendmail", "dummy". ;; - sendmail: use the operating system's `sendmail` command instead of SMTP. This is common on Linux systems. ;; - dummy: send email messages to the log as a testing phase. ;; If your provider does not explicitly say which protocol it uses but does provide a port, @@ -1672,7 +1715,7 @@ ROUTER = console ;; file: session file path, e.g. `data/sessions` ;; redis: network=tcp,addr=:6379,password=macaron,db=0,pool_size=100,idle_timeout=180 ;; mysql: go-sql-driver/mysql dsn config string, e.g. `root:password@/session_table` -;PROVIDER_CONFIG = data/sessions +;PROVIDER_CONFIG = data/sessions ; Relative paths will be made absolute against _`AppWorkPath`_. ;; ;; Session cookie name ;COOKIE_NAME = i_like_gitea @@ -2104,7 +2147,7 @@ ROUTER = console ;[cron.update_checker] ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; -;ENABLED = false +;ENABLED = true ;RUN_AT_START = false ;ENABLE_SUCCESS_NOTICE = false ;SCHEDULE = @every 168h @@ -2197,7 +2240,9 @@ ROUTER = console ;; Show template execution time in the footer ;SHOW_FOOTER_TEMPLATE_LOAD_TIME = true ;; Generate sitemap. Defaults to `true`. -; ENABLE_SITEMAP = true +;ENABLE_SITEMAP = true +;; Enable/Disable RSS/Atom feed +;ENABLE_FEED = true ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; @@ -2335,6 +2380,35 @@ ROUTER = console ;; ;; Path for chunked uploads. Defaults to APP_DATA_PATH + `tmp/package-upload` ;CHUNKED_UPLOAD_PATH = tmp/package-upload +;; +;; Maximum count of package versions a single owner can have (`-1` means no limits) +;LIMIT_TOTAL_OWNER_COUNT = -1 +;; Maximum size of packages a single owner can use (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +;LIMIT_TOTAL_OWNER_SIZE = -1 +;; Maximum size of a Composer upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +;LIMIT_SIZE_COMPOSER = -1 +;; Maximum size of a Conan upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +;LIMIT_SIZE_CONAN = -1 +;; Maximum size of a Container upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +;LIMIT_SIZE_CONTAINER = -1 +;; Maximum size of a Generic upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +;LIMIT_SIZE_GENERIC = -1 +;; Maximum size of a Helm upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +;LIMIT_SIZE_HELM = -1 +;; Maximum size of a Maven upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +;LIMIT_SIZE_MAVEN = -1 +;; Maximum size of a npm upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +;LIMIT_SIZE_NPM = -1 +;; Maximum size of a NuGet upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +;LIMIT_SIZE_NUGET = -1 +;; Maximum size of a Pub upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +;LIMIT_SIZE_PUB = -1 +;; Maximum size of a PyPI upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +;LIMIT_SIZE_PYPI = -1 +;; Maximum size of a RubyGems upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +;LIMIT_SIZE_RUBYGEMS = -1 +;; Maximum size of a Vagrant upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +;LIMIT_SIZE_VAGRANT = -1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; diff --git a/docs/config.yaml b/docs/config.yaml index 66bd379c0c..91afc2e972 100644 --- a/docs/config.yaml +++ b/docs/config.yaml @@ -23,6 +23,8 @@ params: goVersion: 1.19 minNodeVersion: 14 search: nav + repo: "https://github.com/go-gitea/gitea" + docContentPath: "docs/content" outputs: home: 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 df1911934c..dcf91c3396 100644 --- a/docs/content/doc/advanced/config-cheat-sheet.en-us.md +++ b/docs/content/doc/advanced/config-cheat-sheet.en-us.md @@ -27,23 +27,56 @@ accurately recorded in [app.example.ini](https://github.com/go-gitea/gitea/blob/ (s/main/\). Any string in the format `%(X)s` is a feature powered by [ini](https://github.com/go-ini/ini/#recursive-values), for reading values recursively. +In the default values below, a value in the form `$XYZ` refers to an environment variable. (However, see `environment-to-ini`.) Values in the form _`XxYyZz`_ refer to values listed as part of the default configuration. These notation forms will not work in your own `app.ini` file and are only listed here as documentation. + Values containing `#` or `;` must be quoted using `` ` `` or `"""`. **Note:** A full restart is required for Gitea configuration changes to take effect. {{< toc >}} +## Default Configuration (non-`app.ini` configuration) + +These values are environment-dependent but form the basis of a lot of values. They will be +reported as part of the default configuration when running `gitea --help` or on start-up. The order they are emitted there is slightly different but we will list them here in the order they are set-up. + +- _`AppPath`_: This is the absolute path of the running gitea binary. +- _`AppWorkPath`_: This refers to "working path" of the `gitea` binary. It is determined by using the first set thing in the following hierarchy: + - The `--work-path` flag passed to the binary + - The environment variable `$GITEA_WORK_DIR` + - A built-in value set at build time (see building from source) + - Otherwise it defaults to the directory of the _`AppPath`_ + - If any of the above are relative paths then they are made absolute against the +the directory of the _`AppPath`_ +- _`CustomPath`_: This is the base directory for custom templates and other options. +It is determined by using the first set thing in the following hierarchy: + - The `--custom-path` flag passed to the binary + - The environment variable `$GITEA_CUSTOM` + - A built-in value set at build time (see building from source) + - Otherwise it defaults to _`AppWorkPath`_`/custom` + - If any of the above are relative paths then they are made absolute against the +the directory of the _`AppWorkPath`_ +- _`CustomConf`_: This is the path to the `app.ini` file. + - The `--config` flag passed to the binary + - A built-in value set at build time (see building from source) + - Otherwise it defaults to _`CustomPath`_`/conf/app.ini` + - If any of the above are relative paths then they are made absolute against the +the directory of the _`CustomPath`_ + +In addition there is _`StaticRootPath`_ which can be set as a built-in at build time, but will otherwise default to _`AppWorkPath`_ + ## Overall (`DEFAULT`) - `APP_NAME`: **Gitea: Git with a cup of tea**: Application name, used in the page title. -- `RUN_USER`: **git**: The user Gitea will run as. This should be a dedicated system - (non-user) account. Setting this incorrectly will cause Gitea to not start. +- `RUN_USER`: **_current OS username_/`$USER`/`$USERNAME` e.g. git**: The user Gitea will run as. + This should be a dedicated system (non-user) account. Setting this incorrectly will cause Gitea + to not start. - `RUN_MODE`: **prod**: Application run mode, affects performance and debugging. Either "dev", "prod" or "test". ## Repository (`repository`) -- `ROOT`: **%(APP_DATA_PATH)/gitea-repositories**: Root path for storing all repository data. - A relative path is interpreted as **%(GITEA_WORK_DIR)/%(ROOT)**. +- `ROOT`: **%(APP_DATA_PATH)s/gitea-repositories**: Root path for storing all repository data. + A relative path is interpreted as **_`AppWorkPath`_/%(ROOT)s**. - `SCRIPT_TYPE`: **bash**: The script type this server supports. Usually this is `bash`, but some users report that only `sh` is available. - `DETECTED_CHARSETS_ORDER`: **UTF-8, UTF-16BE, UTF-16LE, UTF-32BE, UTF-32LE, ISO-8859, windows-1252, ISO-8859, windows-1250, ISO-8859, ISO-8859, ISO-8859, windows-1253, ISO-8859, windows-1255, ISO-8859, windows-1251, windows-1256, KOI8-R, ISO-8859, windows-1254, Shift_JIS, GB18030, EUC-JP, EUC-KR, Big5, ISO-2022, ISO-2022, ISO-2022, IBM424_rtl, IBM424_ltr, IBM420_rtl, IBM420_ltr**: Tie-break order of detected charsets - if the detected charsets have equal confidence, charsets earlier in the list will be chosen in preference to those later. Adding `defaults` will place the unnamed charsets at that point. @@ -167,6 +200,7 @@ The following configuration set `Content-Type: application/vnd.android.package-a - `METHODS`: **GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS**: list of methods allowed to request - `MAX_AGE`: **10m**: max time to cache response - `ALLOW_CREDENTIALS`: **false**: allow request with credentials +- `HEADERS`: **Content-Type,User-Agent**: additional headers that are permitted in requests - `X_FRAME_OPTIONS`: **SAMEORIGIN**: Set the `X-Frame-Options` header value. ## UI (`ui`) @@ -240,6 +274,7 @@ The following configuration set `Content-Type: application/vnd.android.package-a ## Server (`server`) +- `APP_DATA_PATH`: **_`AppWorkPath`_/data**: This is the default root path for storing data. - `PROTOCOL`: **http**: \[http, https, fcgi, http+unix, fcgi+unix\] - `USE_PROXY_PROTOCOL`: **false**: Expect PROXY protocol headers on connections - `PROXY_PROTOCOL_TLS_BRIDGING`: **false**: When protocol is https, expect PROXY protocol headers after TLS negotiation. @@ -254,12 +289,17 @@ The following configuration set `Content-Type: application/vnd.android.package-a This includes CSS files, images, JS files and web fonts. Avatar images are dynamic resources and still served by Gitea. The option can be just a different path, as in `/static`, or another domain, as in `https://cdn.example.com`. - Requests are then made as `%(ROOT_URL)s/static/css/index.css` and `https://cdn.example.com/css/index.css` respective. + Requests are then made as `%(ROOT_URL)s/static/assets/css/index.css` or `https://cdn.example.com/assets/css/index.css` respectively. The static files are located in the `public/` directory of the Gitea source repository. + You can proxy the STATIC_URL_PREFIX requests to Gitea server to serve the static + assets, or copy the manually built Gitea assets from `$GITEA_BUILD/public` to + the assets location, eg: `/var/www/assets`, make sure `$STATIC_URL_PREFIX/assets/css/index.css` + points to `/var/www/assets/css/index.css`. + - `HTTP_ADDR`: **0.0.0.0**: HTTP listen address. - If `PROTOCOL` is set to `fcgi`, Gitea will listen for FastCGI requests on TCP socket defined by `HTTP_ADDR` and `HTTP_PORT` configuration settings. - - If `PROTOCOL` is set to `http+unix` or `fcgi+unix`, this should be the name of the Unix socket file to use. Relative paths will be made absolute against the AppWorkPath. + - If `PROTOCOL` is set to `http+unix` or `fcgi+unix`, this should be the name of the Unix socket file to use. Relative paths will be made absolute against the _`AppWorkPath`_. - `HTTP_PORT`: **3000**: HTTP listen port. - If `PROTOCOL` is set to `fcgi`, Gitea will listen for FastCGI requests on TCP socket defined by `HTTP_ADDR` and `HTTP_PORT` configuration settings. @@ -269,7 +309,7 @@ The following configuration set `Content-Type: application/vnd.android.package-a most cases you do not need to change the default value. Alter it only if your SSH server node is not the same as HTTP node. Do not set this variable if `PROTOCOL` is set to `http+unix`. -- `LOCAL_USE_PROXY_PROTOCOL`: **%(USE_PROXY_PROTOCOL)**: When making local connections pass the PROXY protocol header. +- `LOCAL_USE_PROXY_PROTOCOL`: **%(USE_PROXY_PROTOCOL)s**: When making local connections pass the PROXY protocol header. This should be set to false if the local connection will go through the proxy. - `PER_WRITE_TIMEOUT`: **30s**: Timeout for any write to the connection. (Set to -1 to disable all timeouts.) @@ -279,7 +319,7 @@ The following configuration set `Content-Type: application/vnd.android.package-a - `START_SSH_SERVER`: **false**: When enabled, use the built-in SSH server. - `SSH_SERVER_USE_PROXY_PROTOCOL`: **false**: Expect PROXY protocol header on connections to the built-in SSH Server. - `BUILTIN_SSH_SERVER_USER`: **%(RUN_USER)s**: Username to use for the built-in SSH Server. -- `SSH_USER`: **%(BUILTIN_SSH_SERVER_USER)**: SSH username displayed in clone URLs. This is only for people who configure the SSH server themselves; in most cases, you want to leave this blank and modify the `BUILTIN_SSH_SERVER_USER`. +- `SSH_USER`: **%(BUILTIN_SSH_SERVER_USER)s**: SSH username displayed in clone URLs. This is only for people who configure the SSH server themselves; in most cases, you want to leave this blank and modify the `BUILTIN_SSH_SERVER_USER`. - `SSH_DOMAIN`: **%(DOMAIN)s**: Domain name of this server, used for displayed clone URL. - `SSH_PORT`: **22**: SSH port displayed in clone URL. - `SSH_LISTEN_HOST`: **0.0.0.0**: Listen address for the built-in SSH server. @@ -308,22 +348,22 @@ The following configuration set `Content-Type: application/vnd.android.package-a - `OFFLINE_MODE`: **false**: Disables use of CDN for static files and Gravatar for profile pictures. - `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). This is ignored if `ENABLE_ACME=true`. Paths are relative to `CUSTOM_PATH`. - `KEY_FILE`: **https/key.pem**: Key file path used for HTTPS. This is ignored if `ENABLE_ACME=true`. Paths are relative to `CUSTOM_PATH`. -- `STATIC_ROOT_PATH`: **./**: Upper level of template and static files path. -- `APP_DATA_PATH`: **data** (**/data/gitea** on docker): Default path for application data. +- `STATIC_ROOT_PATH`: **_`StaticRootPath`_**: Upper level of template and static files path. +- `APP_DATA_PATH`: **data** (**/data/gitea** on docker): Default path for application data. Relative paths will be made absolute against _`AppWorkPath`_. - `STATIC_CACHE_TIME`: **6h**: Web browser cache time for static resources on `custom/`, `public/` and all uploaded avatars. Note that this cache is disabled when `RUN_MODE` is "dev". - `ENABLE_GZIP`: **false**: Enable gzip compression for runtime-generated content, static resources excluded. - `ENABLE_PPROF`: **false**: Application profiling (memory and cpu). For "web" command it listens on `localhost:6060`. For "serv" command it dumps to disk at `PPROF_DATA_PATH` as `(cpuprofile|memprofile)__` -- `PPROF_DATA_PATH`: **data/tmp/pprof**: `PPROF_DATA_PATH`, use an absolute path when you start Gitea as service +- `PPROF_DATA_PATH`: **_`AppWorkPath`_/data/tmp/pprof**: `PPROF_DATA_PATH`, use an absolute path when you start Gitea as service - `LANDING_PAGE`: **home**: Landing page for unauthenticated users \[home, explore, organizations, login, **custom**\]. Where custom would instead be any URL such as "/org/repo" or even `https://anotherwebsite.com` - `LFS_START_SERVER`: **false**: Enables Git LFS support. -- `LFS_CONTENT_PATH`: **%(APP_DATA_PATH)/lfs**: Default LFS content path. (if it is on local storage.) **DEPRECATED** use settings in `[lfs]`. +- `LFS_CONTENT_PATH`: **%(APP_DATA_PATH)s/lfs**: Default LFS content path. (if it is on local storage.) **DEPRECATED** use settings in `[lfs]`. - `LFS_JWT_SECRET`: **\**: LFS authentication secret, change this a unique string. - `LFS_HTTP_AUTH_EXPIRY`: **20m**: LFS authentication validity period in time.Duration, pushes taking longer than this may fail. - `LFS_MAX_FILE_SIZE`: **0**: Maximum allowed LFS file size in bytes (Set to 0 for no limit). - `LFS_LOCKS_PAGING_NUM`: **50**: Maximum number of LFS Locks returned per page. - `REDIRECT_OTHER_PORT`: **false**: If true and `PROTOCOL` is https, allows redirecting http requests on `PORT_TO_REDIRECT` to the https port Gitea listens on. -- `REDIRECTOR_USE_PROXY_PROTOCOL`: **%(USE_PROXY_PROTOCOL)**: expect PROXY protocol header on connections to https redirector. +- `REDIRECTOR_USE_PROXY_PROTOCOL`: **%(USE_PROXY_PROTOCOL)s**: expect PROXY protocol header on connections to https redirector. - `PORT_TO_REDIRECT`: **80**: Port for the http redirection service to listen on. Used when `REDIRECT_OTHER_PORT` is true. - `SSL_MIN_VERSION`: **TLSv1.2**: Set the minimum version of ssl support. - `SSL_MAX_VERSION`: **\**: Set the maximum version of ssl support. @@ -404,6 +444,7 @@ The following configuration set `Content-Type: application/vnd.android.package-a - `MAX_OPEN_CONNS` **0**: Database maximum open connections - default is 0, meaning there is no limit. - `MAX_IDLE_CONNS` **2**: Max idle database connections on connection pool, default is 2 - this will be capped to `MAX_OPEN_CONNS`. - `CONN_MAX_LIFETIME` **0 or 3s**: Sets the maximum amount of time a DB connection may be reused - default is 0, meaning there is no limit (except on MySQL where it is 3s - see #6804 & #7071). +- `AUTO_MIGRATION` **true**: Whether execute database models migrations automatically. Please see #8540 & #8273 for further discussion of the appropriate values for `MAX_OPEN_CONNS`, `MAX_IDLE_CONNS` & `CONN_MAX_LIFETIME` and their relation to port exhaustion. @@ -413,10 +454,10 @@ relation to port exhaustion. - `ISSUE_INDEXER_TYPE`: **bleve**: Issue indexer type, currently supported: `bleve`, `db` or `elasticsearch`. - `ISSUE_INDEXER_CONN_STR`: ****: Issue indexer connection string, available when ISSUE_INDEXER_TYPE is elasticsearch. i.e. http://elastic:changeme@localhost:9200 - `ISSUE_INDEXER_NAME`: **gitea_issues**: Issue indexer name, available when ISSUE_INDEXER_TYPE is elasticsearch -- `ISSUE_INDEXER_PATH`: **indexers/issues.bleve**: Index file used for issue search; available when ISSUE_INDEXER_TYPE is bleve and elasticsearch. +- `ISSUE_INDEXER_PATH`: **indexers/issues.bleve**: Index file used for issue search; available when ISSUE_INDEXER_TYPE is bleve and elasticsearch. Relative paths will be made absolute against _`AppWorkPath`_. - The next 4 configuration values are deprecated and should be set in `queue.issue_indexer` however are kept for backwards compatibility: - `ISSUE_INDEXER_QUEUE_TYPE`: **levelqueue**: Issue indexer queue, currently supports:`channel`, `levelqueue`, `redis`. **DEPRECATED** use settings in `[queue.issue_indexer]`. -- `ISSUE_INDEXER_QUEUE_DIR`: **queues/common**: When `ISSUE_INDEXER_QUEUE_TYPE` is `levelqueue`, this will be the path where the queue will be saved. **DEPRECATED** use settings in `[queue.issue_indexer]`. +- `ISSUE_INDEXER_QUEUE_DIR`: **queues/common**: When `ISSUE_INDEXER_QUEUE_TYPE` is `levelqueue`, this will be the path where the queue will be saved. **DEPRECATED** use settings in `[queue.issue_indexer]`. Relative paths will be made absolute against `%(APP_DATA_PATH)s`. - `ISSUE_INDEXER_QUEUE_CONN_STR`: **addrs=127.0.0.1:6379 db=0**: When `ISSUE_INDEXER_QUEUE_TYPE` is `redis`, this will store the redis connection string. When `ISSUE_INDEXER_QUEUE_TYPE` is `levelqueue`, this is a directory or additional options of the form `leveldb://path/to/db?option=value&....`, and overrides `ISSUE_INDEXER_QUEUE_DIR`. **DEPRECATED** use settings in `[queue.issue_indexer]`. - `ISSUE_INDEXER_QUEUE_BATCH_NUMBER`: **20**: Batch queue number. **DEPRECATED** use settings in `[queue.issue_indexer]`. @@ -438,7 +479,7 @@ relation to port exhaustion. Configuration at `[queue]` will set defaults for queues with overrides for individual queues at `[queue.*]`. (However see below.) - `TYPE`: **persistable-channel**: General queue type, currently support: `persistable-channel` (uses a LevelDB internally), `channel`, `level`, `redis`, `dummy` -- `DATADIR`: **queues/**: Base DataDir for storing persistent and level queues. `DATADIR` for individual queues can be set in `queue.name` sections but will default to `DATADIR/`**`common`**. (Previously each queue would default to `DATADIR/`**`name`**.) +- `DATADIR`: **queues/**: Base DataDir for storing persistent and level queues. `DATADIR` for individual queues can be set in `queue.name` sections but will default to `DATADIR/`**`common`**. (Previously each queue would default to `DATADIR/`**`name`**.) Relative paths will be made absolute against `%(APP_DATA_PATH)s`. - `LENGTH`: **20**: Maximal queue size before channel queues block - `BATCH_LENGTH`: **20**: Batch data before passing to the handler - `CONN_STR`: **redis://127.0.0.1:6379/0**: Connection string for the redis queue type. Options can be set using query params. Similarly LevelDB options can also be set using: **leveldb://relative/path?option=value** or **leveldb:///absolute/path?option=value**, and will override `DATADIR` @@ -594,6 +635,7 @@ Certain queues have defaults that override the defaults set in `[queue]` (this o - `ENABLE_REVERSE_PROXY_FULL_NAME`: **false**: Enable this to allow to auto-registration with a provided full name for the user. - `ENABLE_CAPTCHA`: **false**: Enable this to use captcha validation for registration. +- `REQUIRE_CAPTCHA_FOR_LOGIN`: **false**: Enable this to require captcha validation for login. You also must enable `ENABLE_CAPTCHA`. - `REQUIRE_EXTERNAL_REGISTRATION_CAPTCHA`: **false**: Enable this to force captcha validation even for External Accounts (i.e. GitHub, OpenID Connect, etc). You also must enable `ENABLE_CAPTCHA`. - `CAPTCHA_TYPE`: **image**: \[image, recaptcha, hcaptcha, mcaptcha\] @@ -672,7 +714,7 @@ and [Gitea 1.17 configuration document](https://github.com/go-gitea/gitea/blob/release/v1.17/docs/content/doc/advanced/config-cheat-sheet.en-us.md) - `ENABLED`: **false**: Enable to use a mail service. -- `PROTOCOL`: **\**: Mail server protocol. One of "smtp", "smtps", "smtp+startls", "smtp+unix", "sendmail", "dummy". _Before 1.18, this was inferred from a combination of `MAILER_TYPE` and `IS_TLS_ENABLED`._ +- `PROTOCOL`: **\**: Mail server protocol. One of "smtp", "smtps", "smtp+starttls", "smtp+unix", "sendmail", "dummy". _Before 1.18, this was inferred from a combination of `MAILER_TYPE` and `IS_TLS_ENABLED`._ - SMTP family, if your provider does not explicitly say which protocol it uses but does provide a port, you can set SMTP_PORT instead and this will be inferred. - **sendmail** Use the operating system's `sendmail` command instead of SMTP. This is common on Linux systems. - **dummy** Send email messages to the log as a testing phase. @@ -722,7 +764,7 @@ and ## Session (`session`) - `PROVIDER`: **memory**: Session engine provider \[memory, file, redis, db, mysql, couchbase, memcache, postgres\]. Setting `db` will reuse the configuration in `[database]` -- `PROVIDER_CONFIG`: **data/sessions**: For file, the root path; for db, empty (database config will be used); for others, the connection string. +- `PROVIDER_CONFIG`: **data/sessions**: For file, the root path; for db, empty (database config will be used); for others, the connection string. Relative paths will be made absolute against _`AppWorkPath`_. - `COOKIE_SECURE`: **false**: Enable this to force using HTTPS for all session access. - `COOKIE_NAME`: **i\_like\_gitea**: The name of the cookie used for the session ID. - `GC_INTERVAL_TIME`: **86400**: GC interval in seconds. @@ -963,7 +1005,7 @@ Default templates for project boards: #### Cron - Check for new Gitea versions ('cron.update_checker') -- `ENABLED`: **false**: Enable service. +- `ENABLED`: **true**: Enable service. - `RUN_AT_START`: **false**: Run tasks at start up time (if ENABLED). - `ENABLE_SUCCESS_NOTICE`: **true**: Set to false to switch off success notices. - `SCHEDULE`: **@every 168h**: Cron syntax for scheduling a work, e.g. `@every 168h`. @@ -980,7 +1022,7 @@ Default templates for project boards: ## Git (`git`) - `PATH`: **""**: The path of Git executable. If empty, Gitea searches through the PATH environment. -- `HOME_PATH`: **%(APP_DATA_PATH)/home**: The HOME directory for Git. +- `HOME_PATH`: **%(APP_DATA_PATH)s/home**: The HOME directory for Git. This directory will be used to contain the `.gitconfig` and possible `.gnupg` directories that Gitea's git calls will use. If you can confirm Gitea is the only application running in this environment, you can set it to the normal home directory for Gitea user. - `DISABLE_DIFF_HIGHLIGHT`: **false**: Disables highlight of added and removed changes. - `MAX_GIT_DIFF_LINES`: **1000**: Max number of lines allowed of a single file in diff view. @@ -1138,6 +1180,20 @@ Task queue configuration has been moved to `queue.task`. However, the below conf - `ENABLED`: **true**: Enable/Disable package registry capabilities - `CHUNKED_UPLOAD_PATH`: **tmp/package-upload**: Path for chunked uploads. Defaults to `APP_DATA_PATH` + `tmp/package-upload` +- `LIMIT_TOTAL_OWNER_COUNT`: **-1**: Maximum count of package versions a single owner can have (`-1` means no limits) +- `LIMIT_TOTAL_OWNER_SIZE`: **-1**: Maximum size of packages a single owner can use (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +- `LIMIT_SIZE_COMPOSER`: **-1**: Maximum size of a Composer upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +- `LIMIT_SIZE_CONAN`: **-1**: Maximum size of a Conan upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +- `LIMIT_SIZE_CONTAINER`: **-1**: Maximum size of a Container upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +- `LIMIT_SIZE_GENERIC`: **-1**: Maximum size of a Generic upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +- `LIMIT_SIZE_HELM`: **-1**: Maximum size of a Helm upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +- `LIMIT_SIZE_MAVEN`: **-1**: Maximum size of a Maven upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +- `LIMIT_SIZE_NPM`: **-1**: Maximum size of a npm upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +- `LIMIT_SIZE_NUGET`: **-1**: Maximum size of a NuGet upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +- `LIMIT_SIZE_PUB`: **-1**: Maximum size of a Pub upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +- `LIMIT_SIZE_PYPI`: **-1**: Maximum size of a PyPI upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +- `LIMIT_SIZE_RUBYGEMS`: **-1**: Maximum size of a RubyGems upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) +- `LIMIT_SIZE_VAGRANT`: **-1**: Maximum size of a Vagrant upload (`-1` means no limits, format `1000`, `1 MB`, `1 GiB`) ## Mirror (`mirror`) @@ -1234,3 +1290,4 @@ PROXY_HOSTS = *.github.com - `SHOW_FOOTER_VERSION`: **true**: Show Gitea and Go version information in the footer. - `SHOW_FOOTER_TEMPLATE_LOAD_TIME`: **true**: Show time of template execution in the footer. - `ENABLE_SITEMAP`: **true**: Generate sitemap. +- `ENABLE_FEED`: **true**: Enable/Disable RSS/Atom feed. diff --git a/docs/content/doc/advanced/config-cheat-sheet.zh-cn.md b/docs/content/doc/advanced/config-cheat-sheet.zh-cn.md index 576007f75b..f10b6258c8 100644 --- a/docs/content/doc/advanced/config-cheat-sheet.zh-cn.md +++ b/docs/content/doc/advanced/config-cheat-sheet.zh-cn.md @@ -145,7 +145,8 @@ menu: - `ENABLE_NOTIFY_MAIL`: 是否发送工单创建等提醒邮件,需要 `Mailer` 被激活。 - `ENABLE_REVERSE_PROXY_AUTHENTICATION`: 允许反向代理认证,更多细节见:https://github.com/gogits/gogs/issues/165 - `ENABLE_REVERSE_PROXY_AUTO_REGISTRATION`: 允许通过反向认证做自动注册。 -- `ENABLE_CAPTCHA`: 注册时使用图片验证码。 +- `ENABLE_CAPTCHA`: **false**: 注册时使用图片验证码。 +- `REQUIRE_CAPTCHA_FOR_LOGIN`: **false**: 登录时需要图片验证码。需要同时开启 `ENABLE_CAPTCHA`。 ### Service - Expore (`service.explore`) diff --git a/docs/content/doc/advanced/logging-documentation.en-us.md b/docs/content/doc/advanced/logging-documentation.en-us.md index 4e8cbb3282..145c8c320c 100644 --- a/docs/content/doc/advanced/logging-documentation.en-us.md +++ b/docs/content/doc/advanced/logging-documentation.en-us.md @@ -15,6 +15,14 @@ menu: # Logging Configuration +The logging configuration of Gitea mainly consists of 3 types of components: + +- The `[log]` section for general configuration +- `[log.]` sections for the configuration of different log outputs +- `[log..]` sections for output specific configuration of a log group + +As mentioned below, there is a fully functional log output by default, so it is not necessary to define one. + **Table of Contents** {{< toc >}} @@ -23,6 +31,166 @@ menu: To collect logs for help and issue report, see [Support Options]({{< relref "doc/help/seek-help.en-us.md" >}}). +## The `[log]` section + +Configuration of logging facilities in Gitea happen in the `[log]` section and it's subsections. + +In the top level `[log]` section the following configurations can be placed: + +- `ROOT_PATH`: (Default: **%(GITEA_WORK_DIR)/log**): Base path for log files +- `MODE`: (Default: **console**) List of log outputs to use for the Default logger. +- `ROUTER`: (Default: **console**): List of log outputs to use for the Router logger. +- `ACCESS`: List of log outputs to use for the Access logger. +- `XORM`: (Default: **,**) List of log outputs to use for the XORM logger. +- `ENABLE_ACCESS_LOG`: (Default: **false**): whether the Access logger is allowed to emit logs +- `ENABLE_XORM_LOG`: (Default: **true**): whether the XORM logger is allowed to emit logs + +For details on the loggers check the "Log Groups" section. +Important: log outputs won't be used if you don't enable them for the desired loggers in the corresponding list value. + +Lists are specified as comma separated values. This format also works in subsection. + +This section may be used for defining default values for subsections. +Examples: + +- `LEVEL`: (Default: **Info**) Least severe log events to persist. Case insensitive. The full list of levels as of v1.17.3 can be read [here](https://github.com/go-gitea/gitea/blob/v1.17.3/custom/conf/app.example.ini#L507). +- `STACKTRACE_LEVEL`: (Default: **None**) For this and more severe events the stacktrace will be printed upon getting logged. + +Some values are not inherited by subsections. For details see the "Non-inherited default values" section. + +## Log outputs + +Log outputs are the targets to which log messages will be sent. +The content and the format of the log messages to be saved can be configured in these. + +Log outputs are also called subloggers. + +Gitea provides 4 possible log outputs: + +- `console` - Log to `os.Stdout` or `os.Stderr` +- `file` - Log to a file +- `conn` - Log to a socket (network or unix) +- `smtp` - Log via email + +By default, Gitea has a `console` output configured, which is used by the loggers as seen in the section "The log section" above. + +### Common configuration + +Certain configuration is common to all modes of log output: + +- `MODE` is the mode of the log output. It will default to the sublogger + name, thus `[log.console.router]` will default to `MODE = console`. + For mode specific confgurations read further. +- `LEVEL` is the lowest level that this output will log. This value + is inherited from `[log]` and in the case of the non-default loggers + from `[log.sublogger]`. +- `STACKTRACE_LEVEL` is the lowest level that this output will print + a stacktrace. This value is inherited. +- `COLORIZE` will default to `true` for `console` as + described, otherwise it will default to `false`. + +### Non-inherited default values + +There are several values which are not inherited as described above but +rather default to those specific to type of logger, these are: +`EXPRESSION`, `FLAGS`, `PREFIX` and `FILE_NAME`. + +#### `EXPRESSION` + +`EXPRESSION` represents a regular expression that log events must match to be logged by the sublogger. Either the log message, (with colors removed), must match or the `longfilename:linenumber:functionname` must match. NB: the whole message or string doesn't need to completely match. + +Please note this expression will be run in the sublogger's goroutine +not the logging event subroutine. Therefore it can be complicated. + +#### `FLAGS` + +`FLAGS` represents the preceding logging context information that is +printed before each message. It is a comma-separated string set. The order of values does not matter. + +Possible values are: + +- `none` or `,` - No flags. +- `date` - the date in the local time zone: `2009/01/23`. +- `time` - the time in the local time zone: `01:23:23`. +- `microseconds` - microsecond resolution: `01:23:23.123123`. Assumes + time. +- `longfile` - full file name and line number: `/a/b/c/d.go:23`. +- `shortfile` - final file name element and line number: `d.go:23`. +- `funcname` - function name of the caller: `runtime.Caller()`. +- `shortfuncname` - last part of the function name. Overrides + `funcname`. +- `utc` - if date or time is set, use UTC rather than the local time + zone. +- `levelinitial` - Initial character of the provided level in brackets eg. `[I]` for info. +- `level` - Provided level in brackets `[INFO]` +- `medfile` - Last 20 characters of the filename - equivalent to + `shortfile,longfile`. +- `stdflags` - Equivalent to `date,time,medfile,shortfuncname,levelinitial` + +### Console mode + +In this mode the logger will forward log messages to the stdout and +stderr streams attached to the Gitea process. + +For loggers in console mode, `COLORIZE` will default to `true` if not +on windows, or the windows terminal can be set into ANSI mode or is a +cygwin or Msys pipe. + +Settings: + +- `STDERR`: **false**: Whether the logger should print to `stderr` instead of `stdout`. + +### File mode + +In this mode the logger will save log messages to a file. + +Settings: + +- `FILE_NAME`: The file to write the log events to. For details see below. +- `MAX_SIZE_SHIFT`: **28**: Maximum size shift of a single file. 28 represents 256Mb. For details see below. +- `LOG_ROTATE` **true**: Whether to rotate the log files. TODO: if false, will it delete instead on daily rotate, or do nothing?. +- `DAILY_ROTATE`: **true**: Whether to rotate logs daily. +- `MAX_DAYS`: **7**: Delete rotated log files after this number of days. +- `COMPRESS`: **true**: Whether to compress old log files by default with gzip. +- `COMPRESSION_LEVEL`: **-1**: Compression level. For details see below. + +The default value of `FILE_NAME` depends on the respective logger facility. +If unset, their own default will be used. +If set it will be relative to the provided `ROOT_PATH` in the master `[log]` section. + +`MAX_SIZE_SHIFT` defines the maximum size of a file by left shifting 1 the given number of times (`1 << x`). +The exact behavior at the time of v1.17.3 can be seen [here](https://github.com/go-gitea/gitea/blob/v1.17.3/modules/setting/log.go#L185). + +The useful values of `COMPRESSION_LEVEL` are from 1 to (and including) 9, where higher numbers mean better compression. +Beware that better compression might come with higher resource usage. +Must be preceded with a `-` sign. + +### Conn mode + +In this mode the logger will send log messages over a network socket. + +Settings: + +- `ADDR`: **:7020**: Sets the address to connect to. +- `PROTOCOL`: **tcp**: Set the protocol, either "tcp", "unix" or "udp". +- `RECONNECT`: **false**: Try to reconnect when connection is lost. +- `RECONNECT_ON_MSG`: **false**: Reconnect host for every single message. + +### SMTP mode + +In this mode the logger will send log messages in email. + +It is not recommended to use this logger to send general logging +messages. However, you could perhaps set this logger to work on `FATAL` messages only. + +Settings: + +- `HOST`: **127.0.0.1:25**: The SMTP host to connect to. +- `USER`: User email address to send from. +- `PASSWD`: Password for the smtp server. +- `RECEIVERS`: Email addresses to send to. +- `SUBJECT`: **Diagnostic message from Gitea**. The content of the email's subject field. + ## Log Groups The fundamental thing to be aware of in Gitea is that there are several @@ -172,106 +340,6 @@ which will not be inherited from the `[log]` or relevant - `EXPRESSION` will default to `""` - `PREFIX` will default to `""` -## Log outputs - -Gitea provides 4 possible log outputs: - -- `console` - Log to `os.Stdout` or `os.Stderr` -- `file` - Log to a file -- `conn` - Log to a keep-alive TCP connection -- `smtp` - Log via email - -Certain configuration is common to all modes of log output: - -- `LEVEL` is the lowest level that this output will log. This value - is inherited from `[log]` and in the case of the non-default loggers - from `[log.sublogger]`. -- `STACKTRACE_LEVEL` is the lowest level that this output will print - a stacktrace. This value is inherited. -- `MODE` is the mode of the log output. It will default to the sublogger - name. Thus `[log.console.router]` will default to `MODE = console`. -- `COLORIZE` will default to `true` for `console` as - described, otherwise it will default to `false`. - -### Non-inherited default values - -There are several values which are not inherited as described above but -rather default to those specific to type of logger, these are: -`EXPRESSION`, `FLAGS`, `PREFIX` and `FILE_NAME`. - -#### `EXPRESSION` - -`EXPRESSION` represents a regular expression that log events must match to be logged by the sublogger. Either the log message, (with colors removed), must match or the `longfilename:linenumber:functionname` must match. NB: the whole message or string doesn't need to completely match. - -Please note this expression will be run in the sublogger's goroutine -not the logging event subroutine. Therefore it can be complicated. - -#### `FLAGS` - -`FLAGS` represents the preceding logging context information that is -printed before each message. It is a comma-separated string set. The order of values does not matter. - -Possible values are: - -- `none` or `,` - No flags. -- `date` - the date in the local time zone: `2009/01/23`. -- `time` - the time in the local time zone: `01:23:23`. -- `microseconds` - microsecond resolution: `01:23:23.123123`. Assumes - time. -- `longfile` - full file name and line number: `/a/b/c/d.go:23`. -- `shortfile` - final file name element and line number: `d.go:23`. -- `funcname` - function name of the caller: `runtime.Caller()`. -- `shortfuncname` - last part of the function name. Overrides - `funcname`. -- `utc` - if date or time is set, use UTC rather than the local time - zone. -- `levelinitial` - Initial character of the provided level in brackets eg. `[I]` for info. -- `level` - Provided level in brackets `[INFO]` -- `medfile` - Last 20 characters of the filename - equivalent to - `shortfile,longfile`. -- `stdflags` - Equivalent to `date,time,medfile,shortfuncname,levelinitial` - -### Console mode - -For loggers in console mode, `COLORIZE` will default to `true` if not -on windows, or the windows terminal can be set into ANSI mode or is a -cygwin or Msys pipe. - -If `STDERR` is set to `true` the logger will use `os.Stderr` instead of -`os.Stdout`. - -### File mode - -The `FILE_NAME` defaults as described above. If set it will be relative -to the provided `ROOT_PATH` in the master `[log]` section. - -Other values: - -- `LOG_ROTATE`: **true**: Rotate the log files. -- `MAX_SIZE_SHIFT`: **28**: Maximum size shift of a single file, 28 represents 256Mb. -- `DAILY_ROTATE`: **true**: Rotate logs daily. -- `MAX_DAYS`: **7**: Delete the log file after n days -- `COMPRESS`: **true**: Compress old log files by default with gzip -- `COMPRESSION_LEVEL`: **-1**: Compression level - -### Conn mode - -- `RECONNECT_ON_MSG`: **false**: Reconnect host for every single message. -- `RECONNECT`: **false**: Try to reconnect when connection is lost. -- `PROTOCOL`: **tcp**: Set the protocol, either "tcp", "unix" or "udp". -- `ADDR`: **:7020**: Sets the address to connect to. - -### SMTP mode - -It is not recommended to use this logger to send general logging -messages. However, you could perhaps set this logger to work on `FATAL`. - -- `USER`: User email address to send from. -- `PASSWD`: Password for the smtp server. -- `HOST`: **127.0.0.1:25**: The SMTP host to connect to. -- `RECEIVERS`: Email addresses to send to. -- `SUBJECT`: **Diagnostic message from Gitea** - ## Debugging problems When submitting logs in Gitea issues it is often helpful to submit diff --git a/docs/content/doc/advanced/repo-mirror.en-us.md b/docs/content/doc/advanced/repo-mirror.en-us.md index c1d794762a..e95dfa0d63 100644 --- a/docs/content/doc/advanced/repo-mirror.en-us.md +++ b/docs/content/doc/advanced/repo-mirror.en-us.md @@ -41,13 +41,15 @@ For an existing remote repository, you can set up pull mirroring as follows: The repository now gets mirrored periodically from the remote repository. You can force a sync by selecting **Synchronize Now** in the repository settings. +:exclamation::exclamation: **NOTE:** You can only set up pull mirroring for repos that don't exist yet on your instance. Once the repo is created, you can't convert it into a pull mirror anymore. :exclamation::exclamation: + ## Pushing to a remote repository For an existing repository, you can set up push mirroring as follows: 1. In your repository, go to **Settings** > **Repository**, and then the **Mirror Settings** section. 2. Enter a repository URL. -3. If the repository needs authentication expand the **Authorization** section and fill in your authentication information. +3. If the repository needs authentication expand the **Authorization** section and fill in your authentication information. Note that the requested **password** can also be your access token. 4. Select **Add Push Mirror** to save the configuration. The repository now gets mirrored periodically to the remote repository. You can force a sync by selecting **Synchronize Now**. In case of an error a message displayed to help you resolve it. @@ -59,9 +61,11 @@ The repository now gets mirrored periodically to the remote repository. You can To set up a mirror from Gitea to GitHub, you need to follow these steps: 1. Create a [GitHub personal access token](https://docs.github.com/en/github/authenticating-to-github/creating-a-personal-access-token) with the *public_repo* box checked. -2. Fill in the **Git Remote Repository URL**: `https://github.com//.git`. -3. Fill in the **Authorization** fields with your GitHub username and the personal access token. -4. Select **Add Push Mirror** to save the configuration. +2. Create a repository with that name on GitHub. Unlike Gitea, GitHub does not support creating repositories by pushing to the remote. You can also use an existing remote repo if it has the same commit history as your Gitea repo. +3. In the settings of your Gitea repo, fill in the **Git Remote Repository URL**: `https://github.com//.git`. +4. Fill in the **Authorization** fields with your GitHub username and the personal access token as **Password**. +5. (Optional, available on Gitea 1.18+) Select `Sync when new commits are pushed` so that the mirror will be updated as well as soon as there are changes. You can also disable the periodic sync if you like. +6. Select **Add Push Mirror** to save the configuration. The repository pushes shortly thereafter. To force a push, select the **Synchronize Now** button. diff --git a/docs/content/doc/features/authentication.en-us.md b/docs/content/doc/features/authentication.en-us.md index 7d555d1dcc..f25065d9c4 100644 --- a/docs/content/doc/features/authentication.en-us.md +++ b/docs/content/doc/features/authentication.en-us.md @@ -166,11 +166,47 @@ Uses the following fields: ## PAM (Pluggable Authentication Module) -To configure PAM, set the 'PAM Service Name' to a filename in `/etc/pam.d/`. To -work with normal Linux passwords, the user running Gitea must have read access -to `/etc/shadow`. +This procedure enables PAM authentication. Users may still be added to the +system manually using the user administration. PAM provides a mechanism to +automatically add users to the current database by testing them against PAM +authentication. To work with normal Linux passwords, the user running Gitea +must also have read access to `/etc/shadow` in order to check the validity of +the account when logging in using a public key. -**Note**: PAM support is added via [build-time flags](https://docs.gitea.io/en-us/install-from-source/#build), and the official binaries provided do not have this enabled. +**Note**: If a user has added SSH public keys into Gitea, the use of these +keys _may_ bypass the login check system. Therefore, if you wish to disable a user who +authenticates with PAM, you _should_ also manually disable the account in Gitea using the +built-in user manager. + +1. Configure and prepare the installation. + - It is recommended that you create an administrative user. + - Deselecting automatic sign-up may also be desired. +1. Once the database has been initialized, log in as the newly created +administrative user. +1. Navigate to the user setting (icon in top-right corner), and select +`Site Administration` -> `Authentication Sources`, and select +`Add Authentication Source`. +1. Fill out the field as follows: + - `Authentication Type` : `PAM` + - `Name` : Any value should be valid here, use "System Authentication" if + you'd like. + - `PAM Service Name` : Select the appropriate file listed under `/etc/pam.d/` + that performs the authentication desired.[^1] + - `PAM Email Domain` : The e-mail suffix to append to user authentication. + For example, if the login system expects a user called `gituser`, and this + field is set to `mail.com`, then Gitea will expect the `user email` field + for an authenticated GIT instance to be `gituser@mail.com`.[^2] + +**Note**: PAM support is added via [build-time flags](https://docs.gitea.io/en-us/install-from-source/#build), +and the official binaries provided do not have this enabled. PAM requires that +the necessary libpam dynamic library be available and the necessary PAM +development headers be accessible to the compiler. + +[^1]: For example, using standard Linux log-in on Debian "Bullseye" use +`common-session-noninteractive` - this value may be valid for other flavors of +Debian including Ubuntu and Mint, consult your distribution's documentation. +[^2]: **This is a required field for PAM**. Be aware: In the above example, the +user will log into the Gitea web interface as `gituser` and not `gituser@mail.com` ## SMTP (Simple Mail Transfer Protocol) diff --git a/docs/content/doc/help/faq.en-us.md b/docs/content/doc/help/faq.en-us.md index a59abe8335..a92186334f 100644 --- a/docs/content/doc/help/faq.en-us.md +++ b/docs/content/doc/help/faq.en-us.md @@ -58,29 +58,33 @@ https://github.com/loganinak/MigrateGitlabToGogs ## Where does Gitea store what file -- WorkPath - - Environment variable `GITEA_WORK_DIR` - - Else `--work-path` flag +- _`AppWorkPath`_ + - The `--work-path` flag + - Else Environment variable `GITEA_WORK_DIR` + - Else a built-in value set at build time - Else the directory that contains the Gitea binary -- AppDataPath (default for database, indexers, etc.) +- `%(APP_DATA_PATH)` (default for database, indexers, etc.) - `APP_DATA_PATH` from `app.ini` - - Else `%(WorkPath)/data` -- CustomPath (custom templates) - - Environment variable `GITEA_CUSTOM` - - Else `%(WorkPath)/custom` + - Else _`AppWorkPath`_`/data` +- _`CustomPath`_ (custom templates) + - The `--custom-path` flag + - Else Environment variable `GITEA_CUSTOM` + - Else a built-in value set at build time + - Else _`AppWorkPath`_`/custom` - HomeDir - Unix: Environment variable `HOME` - Windows: Environment variable `USERPROFILE`, else environment variables `HOMEDRIVE`+`HOMEPATH` - RepoRootPath - `ROOT` in the \[repository] section of `app.ini` if absolute - - Else `%(AppWorkPath)/ROOT` if `ROOT` in the \[repository] section of `app.ini` if relative - - Default `%(AppDataPath)/gitea-repositories` + - Else _`AppWorkPath`_`/ROOT` if `ROOT` in the \[repository] section of `app.ini` if relative + - Default `%(APP_DATA_PATH)/gitea-repositories` - INI (config file) - - `-c` flag - - Else `%(CustomPath)/conf/app.ini` + - `--config` flag + - A possible built-in value set a build time + - Else _`CustomPath`_`/conf/app.ini` - SQLite Database - `PATH` in `database` section of `app.ini` - - Else `%(AppDataPath)/gitea.db` + - Else `%(APP_DATA_PATH)/gitea.db` ## Not seeing a clone URL or the clone URL being incorrect diff --git a/docs/content/doc/installation/from-source.en-us.md b/docs/content/doc/installation/from-source.en-us.md index 0be5673be4..4394d19203 100644 --- a/docs/content/doc/installation/from-source.en-us.md +++ b/docs/content/doc/installation/from-source.en-us.md @@ -94,7 +94,7 @@ are provided to keep the build process as simple as possible. Depending on requirements, the following build tags can be included. -- `bindata`: Build a single monolithic binary, with all assets included. +- `bindata`: Build a single monolithic binary, with all assets included. Required for production build. - `sqlite sqlite_unlock_notify`: Enable support for a [SQLite3](https://sqlite.org/) database. Suggested only for tiny installations. @@ -103,11 +103,10 @@ Depending on requirements, the following build tags can be included. available to PAM. - `gogit`: (EXPERIMENTAL) Use go-git variants of Git commands. -Bundling assets into the binary using the `bindata` build tag is recommended for -production deployments. It is possible to serve the static assets directly via a reverse proxy, -but in most cases it is not necessary, and assets should still be bundled in the binary. -You may want to exclude bindata while developing/testing Gitea. -To include assets, add the `bindata` tag: +Bundling all assets (JS/CSS/templates, etc) into the binary. Using the `bindata` build tag is required for +production deployments. You could exclude `bindata` when you are developing/testing Gitea or able to separate the assets correctly. + +To include all assets, use the `bindata` tag: ```bash TAGS="bindata" make build @@ -144,11 +143,11 @@ launched manually from command line, it can be killed by pressing `Ctrl + C`. ## Changing default paths -Gitea will search for a number of things from the `CustomPath`. By default this is +Gitea will search for a number of things from the _`CustomPath`_. By default this is the `custom/` directory in the current working directory when running Gitea. It will also -look for its configuration file `CustomConf` in `$CustomPath/conf/app.ini`, and will use the -current working directory as the relative base path `AppWorkPath` for a number configurable -values. Finally the static files will be served from `StaticRootPath` which defaults to the `AppWorkPath`. +look for its configuration file _`CustomConf`_ in `$(CustomPath)/conf/app.ini`, and will use the +current working directory as the relative base path _`AppWorkPath`_ for a number configurable +values. Finally the static files will be served from _`StaticRootPath`_ which defaults to the _`AppWorkPath`_. These values, although useful when developing, may conflict with downstream users preferences. @@ -156,10 +155,10 @@ One option is to use a script file to shadow the `gitea` binary and create an ap environment before running Gitea. However, when building you can change these defaults using the `LDFLAGS` environment variable for `make`. The appropriate settings are as follows -- To set the `CustomPath` use `LDFLAGS="-X \"code.gitea.io/gitea/modules/setting.CustomPath=custom-path\""` -- For `CustomConf` you should use `-X \"code.gitea.io/gitea/modules/setting.CustomConf=conf.ini\"` -- For `AppWorkPath` you should use `-X \"code.gitea.io/gitea/modules/setting.AppWorkPath=working-path\"` -- For `StaticRootPath` you should use `-X \"code.gitea.io/gitea/modules/setting.StaticRootPath=static-root-path\"` +- To set the _`CustomPath`_ use `LDFLAGS="-X \"code.gitea.io/gitea/modules/setting.CustomPath=custom-path\""` +- For _`CustomConf`_ you should use `-X \"code.gitea.io/gitea/modules/setting.CustomConf=conf.ini\"` +- For _`AppWorkPath`_ you should use `-X \"code.gitea.io/gitea/modules/setting.AppWorkPath=working-path\"` +- For _`StaticRootPath`_ you should use `-X \"code.gitea.io/gitea/modules/setting.StaticRootPath=static-root-path\"` - To change the default PID file location use `-X \"code.gitea.io/gitea/modules/setting.PIDFile=/run/gitea.pid\"` Add as many of the strings with their preceding `-X` to the `LDFLAGS` variable and run `make build` diff --git a/docs/content/doc/installation/with-docker-rootless.en-us.md b/docs/content/doc/installation/with-docker-rootless.en-us.md index 3cae65c2b2..8af3e5b8b6 100644 --- a/docs/content/doc/installation/with-docker-rootless.en-us.md +++ b/docs/content/doc/installation/with-docker-rootless.en-us.md @@ -29,10 +29,16 @@ the official [install instructions](https://docs.docker.com/compose/install/). The most simple setup just creates a volume and a network and starts the `gitea/gitea:latest-rootless` image as a service. Since there is no database available, one can be initialized using SQLite3. -Create a directory for `data` and `config` then paste the following content into a file named `docker-compose.yml`. -Note that the volume should be owned by the user/group with the UID/GID specified in the config file. By default Gitea in docker will use uid:1000 gid:1000. If needed you can set ownership on those folders with the command: `sudo chown 1000:1000 config/ data/` -If you don't give the volume correct permissions, the container may not start. -For a stable release you could use `:latest-rootless`, `:1-rootless` or specify a certain release like `:{{< version >}}-rootless`, but if you'd like to use the latest development version then `:dev-rootless` would be an appropriate tag. If you'd like to run the latest commit from a release branch you can use the `:1.x-dev-rootless` tag, where x is the minor version of Gitea. (e.g. `:1.16-dev-rootless`) + +Create a directory for `data` and `config`: + +```sh +mkdir -p gitea/{data,config} +cd gitea +touch docker-compose.yml +``` + +Then paste the following content into a file named `docker-compose.yml`: ```yaml version: "2" @@ -51,6 +57,16 @@ services: - "2222:2222" ``` +Note that the volume should be owned by the user/group with the UID/GID specified in the config file. By default Gitea in docker will use uid:1000 gid:1000. If needed you can set ownership on those folders with the command: + +```sh +sudo chown 1000:1000 config/ data/ +``` + +> If you don't give the volume correct permissions, the container may not start. + +For a stable release you could use `:latest-rootless`, `:1-rootless` or specify a certain release like `:{{< version >}}-rootless`, but if you'd like to use the latest development version then `:dev-rootless` would be an appropriate tag. If you'd like to run the latest commit from a release branch you can use the `:1.x-dev-rootless` tag, where x is the minor version of Gitea. (e.g. `:1.16-dev-rootless`) + ## Custom port To bind the integrated ssh and the webserver on a different port, adjust diff --git a/docs/content/doc/packages/overview.en-us.md b/docs/content/doc/packages/overview.en-us.md index 0abb054b0f..239ba6834e 100644 --- a/docs/content/doc/packages/overview.en-us.md +++ b/docs/content/doc/packages/overview.en-us.md @@ -32,7 +32,7 @@ The following package managers are currently supported: | [Generic]({{< relref "doc/packages/generic.en-us.md" >}}) | - | any HTTP client | | [Helm]({{< relref "doc/packages/helm.en-us.md" >}}) | - | any HTTP client, `cm-push` | | [Maven]({{< relref "doc/packages/maven.en-us.md" >}}) | Java | `mvn`, `gradle` | -| [npm]({{< relref "doc/packages/npm.en-us.md" >}}) | JavaScript | `npm`, `yarn` | +| [npm]({{< relref "doc/packages/npm.en-us.md" >}}) | JavaScript | `npm`, `yarn`, `pnpm` | | [NuGet]({{< relref "doc/packages/nuget.en-us.md" >}}) | .NET | `nuget` | | [Pub]({{< relref "doc/packages/pub.en-us.md" >}}) | Dart | `dart`, `flutter` | | [PyPI]({{< relref "doc/packages/pypi.en-us.md" >}}) | Python | `pip`, `twine` | diff --git a/docs/content/doc/packages/storage.en-us.md b/docs/content/doc/packages/storage.en-us.md new file mode 100644 index 0000000000..b04a7595f7 --- /dev/null +++ b/docs/content/doc/packages/storage.en-us.md @@ -0,0 +1,84 @@ +--- +date: "2022-11-01T00:00:00+00:00" +title: "Storage" +slug: "packages/storage" +draft: false +toc: false +menu: + sidebar: + parent: "packages" + name: "Storage" + weight: 5 + identifier: "storage" +--- + +# Storage + +This document describes the storage of the package registry and how it can be managed. + +**Table of Contents** + +{{< toc >}} + +## Deduplication + +The package registry has a build-in deduplication of uploaded blobs. +If two identical files are uploaded only one blob is saved on the filesystem. +This ensures no space is wasted for duplicated files. + +If two packages are uploaded with identical files, both packages will display the same size but on the filesystem they require only half of the size. +Whenever a package gets deleted only the references to the underlaying blobs are removed. +The blobs get not removed at this moment, so they still require space on the filesystem. +When a new package gets uploaded the existing blobs may get referenced again. + +These unreferenced blobs get deleted by a [clean up job]({{< relref "doc/advanced/config-cheat-sheet.en-us.md#cron---cleanup-expired-packages-croncleanup_packages" >}}). +The config setting `OLDER_THAN` configures how long unreferenced blobs are kept before they get deleted. + +## Cleanup Rules + +Package registries can become large over time without cleanup. +It's recommended to delete unnecessary packages and set up cleanup rules to automatically manage the package registry usage. +Every package owner (user or organization) manages the cleanup rules which are applied to their packages. + +|Setting|Description| +|-|-| +|Enabled|Turn the cleanup rule on or off.| +|Type|Every rule manages a specific package type.| +|Apply pattern to full package name|If enabled, the patterns below are applied to the full package name (`package/version`). Otherwise only the version (`version`) is used.| +|Keep the most recent|How many versions to *always* keep for each package.| +|Keep versions matching|The regex pattern that determines which versions to keep. An empty pattern keeps no version while `.+` keeps all versions. The container registry will always keep the `latest` version even if not configured.| +|Remove versions older than|Remove only versions older than the selected days.| +|Remove versions matching|The regex pattern that determines which versions to remove. An empty pattern or `.+` leads to the removal of every package if no other setting tells otherwise.| + +Every cleanup rule can show a preview of the affected packages. +This can be used to check if the cleanup rules is proper configured. + +### Regex examples + +Regex patterns are automatically surrounded with `\A` and `\z` anchors. +Do not include any `\A`, `\z`, `^` or `$` token in the regex patterns as they are not necessary. +The patterns are case-insensitive which matches the behaviour of the package registry in Gitea. + +|Pattern|Description| +|-|-| +|`.*`|Match every possible version.| +|`v.+`|Match versions that start with `v`.| +|`release`|Match only the version `release`.| +|`release.*`|Match versions that are either named or start with `release`.| +|`.+-temp-.+`|Match versions that contain `-temp-`.| +|`v.+\|release`|Match versions that either start with `v` or are named `release`.| +|`package/v.+\|other/release`|Match versions of the package `package` that start with `v` or the version `release` of the package `other`. This needs the setting *Apply pattern to full package name* enabled.| + +### How the cleanup rules work + +The cleanup rules are part of the [clean up job]({{< relref "doc/advanced/config-cheat-sheet.en-us.md#cron---cleanup-expired-packages-croncleanup_packages" >}}) and run periodicly. + +The cleanup rule: + +1. Collects all packages of the package type for the owners registry. +1. For every package it collects all versions. +1. Excludes from the list the # versions based on the *Keep the most recent* value. +1. Excludes from the list any versions matching the *Keep versions matching* value. +1. Excludes from the list the versions more recent than the *Remove versions older than* value. +1. Excludes from the list any versions not matching the *Remove versions matching* value. +1. Deletes the remaining versions. diff --git a/docs/content/doc/packages/vagrant.en-us.md b/docs/content/doc/packages/vagrant.en-us.md index e846de1a2a..1e6d7a7721 100644 --- a/docs/content/doc/packages/vagrant.en-us.md +++ b/docs/content/doc/packages/vagrant.en-us.md @@ -7,7 +7,7 @@ toc: false menu: sidebar: parent: "packages" - name: "vagrant" + name: "Vagrant" weight: 120 identifier: "vagrant" --- diff --git a/docs/content/doc/translation/guidelines.de-de.md b/docs/content/doc/translation/guidelines.de-de.md index eee031a54e..3fa7185562 100644 --- a/docs/content/doc/translation/guidelines.de-de.md +++ b/docs/content/doc/translation/guidelines.de-de.md @@ -45,15 +45,15 @@ Beispiel: Wenn der Button mit `löschen` beschriftet ist, sollte im Modal die Fr ## Artikeldefinitionen für Anglizismen * _Der_ Commit (m.) -* _Der_ Branch (m.) +* _Der_ Branch (m.), plural: die Branches * _Das_ Issue (n.) * _Der_ Fork (m.) -* _Das_ Repository (n.) +* _Das_ Repository (n.), plural: die Repositories * _Der_ Pull-Request (m.) -* _Der_ Token (m.) +* _Der_ Token (m.), plural: die Token * _Das_ Review (n.) * _Der_ Key (m.) -* _Der_ Committer (m.) +* _Der_ Committer (m.), plural: die Committer ## Weiterführende Links diff --git a/go.mod b/go.mod index 5d38ff0481..1c663f588b 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module code.gitea.io/gitea go 1.18 require ( - code.gitea.io/gitea-vet v0.2.2-0.20220122151748-48ebc902541b + code.gitea.io/gitea-vet v0.2.2 code.gitea.io/sdk/gitea v0.15.1 codeberg.org/gusted/mcaptcha v0.0.0-20220723083913-4f3072e1d570 gitea.com/go-chi/binding v0.0.0-20221013104517-b29891619681 @@ -15,7 +15,7 @@ require ( github.com/42wim/sshsig v0.0.0-20211121163825-841cf5bbc121 github.com/NYTimes/gziphandler v1.1.1 github.com/PuerkitoBio/goquery v1.8.0 - github.com/alecthomas/chroma/v2 v2.3.0 + github.com/alecthomas/chroma/v2 v2.4.0 github.com/blevesearch/bleve/v2 v2.3.4 github.com/buildkite/terminal-to-html/v3 v3.7.0 github.com/caddyserver/certmagic v0.17.2 @@ -95,20 +95,19 @@ require ( github.com/yuin/goldmark-meta v1.1.0 go.jolheiser.com/hcaptcha v0.0.4 go.jolheiser.com/pwn v0.0.3 - golang.org/x/crypto v0.0.0-20220926161630-eccd6366d1be - golang.org/x/net v0.0.0-20220927171203-f486391704dc + golang.org/x/crypto v0.2.1-0.20221112162523-6fad3dfc1891 + golang.org/x/net v0.2.0 golang.org/x/oauth2 v0.0.0-20220909003341-f21342109be1 - golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec - golang.org/x/text v0.3.8 + golang.org/x/sys v0.2.0 + golang.org/x/text v0.4.0 golang.org/x/tools v0.1.12 gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df gopkg.in/ini.v1 v1.67.0 - gopkg.in/yaml.v2 v2.4.0 gopkg.in/yaml.v3 v3.0.1 mvdan.cc/xurls/v2 v2.4.0 strk.kbt.io/projects/go/libravatar v0.0.0-20191008002943-06d1c002b251 - xorm.io/builder v0.3.11 - xorm.io/xorm v1.3.2-0.20220714055524-c3bce556200f + xorm.io/builder v0.3.12 + xorm.io/xorm v1.3.3-0.20221209153726-f1bfc5ce9830 ) require ( @@ -184,7 +183,7 @@ require ( github.com/go-openapi/strfmt v0.21.3 // indirect github.com/go-openapi/swag v0.22.3 // indirect github.com/go-openapi/validate v0.22.0 // indirect - github.com/goccy/go-json v0.9.11 // indirect + github.com/goccy/go-json v0.10.0 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect github.com/golang-sql/sqlexp v0.1.0 // indirect @@ -293,6 +292,7 @@ require ( gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect gopkg.in/cheggaaa/pb.v1 v1.0.28 // indirect gopkg.in/warnings.v0 v0.1.2 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect sigs.k8s.io/yaml v1.2.0 // indirect ) diff --git a/go.sum b/go.sum index 56eb524a81..3b5bdd7bc2 100644 --- a/go.sum +++ b/go.sum @@ -65,8 +65,8 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9 cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3fOKtUw0Xmo= cloud.google.com/go/storage v1.22.1/go.mod h1:S8N1cAStu7BOeFfE8KAQzmyyLkK8p/vmRq6kuBTW58Y= code.gitea.io/gitea-vet v0.2.1/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFjGGfE= -code.gitea.io/gitea-vet v0.2.2-0.20220122151748-48ebc902541b h1:uv9a8eGSdQ8Dr4HyUcuHFfDsk/QuwO+wf+Y99RYdxY0= -code.gitea.io/gitea-vet v0.2.2-0.20220122151748-48ebc902541b/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFjGGfE= +code.gitea.io/gitea-vet v0.2.2 h1:TEOV/Glf38iGmKzKP0EB++Z5OSL4zGg3RrAvlwaMuvk= +code.gitea.io/gitea-vet v0.2.2/go.mod h1:zcNbT/aJEmivCAhfmkHOlT645KNOf9W2KnkLgFjGGfE= code.gitea.io/sdk/gitea v0.11.3/go.mod h1:z3uwDV/b9Ls47NGukYM9XhnHtqPh/J+t40lsUrR6JDY= code.gitea.io/sdk/gitea v0.15.1 h1:WJreC7YYuxbn0UDaPuWIe/mtiNKTvLN8MLkaw71yx/M= code.gitea.io/sdk/gitea v0.15.1/go.mod h1:klY2LVI3s3NChzIk/MzMn7G1FHrfU7qd63iSMVoHRBA= @@ -162,9 +162,10 @@ github.com/acomagu/bufpipe v1.0.3/go.mod h1:mxdxdup/WdsKVreO5GpW4+M/1CE2sMG4jeGJ github.com/afex/hystrix-go v0.0.0-20180502004556-fa1af6a1f4f5/go.mod h1:SkGFH1ia65gfNATL8TAiHDNxPzPdmEL5uirI2Uyuz6c= github.com/akavel/rsrc v0.8.0/go.mod h1:uLoCtb9J+EyAqh+26kdrTgmzRBFPGOolLWKpdxkKq+c= github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7/go.mod h1:6zEj6s6u/ghQa61ZWa/C2Aw3RkjiTBOix7dkqa1VLIs= +github.com/alecthomas/assert/v2 v2.2.0 h1:f6L/b7KE2bfA+9O4FL3CM/xJccDEwPVYd5fALBiuwvw= github.com/alecthomas/chroma/v2 v2.2.0/go.mod h1:vf4zrexSH54oEjJ7EdB65tGNHmH3pGZmVkgTP5RHvAs= -github.com/alecthomas/chroma/v2 v2.3.0 h1:83xfxrnjv8eK+Cf8qZDzNo3PPF9IbTWHs7z28GY6D0U= -github.com/alecthomas/chroma/v2 v2.3.0/go.mod h1:mZxeWZlxP2Dy+/8cBob2PYd8O2DwNAzave5AY7A2eQw= +github.com/alecthomas/chroma/v2 v2.4.0 h1:Loe2ZjT5x3q1bcWwemqyqEi8p11/IV/ncFCeLYDpWC4= +github.com/alecthomas/chroma/v2 v2.4.0/go.mod h1:6kHzqF5O6FUSJzBXW7fXELjb+e+7OXW4UpoPqMO7IBQ= github.com/alecthomas/kingpin v2.2.6+incompatible/go.mod h1:59OFYbFVLKQKq+mqrL6Rw5bR0c3ACQaawgXx0QYndlE= github.com/alecthomas/repr v0.0.0-20220113201626-b1b626ac65ae/go.mod h1:2kn6fqh/zIyPLmm3ugklbEi5hg5wS435eygvNfaDQL8= github.com/alecthomas/repr v0.1.0 h1:ENn2e1+J3k09gyj2shc0dHr/yjaWSHRlrJ4DPMevDqE= @@ -598,8 +599,8 @@ github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJA github.com/goccy/go-json v0.8.1/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-json v0.9.5/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/goccy/go-json v0.9.6/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= -github.com/goccy/go-json v0.9.11 h1:/pAaQDLHEoCq/5FFmSKBswWmK6H0e8g4159Kc/X/nqk= -github.com/goccy/go-json v0.9.11/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/goccy/go-json v0.10.0 h1:mXKd9Qw4NuzShiRlOXKews24ufknHO7gx30lsDyokKA= +github.com/goccy/go-json v0.10.0/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gofrs/uuid v4.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= @@ -830,6 +831,7 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= +github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/huandu/xstrings v1.0.0/go.mod h1:4qWG/gcEcfX4z/mBDHJ++3ReCw9ibxbsNJbcucJdbSo= github.com/huandu/xstrings v1.2.0/go.mod h1:DvyZB1rfVYsBIigL8HwpZgxHwXozlTgGqn63UyNX5k4= @@ -1608,8 +1610,8 @@ golang.org/x/crypto v0.0.0-20220214200702-86341886e292/go.mod h1:IxCIyHEi3zRg3s0 golang.org/x/crypto v0.0.0-20220315160706-3147a52a75dd/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.0.0-20220826181053-bd7e27e6170d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/crypto v0.0.0-20220926161630-eccd6366d1be h1:fmw3UbQh+nxngCAHrDCCztao/kbYFnWjoqop8dHx05A= -golang.org/x/crypto v0.0.0-20220926161630-eccd6366d1be/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.2.1-0.20221112162523-6fad3dfc1891 h1:WhEPFM1Ck5gaKybeSWvzI7Y/cd8K9K5tJGRxXMACOBA= +golang.org/x/crypto v0.2.1-0.20221112162523-6fad3dfc1891/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -1721,8 +1723,8 @@ golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220630215102-69896b714898/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.0.0-20220826154423-83b083e8dc8b/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= -golang.org/x/net v0.0.0-20220927171203-f486391704dc h1:FxpXZdoBqT8RjqTy6i1E8nXHhW21wK7ptQ/EPIGxzPQ= -golang.org/x/net v0.0.0-20220927171203-f486391704dc/go.mod h1:YDH+HFinaLZZlnHAfSS6ZXJJ9M9t4Dl22yv3iI2vPwk= +golang.org/x/net v0.2.0 h1:sZfSu1wtKLGlWI4ZZayP0ck9Y73K1ynO6gqzTdBVdPU= +golang.org/x/net v0.2.0/go.mod h1:KqCZLdyyvdV855qA2rE3GC2aiw5xGR5TEjj8smXukLY= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20181106182150-f42d05182288/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -1876,13 +1878,13 @@ golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220825204002-c680a09ffe64/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec h1:BkDtF2Ih9xZ7le9ndzTA7KJow28VbQW3odyk/8drmuI= -golang.org/x/sys v0.0.0-20220928140112-f11e5e49a4ec/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.2.0 h1:ljd4t30dBnAvMZaQCevtY0xLLD0A+bRZXbgLMLU1F/A= +golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/term v0.0.0-20220722155259-a9ba230a4035 h1:Q5284mrmYTpACcm+eAKjKJH48BBwSyfJqmmGDTtT8Vc= golang.org/x/term v0.0.0-20220722155259-a9ba230a4035/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.2.0 h1:z85xZCsEl7bi/KwbNADeBYoOP0++7W1ipu+aGnpwzRM= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -1892,8 +1894,8 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY= -golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg= +golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -2377,7 +2379,7 @@ sourcegraph.com/sourcegraph/appdash v0.0.0-20190731080439-ebfcffb1b5c0/go.mod h1 strk.kbt.io/projects/go/libravatar v0.0.0-20191008002943-06d1c002b251 h1:mUcz5b3FJbP5Cvdq7Khzn6J9OCUQJaBwgBkCR+MOwSs= strk.kbt.io/projects/go/libravatar v0.0.0-20191008002943-06d1c002b251/go.mod h1:FJGmPh3vz9jSos1L/F91iAgnC/aejc0wIIrF2ZwJxdY= xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978/go.mod h1:aUW0S9eb9VCaPohFCH3j7czOx1PMW3i1HrSzbLYGBSE= -xorm.io/builder v0.3.11 h1:naLkJitGyYW7ZZdncsh/JW+HF4HshmvTHTyUyPwJS00= -xorm.io/builder v0.3.11/go.mod h1:aUW0S9eb9VCaPohFCH3j7czOx1PMW3i1HrSzbLYGBSE= -xorm.io/xorm v1.3.2-0.20220714055524-c3bce556200f h1:3NvNsM4lnttTsHpk8ODHqrwN1MCEjsO3bD/rpd8A47k= -xorm.io/xorm v1.3.2-0.20220714055524-c3bce556200f/go.mod h1:9NbjqdnjX6eyjRRhh01GHm64r6N9shTb/8Ak3YRt8Nw= +xorm.io/builder v0.3.12 h1:ASZYX7fQmy+o8UJdhlLHSW57JDOkM8DNhcAF5d0LiJM= +xorm.io/builder v0.3.12/go.mod h1:aUW0S9eb9VCaPohFCH3j7czOx1PMW3i1HrSzbLYGBSE= +xorm.io/xorm v1.3.3-0.20221209153726-f1bfc5ce9830 h1:ohaHCvT7ocSDkTEa2/2z0BXfINYlHm/Z7IzN7MeXQlM= +xorm.io/xorm v1.3.3-0.20221209153726-f1bfc5ce9830/go.mod h1:9NbjqdnjX6eyjRRhh01GHm64r6N9shTb/8Ak3YRt8Nw= diff --git a/main.go b/main.go index 0e550f05eb..070e9857d0 100644 --- a/main.go +++ b/main.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2016 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. +// SPDX-License-Identifier: MIT // Gitea (git with a cup of tea) is a painless self-hosted Git Service. package main // import "code.gitea.io/gitea" diff --git a/models/activities/action.go b/models/activities/action.go index b4fda22419..3c5b623035 100644 --- a/models/activities/action.go +++ b/models/activities/action.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package activities @@ -115,12 +114,12 @@ func (a *Action) GetOpType() ActionType { } // LoadActUser loads a.ActUser -func (a *Action) LoadActUser() { +func (a *Action) LoadActUser(ctx context.Context) { if a.ActUser != nil { return } var err error - a.ActUser, err = user_model.GetUserByID(a.ActUserID) + a.ActUser, err = user_model.GetUserByID(ctx, a.ActUserID) if err == nil { return } else if user_model.IsErrUserNotExist(err) { @@ -130,12 +129,12 @@ func (a *Action) LoadActUser() { } } -func (a *Action) loadRepo() { +func (a *Action) loadRepo(ctx context.Context) { if a.Repo != nil { return } var err error - a.Repo, err = repo_model.GetRepositoryByID(a.RepoID) + a.Repo, err = repo_model.GetRepositoryByID(ctx, a.RepoID) if err != nil { log.Error("repo_model.GetRepositoryByID(%d): %v", a.RepoID, err) } @@ -143,13 +142,13 @@ func (a *Action) loadRepo() { // GetActFullName gets the action's user full name. func (a *Action) GetActFullName() string { - a.LoadActUser() + a.LoadActUser(db.DefaultContext) return a.ActUser.FullName } // GetActUserName gets the action's user name. func (a *Action) GetActUserName() string { - a.LoadActUser() + a.LoadActUser(db.DefaultContext) return a.ActUser.Name } @@ -180,7 +179,7 @@ func (a *Action) GetDisplayNameTitle() string { // GetRepoUserName returns the name of the action repository owner. func (a *Action) GetRepoUserName() string { - a.loadRepo() + a.loadRepo(db.DefaultContext) return a.Repo.OwnerName } @@ -192,7 +191,7 @@ func (a *Action) ShortRepoUserName() string { // GetRepoName returns the name of the action repository. func (a *Action) GetRepoName() string { - a.loadRepo() + a.loadRepo(db.DefaultContext) return a.Repo.Name } @@ -381,7 +380,7 @@ func activityQueryCondition(opts GetFeedsOptions) (builder.Cond, error) { cond := builder.NewCond() if opts.RequestedTeam != nil && opts.RequestedUser == nil { - org, err := user_model.GetUserByID(opts.RequestedTeam.OrgID) + org, err := user_model.GetUserByID(db.DefaultContext, opts.RequestedTeam.OrgID) if err != nil { return nil, err } @@ -466,7 +465,8 @@ func DeleteOldActions(olderThan time.Duration) (err error) { return err } -func notifyWatchers(ctx context.Context, actions ...*Action) error { +// NotifyWatchers creates batch of actions for every watcher. +func NotifyWatchers(ctx context.Context, actions ...*Action) error { var watchers []*repo_model.Watch var repo *repo_model.Repository var err error @@ -494,7 +494,7 @@ func notifyWatchers(ctx context.Context, actions ...*Action) error { } if repoChanged { - act.loadRepo() + act.loadRepo(ctx) repo = act.Repo // check repo owner exist. @@ -519,7 +519,7 @@ func notifyWatchers(ctx context.Context, actions ...*Action) error { permIssue = make([]bool, len(watchers)) permPR = make([]bool, len(watchers)) for i, watcher := range watchers { - user, err := user_model.GetUserByIDCtx(ctx, watcher.UserID) + user, err := user_model.GetUserByID(ctx, watcher.UserID) if err != nil { permCode[i] = false permIssue[i] = false @@ -570,20 +570,15 @@ func notifyWatchers(ctx context.Context, actions ...*Action) error { return nil } -// NotifyWatchers creates batch of actions for every watcher. -func NotifyWatchers(actions ...*Action) error { - return notifyWatchers(db.DefaultContext, actions...) -} - // NotifyWatchersActions creates batch of actions for every watcher. func NotifyWatchersActions(acts []*Action) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } defer committer.Close() for _, act := range acts { - if err := notifyWatchers(ctx, act); err != nil { + if err := NotifyWatchers(ctx, act); err != nil { return err } } @@ -608,17 +603,17 @@ func DeleteIssueActions(ctx context.Context, repoID, issueID int64) error { } // CountActionCreatedUnixString count actions where created_unix is an empty string -func CountActionCreatedUnixString() (int64, error) { +func CountActionCreatedUnixString(ctx context.Context) (int64, error) { if setting.Database.UseSQLite3 { - return db.GetEngine(db.DefaultContext).Where(`created_unix = ""`).Count(new(Action)) + return db.GetEngine(ctx).Where(`created_unix = ""`).Count(new(Action)) } return 0, nil } // FixActionCreatedUnixString set created_unix to zero if it is an empty string -func FixActionCreatedUnixString() (int64, error) { +func FixActionCreatedUnixString(ctx context.Context) (int64, error) { if setting.Database.UseSQLite3 { - res, err := db.GetEngine(db.DefaultContext).Exec(`UPDATE action SET created_unix = 0 WHERE created_unix = ""`) + res, err := db.GetEngine(ctx).Exec(`UPDATE action SET created_unix = 0 WHERE created_unix = ""`) if err != nil { return 0, err } diff --git a/models/activities/action_list.go b/models/activities/action_list.go index 86aa8689e2..3d74397c69 100644 --- a/models/activities/action_list.go +++ b/models/activities/action_list.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package activities @@ -82,7 +81,7 @@ func (actions ActionList) loadRepoOwner(ctx context.Context, userMap map[int64]* } repoOwner, ok := userMap[action.Repo.OwnerID] if !ok { - repoOwner, err = user_model.GetUserByIDCtx(ctx, action.Repo.OwnerID) + repoOwner, err = user_model.GetUserByID(ctx, action.Repo.OwnerID) if err != nil { if user_model.IsErrUserNotExist(err) { continue diff --git a/models/activities/action_test.go b/models/activities/action_test.go index d97c0c33c4..485305761c 100644 --- a/models/activities/action_test.go +++ b/models/activities/action_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package activities_test @@ -188,7 +187,7 @@ func TestNotifyWatchers(t *testing.T) { RepoID: 1, OpType: activities_model.ActionStarRepo, } - assert.NoError(t, activities_model.NotifyWatchers(action)) + assert.NoError(t, activities_model.NotifyWatchers(db.DefaultContext, action)) // One watchers are inactive, thus action is only created for user 8, 1, 4, 11 unittest.AssertExistsAndLoadBean(t, &activities_model.Action{ @@ -256,17 +255,17 @@ func TestConsistencyUpdateAction(t *testing.T) { // // Get rid of incorrectly set created_unix // - count, err := activities_model.CountActionCreatedUnixString() + count, err := activities_model.CountActionCreatedUnixString(db.DefaultContext) assert.NoError(t, err) assert.EqualValues(t, 1, count) - count, err = activities_model.FixActionCreatedUnixString() + count, err = activities_model.FixActionCreatedUnixString(db.DefaultContext) assert.NoError(t, err) assert.EqualValues(t, 1, count) - count, err = activities_model.CountActionCreatedUnixString() + count, err = activities_model.CountActionCreatedUnixString(db.DefaultContext) assert.NoError(t, err) assert.EqualValues(t, 0, count) - count, err = activities_model.FixActionCreatedUnixString() + count, err = activities_model.FixActionCreatedUnixString(db.DefaultContext) assert.NoError(t, err) assert.EqualValues(t, 0, count) diff --git a/models/activities/main_test.go b/models/activities/main_test.go index 0a87f47600..a8740f53c4 100644 --- a/models/activities/main_test.go +++ b/models/activities/main_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package activities_test diff --git a/models/activities/notification.go b/models/activities/notification.go index 5748b807a0..d20a53a41d 100644 --- a/models/activities/notification.go +++ b/models/activities/notification.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package activities @@ -136,56 +135,48 @@ func GetNotifications(ctx context.Context, options *FindNotificationOptions) (nl } // CountNotifications count all notifications that fit to the given options and ignore pagination. -func CountNotifications(opts *FindNotificationOptions) (int64, error) { - return db.GetEngine(db.DefaultContext).Where(opts.ToCond()).Count(&Notification{}) +func CountNotifications(ctx context.Context, opts *FindNotificationOptions) (int64, error) { + return db.GetEngine(ctx).Where(opts.ToCond()).Count(&Notification{}) } // CreateRepoTransferNotification creates notification for the user a repository was transferred to -func CreateRepoTransferNotification(doer, newOwner *user_model.User, repo *repo_model.Repository) error { - ctx, committer, err := db.TxContext() - if err != nil { - return err - } - defer committer.Close() +func CreateRepoTransferNotification(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository) error { + return db.AutoTx(ctx, func(ctx context.Context) error { + var notify []*Notification - var notify []*Notification - - if newOwner.IsOrganization() { - users, err := organization.GetUsersWhoCanCreateOrgRepo(ctx, newOwner.ID) - if err != nil || len(users) == 0 { - return err - } - for i := range users { - notify = append(notify, &Notification{ - UserID: users[i].ID, + if newOwner.IsOrganization() { + users, err := organization.GetUsersWhoCanCreateOrgRepo(ctx, newOwner.ID) + if err != nil || len(users) == 0 { + return err + } + for i := range users { + notify = append(notify, &Notification{ + UserID: users[i].ID, + RepoID: repo.ID, + Status: NotificationStatusUnread, + UpdatedBy: doer.ID, + Source: NotificationSourceRepository, + }) + } + } else { + notify = []*Notification{{ + UserID: newOwner.ID, RepoID: repo.ID, Status: NotificationStatusUnread, UpdatedBy: doer.ID, Source: NotificationSourceRepository, - }) + }} } - } else { - notify = []*Notification{{ - UserID: newOwner.ID, - RepoID: repo.ID, - Status: NotificationStatusUnread, - UpdatedBy: doer.ID, - Source: NotificationSourceRepository, - }} - } - if err := db.Insert(ctx, notify); err != nil { - return err - } - - return committer.Commit() + return db.Insert(ctx, notify) + }) } // CreateOrUpdateIssueNotifications creates an issue notification // for each watcher, or updates it if already exists // receiverID > 0 just send to receiver, else send to all watcher func CreateOrUpdateIssueNotifications(issueID, commentID, notificationAuthorID, receiverID int64) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -254,7 +245,7 @@ func createOrUpdateIssueNotifications(ctx context.Context, issueID, commentID, n // notify for userID := range toNotify { issue.Repo.Units = nil - user, err := user_model.GetUserByIDCtx(ctx, userID) + user, err := user_model.GetUserByID(ctx, userID) if err != nil { if user_model.IsErrUserNotExist(err) { continue @@ -379,11 +370,7 @@ func CountUnread(ctx context.Context, userID int64) int64 { } // LoadAttributes load Repo Issue User and Comment if not loaded -func (n *Notification) LoadAttributes() (err error) { - return n.loadAttributes(db.DefaultContext) -} - -func (n *Notification) loadAttributes(ctx context.Context) (err error) { +func (n *Notification) LoadAttributes(ctx context.Context) (err error) { if err = n.loadRepo(ctx); err != nil { return } @@ -401,7 +388,7 @@ func (n *Notification) loadAttributes(ctx context.Context) (err error) { func (n *Notification) loadRepo(ctx context.Context) (err error) { if n.Repository == nil { - n.Repository, err = repo_model.GetRepositoryByIDCtx(ctx, n.RepoID) + n.Repository, err = repo_model.GetRepositoryByID(ctx, n.RepoID) if err != nil { return fmt.Errorf("getRepositoryByID [%d]: %w", n.RepoID, err) } @@ -438,7 +425,7 @@ func (n *Notification) loadComment(ctx context.Context) (err error) { func (n *Notification) loadUser(ctx context.Context) (err error) { if n.User == nil { - n.User, err = user_model.GetUserByIDCtx(ctx, n.UserID) + n.User, err = user_model.GetUserByID(ctx, n.UserID) if err != nil { return fmt.Errorf("getUserByID [%d]: %w", n.UserID, err) } @@ -481,10 +468,10 @@ func (n *Notification) APIURL() string { type NotificationList []*Notification // LoadAttributes load Repo Issue User and Comment if not loaded -func (nl NotificationList) LoadAttributes() error { +func (nl NotificationList) LoadAttributes(ctx context.Context) error { var err error for i := 0; i < len(nl); i++ { - err = nl[i].LoadAttributes() + err = nl[i].LoadAttributes(ctx) if err != nil && !issues_model.IsErrCommentNotExist(err) { return err } @@ -504,7 +491,7 @@ func (nl NotificationList) getPendingRepoIDs() []int64 { } // LoadRepos loads repositories from database -func (nl NotificationList) LoadRepos() (repo_model.RepositoryList, []int, error) { +func (nl NotificationList) LoadRepos(ctx context.Context) (repo_model.RepositoryList, []int, error) { if len(nl) == 0 { return repo_model.RepositoryList{}, []int{}, nil } @@ -517,7 +504,7 @@ func (nl NotificationList) LoadRepos() (repo_model.RepositoryList, []int, error) if left < limit { limit = left } - rows, err := db.GetEngine(db.DefaultContext). + rows, err := db.GetEngine(ctx). In("id", repoIDs[:limit]). Rows(new(repo_model.Repository)) if err != nil { @@ -578,7 +565,7 @@ func (nl NotificationList) getPendingIssueIDs() []int64 { } // LoadIssues loads issues from database -func (nl NotificationList) LoadIssues() ([]int, error) { +func (nl NotificationList) LoadIssues(ctx context.Context) ([]int, error) { if len(nl) == 0 { return []int{}, nil } @@ -591,7 +578,7 @@ func (nl NotificationList) LoadIssues() ([]int, error) { if left < limit { limit = left } - rows, err := db.GetEngine(db.DefaultContext). + rows, err := db.GetEngine(ctx). In("id", issueIDs[:limit]). Rows(new(issues_model.Issue)) if err != nil { @@ -662,7 +649,7 @@ func (nl NotificationList) getPendingCommentIDs() []int64 { } // LoadComments loads comments from database -func (nl NotificationList) LoadComments() ([]int, error) { +func (nl NotificationList) LoadComments(ctx context.Context) ([]int, error) { if len(nl) == 0 { return []int{}, nil } @@ -675,7 +662,7 @@ func (nl NotificationList) LoadComments() ([]int, error) { if left < limit { limit = left } - rows, err := db.GetEngine(db.DefaultContext). + rows, err := db.GetEngine(ctx). In("id", commentIDs[:limit]). Rows(new(issues_model.Comment)) if err != nil { @@ -775,8 +762,8 @@ func SetRepoReadBy(ctx context.Context, userID, repoID int64) error { } // SetNotificationStatus change the notification status -func SetNotificationStatus(notificationID int64, user *user_model.User, status NotificationStatus) (*Notification, error) { - notification, err := getNotificationByID(db.DefaultContext, notificationID) +func SetNotificationStatus(ctx context.Context, notificationID int64, user *user_model.User, status NotificationStatus) (*Notification, error) { + notification, err := GetNotificationByID(ctx, notificationID) if err != nil { return notification, err } @@ -787,16 +774,12 @@ func SetNotificationStatus(notificationID int64, user *user_model.User, status N notification.Status = status - _, err = db.GetEngine(db.DefaultContext).ID(notificationID).Update(notification) + _, err = db.GetEngine(ctx).ID(notificationID).Update(notification) return notification, err } // GetNotificationByID return notification by ID -func GetNotificationByID(notificationID int64) (*Notification, error) { - return getNotificationByID(db.DefaultContext, notificationID) -} - -func getNotificationByID(ctx context.Context, notificationID int64) (*Notification, error) { +func GetNotificationByID(ctx context.Context, notificationID int64) (*Notification, error) { notification := new(Notification) ok, err := db.GetEngine(ctx). Where("id = ?", notificationID). @@ -813,9 +796,9 @@ func getNotificationByID(ctx context.Context, notificationID int64) (*Notificati } // UpdateNotificationStatuses updates the statuses of all of a user's notifications that are of the currentStatus type to the desiredStatus -func UpdateNotificationStatuses(user *user_model.User, currentStatus, desiredStatus NotificationStatus) error { +func UpdateNotificationStatuses(ctx context.Context, user *user_model.User, currentStatus, desiredStatus NotificationStatus) error { n := &Notification{Status: desiredStatus, UpdatedBy: user.ID} - _, err := db.GetEngine(db.DefaultContext). + _, err := db.GetEngine(ctx). Where("user_id = ? AND status = ?", user.ID, currentStatus). Cols("status", "updated_by", "updated_unix"). Update(n) diff --git a/models/activities/notification_test.go b/models/activities/notification_test.go index 4ee16af076..36b63b266b 100644 --- a/models/activities/notification_test.go +++ b/models/activities/notification_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package activities_test @@ -82,14 +81,14 @@ func TestSetNotificationStatus(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) notf := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead}) - _, err := activities_model.SetNotificationStatus(notf.ID, user, activities_model.NotificationStatusPinned) + _, err := activities_model.SetNotificationStatus(db.DefaultContext, notf.ID, user, activities_model.NotificationStatusPinned) assert.NoError(t, err) unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: notf.ID, Status: activities_model.NotificationStatusPinned}) - _, err = activities_model.SetNotificationStatus(1, user, activities_model.NotificationStatusRead) + _, err = activities_model.SetNotificationStatus(db.DefaultContext, 1, user, activities_model.NotificationStatusRead) assert.Error(t, err) - _, err = activities_model.SetNotificationStatus(unittest.NonexistentID, user, activities_model.NotificationStatusRead) + _, err = activities_model.SetNotificationStatus(db.DefaultContext, unittest.NonexistentID, user, activities_model.NotificationStatusRead) assert.Error(t, err) } @@ -102,7 +101,7 @@ func TestUpdateNotificationStatuses(t *testing.T) { &activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead}) notfPinned := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusPinned}) - assert.NoError(t, activities_model.UpdateNotificationStatuses(user, activities_model.NotificationStatusUnread, activities_model.NotificationStatusRead)) + assert.NoError(t, activities_model.UpdateNotificationStatuses(db.DefaultContext, user, activities_model.NotificationStatusUnread, activities_model.NotificationStatusRead)) unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: notfUnread.ID, Status: activities_model.NotificationStatusRead}) unittest.AssertExistsAndLoadBean(t, diff --git a/models/activities/repo_activity.go b/models/activities/repo_activity.go index 4c8aa7e81d..9018276c3a 100644 --- a/models/activities/repo_activity.go +++ b/models/activities/repo_activity.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package activities diff --git a/models/activities/statistic.go b/models/activities/statistic.go index ea785a3ee2..138f4d8fe9 100644 --- a/models/activities/statistic.go +++ b/models/activities/statistic.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package activities diff --git a/models/activities/user_heatmap.go b/models/activities/user_heatmap.go index 6e76be6c6b..3370103a55 100644 --- a/models/activities/user_heatmap.go +++ b/models/activities/user_heatmap.go @@ -1,6 +1,5 @@ // Copyright 2018 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 models +// SPDX-License-Identifier: MIT package activities diff --git a/models/activities/user_heatmap_test.go b/models/activities/user_heatmap_test.go index a8a240f790..34715ab6dd 100644 --- a/models/activities/user_heatmap_test.go +++ b/models/activities/user_heatmap_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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 models +// SPDX-License-Identifier: MIT package activities_test diff --git a/models/admin/task.go b/models/admin/task.go index 4fa0f10394..9e661b9997 100644 --- a/models/admin/task.go +++ b/models/admin/task.go @@ -1,6 +1,5 @@ // Copyright 2019 Gitea. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package admin diff --git a/models/asymkey/error.go b/models/asymkey/error.go index 3ddeb0498a..1d486082f4 100644 --- a/models/asymkey/error.go +++ b/models/asymkey/error.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey diff --git a/models/asymkey/gpg_key.go b/models/asymkey/gpg_key.go index 83774533aa..ecd9041e65 100644 --- a/models/asymkey/gpg_key.go +++ b/models/asymkey/gpg_key.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package asymkey @@ -234,7 +233,7 @@ func DeleteGPGKey(doer *user_model.User, id int64) (err error) { return ErrGPGKeyAccessDenied{doer.ID, key.ID} } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/asymkey/gpg_key_add.go b/models/asymkey/gpg_key_add.go index d01f2deb03..eb4027b3a4 100644 --- a/models/asymkey/gpg_key_add.go +++ b/models/asymkey/gpg_key_add.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey @@ -73,7 +72,7 @@ func AddGPGKey(ownerID int64, content, token, signature string) ([]*GPGKey, erro return nil, err } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } diff --git a/models/asymkey/gpg_key_commit_verification.go b/models/asymkey/gpg_key_commit_verification.go index d5b06f83fd..1b88fb8b13 100644 --- a/models/asymkey/gpg_key_commit_verification.go +++ b/models/asymkey/gpg_key_commit_verification.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey @@ -427,7 +426,7 @@ func hashAndVerifyForKeyID(sig *packet.Signature, payload string, committer *use Email: email, } if key.OwnerID != 0 { - owner, err := user_model.GetUserByID(key.OwnerID) + owner, err := user_model.GetUserByID(db.DefaultContext, key.OwnerID) if err == nil { signer = owner } else if !user_model.IsErrUserNotExist(err) { diff --git a/models/asymkey/gpg_key_common.go b/models/asymkey/gpg_key_common.go index 1ea510c45f..5ceeee9aac 100644 --- a/models/asymkey/gpg_key_common.go +++ b/models/asymkey/gpg_key_common.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey diff --git a/models/asymkey/gpg_key_import.go b/models/asymkey/gpg_key_import.go index 210c4b835b..5b5ef4faba 100644 --- a/models/asymkey/gpg_key_import.go +++ b/models/asymkey/gpg_key_import.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey diff --git a/models/asymkey/gpg_key_test.go b/models/asymkey/gpg_key_test.go index 2cee45d98f..6a0f9c6144 100644 --- a/models/asymkey/gpg_key_test.go +++ b/models/asymkey/gpg_key_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package asymkey diff --git a/models/asymkey/gpg_key_verify.go b/models/asymkey/gpg_key_verify.go index 152765cc3a..cb5eb7c853 100644 --- a/models/asymkey/gpg_key_verify.go +++ b/models/asymkey/gpg_key_verify.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey @@ -31,7 +30,7 @@ import ( // VerifyGPGKey marks a GPG key as verified func VerifyGPGKey(ownerID int64, keyID, token, signature string) (string, error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return "", err } diff --git a/models/asymkey/main_test.go b/models/asymkey/main_test.go index 9f53e335fe..82a408ece0 100644 --- a/models/asymkey/main_test.go +++ b/models/asymkey/main_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey diff --git a/models/asymkey/ssh_key.go b/models/asymkey/ssh_key.go index 7ed4ad6b3f..4d6ae8103c 100644 --- a/models/asymkey/ssh_key.go +++ b/models/asymkey/ssh_key.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package asymkey @@ -100,7 +99,7 @@ func AddPublicKey(ownerID int64, name, content string, authSourceID int64) (*Pub return nil, err } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } @@ -321,7 +320,7 @@ func PublicKeyIsExternallyManaged(id int64) (bool, error) { // deleteKeysMarkedForDeletion returns true if ssh keys needs update func deleteKeysMarkedForDeletion(keys []string) (bool, error) { // Start session - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return false, err } diff --git a/models/asymkey/ssh_key_authorized_keys.go b/models/asymkey/ssh_key_authorized_keys.go index ce3b0248ce..e138182d68 100644 --- a/models/asymkey/ssh_key_authorized_keys.go +++ b/models/asymkey/ssh_key_authorized_keys.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey diff --git a/models/asymkey/ssh_key_authorized_principals.go b/models/asymkey/ssh_key_authorized_principals.go index 4b08d0dfe7..092839611f 100644 --- a/models/asymkey/ssh_key_authorized_principals.go +++ b/models/asymkey/ssh_key_authorized_principals.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey diff --git a/models/asymkey/ssh_key_commit_verification.go b/models/asymkey/ssh_key_commit_verification.go index 65bae0f393..af73637c4a 100644 --- a/models/asymkey/ssh_key_commit_verification.go +++ b/models/asymkey/ssh_key_commit_verification.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey diff --git a/models/asymkey/ssh_key_deploy.go b/models/asymkey/ssh_key_deploy.go index d5c981da47..cc84392117 100644 --- a/models/asymkey/ssh_key_deploy.go +++ b/models/asymkey/ssh_key_deploy.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey @@ -126,7 +125,7 @@ func AddDeployKey(repoID int64, name, content string, readOnly bool) (*DeployKey accessMode = perm.AccessModeWrite } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } diff --git a/models/asymkey/ssh_key_fingerprint.go b/models/asymkey/ssh_key_fingerprint.go index 788d58dbab..ca0334cc0b 100644 --- a/models/asymkey/ssh_key_fingerprint.go +++ b/models/asymkey/ssh_key_fingerprint.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey diff --git a/models/asymkey/ssh_key_parse.go b/models/asymkey/ssh_key_parse.go index 2462310ed9..b3eecb2c9b 100644 --- a/models/asymkey/ssh_key_parse.go +++ b/models/asymkey/ssh_key_parse.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey diff --git a/models/asymkey/ssh_key_principals.go b/models/asymkey/ssh_key_principals.go index e0d407af35..f00c3f3e9e 100644 --- a/models/asymkey/ssh_key_principals.go +++ b/models/asymkey/ssh_key_principals.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey @@ -26,7 +25,7 @@ import ( // AddPrincipalKey adds new principal to database and authorized_principals file. func AddPrincipalKey(ownerID int64, content string, authSourceID int64) (*PublicKey, error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } diff --git a/models/asymkey/ssh_key_test.go b/models/asymkey/ssh_key_test.go index adffedd0b6..afd79ae6de 100644 --- a/models/asymkey/ssh_key_test.go +++ b/models/asymkey/ssh_key_test.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package asymkey diff --git a/models/asymkey/ssh_key_verify.go b/models/asymkey/ssh_key_verify.go index 710cb3af00..d6c16eb467 100644 --- a/models/asymkey/ssh_key_verify.go +++ b/models/asymkey/ssh_key_verify.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey @@ -15,7 +14,7 @@ import ( // VerifySSHKey marks a SSH key as verified func VerifySSHKey(ownerID int64, fingerprint, token, signature string) (string, error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return "", err } diff --git a/models/auth/main_test.go b/models/auth/main_test.go index 5d52e963b8..3205d8816f 100644 --- a/models/auth/main_test.go +++ b/models/auth/main_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package auth_test diff --git a/models/auth/oauth2.go b/models/auth/oauth2.go index ccd9336f65..8e5a003d19 100644 --- a/models/auth/oauth2.go +++ b/models/auth/oauth2.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth @@ -201,7 +200,7 @@ type UpdateOAuth2ApplicationOptions struct { // UpdateOAuth2Application updates an oauth2 application func UpdateOAuth2Application(opts UpdateOAuth2ApplicationOptions) (*OAuth2Application, error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } @@ -265,7 +264,7 @@ func deleteOAuth2Application(ctx context.Context, id, userid int64) error { // DeleteOAuth2Application deletes the application with the given id and the grants and auth codes related to it. It checks if the userid was the creator of the app. func DeleteOAuth2Application(id, userid int64) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/auth/oauth2_test.go b/models/auth/oauth2_test.go index 7a4df6b9ac..80d0e9baa4 100644 --- a/models/auth/oauth2_test.go +++ b/models/auth/oauth2_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth_test diff --git a/models/auth/session.go b/models/auth/session.go index 5b130c64b6..b60e6a903b 100644 --- a/models/auth/session.go +++ b/models/auth/session.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package auth @@ -37,7 +36,7 @@ func ReadSession(key string) (*Session, error) { Key: key, } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } @@ -73,7 +72,7 @@ func DestroySession(key string) error { // RegenerateSession regenerates a session from the old id func RegenerateSession(oldKey, newKey string) (*Session, error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } diff --git a/models/auth/source.go b/models/auth/source.go index cb45887059..23fc57793f 100644 --- a/models/auth/source.go +++ b/models/auth/source.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth diff --git a/models/auth/source_test.go b/models/auth/source_test.go index 67e96ee19e..31216cca8e 100644 --- a/models/auth/source_test.go +++ b/models/auth/source_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth_test diff --git a/models/auth/token.go b/models/auth/token.go index 17c07531f8..0dfcb7629b 100644 --- a/models/auth/token.go +++ b/models/auth/token.go @@ -1,22 +1,20 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth import ( "crypto/subtle" + "encoding/hex" "fmt" "time" "code.gitea.io/gitea/models/db" - "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/util" - gouuid "github.com/google/uuid" lru "github.com/hashicorp/golang-lru" ) @@ -66,7 +64,7 @@ type AccessToken struct { Token string `xorm:"-"` TokenHash string `xorm:"UNIQUE"` // sha256 of token TokenSalt string - TokenLastEight string `xorm:"token_last_eight"` + TokenLastEight string `xorm:"INDEX token_last_eight"` CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` @@ -101,8 +99,12 @@ func NewAccessToken(t *AccessToken) error { if err != nil { return err } + token, err := util.CryptoRandomBytes(20) + if err != nil { + return err + } t.TokenSalt = salt - t.Token = base.EncodeSha1(gouuid.New().String()) + t.Token = hex.EncodeToString(token) t.TokenHash = HashToken(t.Token, t.TokenSalt) t.TokenLastEight = t.Token[len(t.Token)-8:] _, err = db.GetEngine(db.DefaultContext).Insert(t) diff --git a/models/auth/token_test.go b/models/auth/token_test.go index b27ff13406..8a1e664950 100644 --- a/models/auth/token_test.go +++ b/models/auth/token_test.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package auth_test diff --git a/models/auth/twofactor.go b/models/auth/twofactor.go index 736d4c340c..5b3a9d011a 100644 --- a/models/auth/twofactor.go +++ b/models/auth/twofactor.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package auth @@ -10,6 +9,7 @@ import ( "crypto/subtle" "encoding/base32" "encoding/base64" + "encoding/hex" "fmt" "code.gitea.io/gitea/models/db" @@ -79,7 +79,7 @@ func (t *TwoFactor) GenerateScratchToken() (string, error) { // HashToken return the hashable salt func HashToken(token, salt string) string { tempHash := pbkdf2.Key([]byte(token), []byte(salt), 10000, 50, sha256.New) - return fmt.Sprintf("%x", tempHash) + return hex.EncodeToString(tempHash) } // VerifyScratchToken verifies if the specified scratch token is valid. diff --git a/models/auth/webauthn.go b/models/auth/webauthn.go index 1575b6cbab..d5b2ceafd3 100644 --- a/models/auth/webauthn.go +++ b/models/auth/webauthn.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package auth diff --git a/models/auth/webauthn_test.go b/models/auth/webauthn_test.go index 29344376cc..8ba900bf89 100644 --- a/models/auth/webauthn_test.go +++ b/models/auth/webauthn_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package auth_test diff --git a/models/avatars/avatar.go b/models/avatars/avatar.go index 418e9b9ccc..7ccb782fa6 100644 --- a/models/avatars/avatar.go +++ b/models/avatars/avatar.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package avatars @@ -20,8 +19,12 @@ import ( "code.gitea.io/gitea/modules/setting" ) -// DefaultAvatarPixelSize is the default size in pixels of a rendered avatar -const DefaultAvatarPixelSize = 28 +const ( + // DefaultAvatarClass is the default class of a rendered avatar + DefaultAvatarClass = "ui avatar vm" + // DefaultAvatarPixelSize is the default size in pixels of a rendered avatar + DefaultAvatarPixelSize = 28 +) // EmailHash represents a pre-generated hash map (mainly used by LibravatarURL, it queries email server's DNS records) type EmailHash struct { @@ -97,7 +100,7 @@ func saveEmailHash(email string) string { Hash: emailHash, } // OK we're going to open a session just because I think that that might hide away any problems with postgres reporting errors - if err := db.WithTx(func(ctx context.Context) error { + if err := db.WithTx(db.DefaultContext, func(ctx context.Context) error { has, err := db.GetEngine(ctx).Where("email = ? AND hash = ?", emailHash.Email, emailHash.Hash).Get(new(EmailHash)) if has || err != nil { // Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time @@ -150,10 +153,11 @@ func generateEmailAvatarLink(email string, size int, final bool) string { return DefaultAvatarLink() } - enableFederatedAvatar, _ := system_model.GetSetting(system_model.KeyPictureEnableFederatedAvatar) + enableFederatedAvatarSetting, _ := system_model.GetSetting(system_model.KeyPictureEnableFederatedAvatar) + enableFederatedAvatar := enableFederatedAvatarSetting.GetValueBool() var err error - if enableFederatedAvatar != nil && enableFederatedAvatar.GetValueBool() && system_model.LibravatarService != nil { + if enableFederatedAvatar && system_model.LibravatarService != nil { emailHash := saveEmailHash(email) if final { // for final link, we can spend more time on slow external query @@ -171,8 +175,10 @@ func generateEmailAvatarLink(email string, size int, final bool) string { return urlStr } - disableGravatar, _ := system_model.GetSetting(system_model.KeyPictureDisableGravatar) - if disableGravatar != nil && !disableGravatar.GetValueBool() { + disableGravatarSetting, _ := system_model.GetSetting(system_model.KeyPictureDisableGravatar) + + disableGravatar := disableGravatarSetting.GetValueBool() + if !disableGravatar { // copy GravatarSourceURL, because we will modify its Path. avatarURLCopy := *system_model.GravatarSourceURL avatarURLCopy.Path = path.Join(avatarURLCopy.Path, HashEmail(email)) diff --git a/models/avatars/avatar_test.go b/models/avatars/avatar_test.go index ace5445fc0..29be2ea346 100644 --- a/models/avatars/avatar_test.go +++ b/models/avatars/avatar_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package avatars_test diff --git a/models/avatars/main_test.go b/models/avatars/main_test.go index 0e98d8f64d..6507632717 100644 --- a/models/avatars/main_test.go +++ b/models/avatars/main_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package avatars_test diff --git a/models/db/common.go b/models/db/common.go index 1a59a8b5c6..76c7c119f4 100644 --- a/models/db/common.go +++ b/models/db/common.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package db diff --git a/models/db/consistency.go b/models/db/consistency.go index 7addb174c4..d19732cf80 100644 --- a/models/db/consistency.go +++ b/models/db/consistency.go @@ -1,14 +1,18 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package db -import "xorm.io/builder" +import ( + "context" + + "xorm.io/builder" +) // CountOrphanedObjects count subjects with have no existing refobject anymore -func CountOrphanedObjects(subject, refobject, joinCond string) (int64, error) { - return GetEngine(DefaultContext).Table("`"+subject+"`"). +func CountOrphanedObjects(ctx context.Context, subject, refobject, joinCond string) (int64, error) { + return GetEngine(ctx). + Table("`"+subject+"`"). Join("LEFT", "`"+refobject+"`", joinCond). Where(builder.IsNull{"`" + refobject + "`.id"}). Select("COUNT(`" + subject + "`.`id`)"). @@ -16,12 +20,12 @@ func CountOrphanedObjects(subject, refobject, joinCond string) (int64, error) { } // DeleteOrphanedObjects delete subjects with have no existing refobject anymore -func DeleteOrphanedObjects(subject, refobject, joinCond string) error { +func DeleteOrphanedObjects(ctx context.Context, subject, refobject, joinCond string) error { subQuery := builder.Select("`"+subject+"`.id"). From("`"+subject+"`"). Join("LEFT", "`"+refobject+"`", joinCond). Where(builder.IsNull{"`" + refobject + "`.id"}) b := builder.Delete(builder.In("id", subQuery)).From("`" + subject + "`") - _, err := GetEngine(DefaultContext).Exec(b) + _, err := GetEngine(ctx).Exec(b) return err } diff --git a/models/db/context.go b/models/db/context.go index e90780e4e9..c8ad0c1aa2 100644 --- a/models/db/context.go +++ b/models/db/context.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package db @@ -8,6 +7,7 @@ import ( "context" "database/sql" + "xorm.io/xorm" "xorm.io/xorm/schemas" ) @@ -21,8 +21,10 @@ type contextKey struct { } // enginedContextKey is a context key. It is used with context.Value() to get the current Engined for the context -var enginedContextKey = &contextKey{"engined"} -var _ Engined = &Context{} +var ( + enginedContextKey = &contextKey{"engined"} + _ Engined = &Context{} +) // Context represents a db context type Context struct { @@ -86,7 +88,11 @@ type Committer interface { } // TxContext represents a transaction Context -func TxContext() (*Context, Committer, error) { +func TxContext(parentCtx context.Context) (*Context, Committer, error) { + if InTransaction(parentCtx) { + return nil, nil, ErrAlreadyInTransaction + } + sess := x.NewSession() if err := sess.Begin(); err != nil { sess.Close() @@ -97,14 +103,24 @@ func TxContext() (*Context, Committer, error) { } // WithTx represents executing database operations on a transaction -// you can optionally change the context to a parent one -func WithTx(f func(ctx context.Context) error, stdCtx ...context.Context) error { - parentCtx := DefaultContext - if len(stdCtx) != 0 && stdCtx[0] != nil { - // TODO: make sure parent context has no open session - parentCtx = stdCtx[0] +// This function will always open a new transaction, if a transaction exist in parentCtx return an error. +func WithTx(parentCtx context.Context, f func(ctx context.Context) error) error { + if InTransaction(parentCtx) { + return ErrAlreadyInTransaction } + return txWithNoCheck(parentCtx, f) +} +// AutoTx represents executing database operations on a transaction, if the transaction exist, +// this function will reuse it otherwise will create a new one and close it when finished. +func AutoTx(parentCtx context.Context, f func(ctx context.Context) error) error { + if InTransaction(parentCtx) { + return f(newContext(parentCtx, GetEngine(parentCtx), true)) + } + return txWithNoCheck(parentCtx, f) +} + +func txWithNoCheck(parentCtx context.Context, f func(ctx context.Context) error) error { sess := x.NewSession() defer sess.Close() if err := sess.Begin(); err != nil { @@ -180,3 +196,28 @@ func EstimateCount(ctx context.Context, bean interface{}) (int64, error) { } return rows, err } + +// InTransaction returns true if the engine is in a transaction otherwise return false +func InTransaction(ctx context.Context) bool { + var e Engine + if engined, ok := ctx.(Engined); ok { + e = engined.Engine() + } else { + enginedInterface := ctx.Value(enginedContextKey) + if enginedInterface != nil { + e = enginedInterface.(Engined).Engine() + } + } + if e == nil { + return false + } + + switch t := e.(type) { + case *xorm.Engine: + return false + case *xorm.Session: + return t.IsInTx() + default: + return false + } +} diff --git a/models/db/context_test.go b/models/db/context_test.go new file mode 100644 index 0000000000..e7518a50d8 --- /dev/null +++ b/models/db/context_test.go @@ -0,0 +1,32 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package db_test + +import ( + "context" + "testing" + + "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + + "github.com/stretchr/testify/assert" +) + +func TestInTransaction(t *testing.T) { + assert.NoError(t, unittest.PrepareTestDatabase()) + assert.False(t, db.InTransaction(db.DefaultContext)) + assert.NoError(t, db.WithTx(db.DefaultContext, func(ctx context.Context) error { + assert.True(t, db.InTransaction(ctx)) + return nil + })) + + ctx, committer, err := db.TxContext(db.DefaultContext) + assert.NoError(t, err) + defer committer.Close() + assert.True(t, db.InTransaction(ctx)) + assert.Error(t, db.WithTx(ctx, func(ctx context.Context) error { + assert.True(t, db.InTransaction(ctx)) + return nil + })) +} diff --git a/models/db/convert.go b/models/db/convert.go index 039a681040..b17e68c87e 100644 --- a/models/db/convert.go +++ b/models/db/convert.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package db diff --git a/models/db/engine.go b/models/db/engine.go index 41949eb6f6..3d05fa8b63 100755 --- a/models/db/engine.go +++ b/models/db/engine.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package db @@ -47,7 +46,7 @@ type Engine interface { Incr(column string, arg ...interface{}) *xorm.Session Insert(...interface{}) (int64, error) Iterate(interface{}, xorm.IterFunc) error - Join(joinOperator string, tablename interface{}, condition string, args ...interface{}) *xorm.Session + Join(joinOperator string, tablename, condition interface{}, args ...interface{}) *xorm.Session SQL(interface{}, ...interface{}) *xorm.Session Where(interface{}, ...interface{}) *xorm.Session Asc(colNames ...string) *xorm.Session diff --git a/models/db/engine_test.go b/models/db/engine_test.go index c26d94c340..fa1ac08a17 100644 --- a/models/db/engine_test.go +++ b/models/db/engine_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package db_test @@ -41,11 +40,11 @@ func TestDeleteOrphanedObjects(t *testing.T) { _, err = db.GetEngine(db.DefaultContext).Insert(&issues_model.PullRequest{IssueID: 1000}, &issues_model.PullRequest{IssueID: 1001}, &issues_model.PullRequest{IssueID: 1003}) assert.NoError(t, err) - orphaned, err := db.CountOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id") + orphaned, err := db.CountOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id") assert.NoError(t, err) assert.EqualValues(t, 3, orphaned) - err = db.DeleteOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id") + err = db.DeleteOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id") assert.NoError(t, err) countAfter, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{}) diff --git a/models/db/error.go b/models/db/error.go index 9577fa55db..5860cb4a07 100644 --- a/models/db/error.go +++ b/models/db/error.go @@ -1,15 +1,17 @@ // 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. +// SPDX-License-Identifier: MIT package db import ( + "errors" "fmt" "code.gitea.io/gitea/modules/util" ) +var ErrAlreadyInTransaction = errors.New("database connection has already been in a transaction") + // ErrCancelled represents an error due to context cancellation type ErrCancelled struct { Message string diff --git a/models/db/index.go b/models/db/index.go index 58a976ad52..f840a62c89 100644 --- a/models/db/index.go +++ b/models/db/index.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package db @@ -8,6 +7,9 @@ import ( "context" "errors" "fmt" + "strconv" + + "code.gitea.io/gitea/modules/setting" ) // ResourceIndex represents a resource index which could be used as issue/release and others @@ -24,11 +26,6 @@ var ( ErrGetResourceIndexFailed = errors.New("get resource index failed") ) -const ( - // MaxDupIndexAttempts max retry times to create index - MaxDupIndexAttempts = 3 -) - // SyncMaxResourceIndex sync the max index with the resource func SyncMaxResourceIndex(ctx context.Context, tableName string, groupID, maxIndex int64) (err error) { e := GetEngine(ctx) @@ -61,8 +58,25 @@ func SyncMaxResourceIndex(ctx context.Context, tableName string, groupID, maxInd return nil } +func postgresGetNextResourceIndex(ctx context.Context, tableName string, groupID int64) (int64, error) { + res, err := GetEngine(ctx).Query(fmt.Sprintf("INSERT INTO %s (group_id, max_index) "+ + "VALUES (?,1) ON CONFLICT (group_id) DO UPDATE SET max_index = %s.max_index+1 RETURNING max_index", + tableName, tableName), groupID) + if err != nil { + return 0, err + } + if len(res) == 0 { + return 0, ErrGetResourceIndexFailed + } + return strconv.ParseInt(string(res[0]["max_index"]), 10, 64) +} + // GetNextResourceIndex generates a resource index, it must run in the same transaction where the resource is created func GetNextResourceIndex(ctx context.Context, tableName string, groupID int64) (int64, error) { + if setting.Database.UsePostgreSQL { + return postgresGetNextResourceIndex(ctx, tableName, groupID) + } + e := GetEngine(ctx) // try to update the max_index to next value, and acquire the write-lock for the record diff --git a/models/db/index_test.go b/models/db/index_test.go index 1ea30e2b60..5fce0a6012 100644 --- a/models/db/index_test.go +++ b/models/db/index_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package db_test @@ -59,7 +58,7 @@ func TestSyncMaxResourceIndex(t *testing.T) { assert.EqualValues(t, 62, maxIndex) // commit transaction - err = db.WithTx(func(ctx context.Context) error { + err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { err = db.SyncMaxResourceIndex(ctx, "test_index", 10, 73) assert.NoError(t, err) maxIndex, err = getCurrentResourceIndex(ctx, "test_index", 10) @@ -73,7 +72,7 @@ func TestSyncMaxResourceIndex(t *testing.T) { assert.EqualValues(t, 73, maxIndex) // rollback transaction - err = db.WithTx(func(ctx context.Context) error { + err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { err = db.SyncMaxResourceIndex(ctx, "test_index", 10, 84) maxIndex, err = getCurrentResourceIndex(ctx, "test_index", 10) assert.NoError(t, err) @@ -102,7 +101,7 @@ func TestGetNextResourceIndex(t *testing.T) { assert.EqualValues(t, 2, maxIndex) // commit transaction - err = db.WithTx(func(ctx context.Context) error { + err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { maxIndex, err = db.GetNextResourceIndex(ctx, "test_index", 20) assert.NoError(t, err) assert.EqualValues(t, 3, maxIndex) @@ -114,7 +113,7 @@ func TestGetNextResourceIndex(t *testing.T) { assert.EqualValues(t, 3, maxIndex) // rollback transaction - err = db.WithTx(func(ctx context.Context) error { + err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { maxIndex, err = db.GetNextResourceIndex(ctx, "test_index", 20) assert.NoError(t, err) assert.EqualValues(t, 4, maxIndex) diff --git a/models/db/install/db.go b/models/db/install/db.go index 363a8c8679..d4c1139637 100644 --- a/models/db/install/db.go +++ b/models/db/install/db.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package install diff --git a/models/db/iterate.go b/models/db/iterate.go index cbd2feed28..fc8c78d83e 100644 --- a/models/db/iterate.go +++ b/models/db/iterate.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package db diff --git a/models/db/iterate_test.go b/models/db/iterate_test.go index 5d03a6e9ce..57b1bd3cd1 100644 --- a/models/db/iterate_test.go +++ b/models/db/iterate_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package db_test @@ -26,7 +25,7 @@ func TestIterate(t *testing.T) { return nil }) assert.NoError(t, err) - assert.EqualValues(t, 79, repoCnt) + assert.EqualValues(t, 80, repoCnt) err = db.Iterate(db.DefaultContext, nil, func(ctx context.Context, repoUnit *repo_model.RepoUnit) error { reopUnit2 := repo_model.RepoUnit{ID: repoUnit.ID} diff --git a/models/db/list_options.go b/models/db/list_options.go index 54f6d945c8..b9ee360b1b 100644 --- a/models/db/list_options.go +++ b/models/db/list_options.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package db diff --git a/models/db/log.go b/models/db/log.go index 4c497fdfd7..fec2ea3c3d 100644 --- a/models/db/log.go +++ b/models/db/log.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package db diff --git a/models/db/main_test.go b/models/db/main_test.go index b774dce4d8..ce48502918 100644 --- a/models/db/main_test.go +++ b/models/db/main_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package db_test diff --git a/models/db/name.go b/models/db/name.go index a05d1a789b..51be33a8bc 100644 --- a/models/db/name.go +++ b/models/db/name.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package db diff --git a/models/db/paginator/main_test.go b/models/db/paginator/main_test.go index 1127987e53..b0557bc5a4 100644 --- a/models/db/paginator/main_test.go +++ b/models/db/paginator/main_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package paginator diff --git a/models/db/paginator/paginator.go b/models/db/paginator/paginator.go index 747539f30e..bcda47d978 100644 --- a/models/db/paginator/paginator.go +++ b/models/db/paginator/paginator.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package paginator diff --git a/models/db/paginator/paginator_test.go b/models/db/paginator/paginator_test.go index fdb8eee441..a1117fc7a4 100644 --- a/models/db/paginator/paginator_test.go +++ b/models/db/paginator/paginator_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package paginator diff --git a/models/db/search.go b/models/db/search.go index 704a48ed1e..f5273cb6f6 100644 --- a/models/db/search.go +++ b/models/db/search.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package db diff --git a/models/db/sequence.go b/models/db/sequence.go index 48e4a8f1ac..6d801d022f 100644 --- a/models/db/sequence.go +++ b/models/db/sequence.go @@ -1,10 +1,10 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package db import ( + "context" "fmt" "regexp" @@ -12,7 +12,7 @@ import ( ) // CountBadSequences looks for broken sequences from recreate-table mistakes -func CountBadSequences() (int64, error) { +func CountBadSequences(_ context.Context) (int64, error) { if !setting.Database.UsePostgreSQL { return 0, nil } @@ -33,7 +33,7 @@ func CountBadSequences() (int64, error) { } // FixBadSequences fixes for broken sequences from recreate-table mistakes -func FixBadSequences() error { +func FixBadSequences(_ context.Context) error { if !setting.Database.UsePostgreSQL { return nil } diff --git a/models/db/sql_postgres_with_schema.go b/models/db/sql_postgres_with_schema.go index 4bbd12bdeb..ec63447f6f 100644 --- a/models/db/sql_postgres_with_schema.go +++ b/models/db/sql_postgres_with_schema.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package db diff --git a/models/error.go b/models/error.go index f4c4bc8f67..8223f23585 100644 --- a/models/error.go +++ b/models/error.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package models diff --git a/models/fixture_generation.go b/models/fixture_generation.go index f4644859eb..abf880ee8e 100644 --- a/models/fixture_generation.go +++ b/models/fixture_generation.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package models @@ -22,7 +21,7 @@ func GetYamlFixturesAccess() (string, error) { } for _, repo := range repos { - repo.MustOwner() + repo.MustOwner(db.DefaultContext) if err := access_model.RecalculateAccesses(db.DefaultContext, repo); err != nil { return "", err } diff --git a/models/fixture_test.go b/models/fixture_test.go index 0857341e44..8a28db8164 100644 --- a/models/fixture_test.go +++ b/models/fixture_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package models diff --git a/models/fixtures/repo_unit.yml b/models/fixtures/repo_unit.yml index 59ab618340..73db47218b 100644 --- a/models/fixtures/repo_unit.yml +++ b/models/fixtures/repo_unit.yml @@ -544,3 +544,9 @@ repo_id: 51 type: 2 created_unix: 946684810 + +- + id: 80 + repo_id: 53 + type: 1 + created_unix: 946684810 diff --git a/models/fixtures/repository.yml b/models/fixtures/repository.yml index f09953be7e..a5a3dd0601 100644 --- a/models/fixtures/repository.yml +++ b/models/fixtures/repository.yml @@ -1558,3 +1558,30 @@ size: 0 is_fsck_enabled: true close_issues_via_commit_in_any_branch: false + +- + id: 53 + owner_id: 30 + owner_name: user30 + lower_name: renderer + name: renderer + is_archived: false + is_empty: false + is_private: false + num_issues: 0 + num_closed_issues: 0 + num_pulls: 0 + num_closed_pulls: 0 + num_milestones: 0 + num_closed_milestones: 0 + num_watches: 0 + num_projects: 0 + num_closed_projects: 0 + status: 0 + is_fork: false + fork_id: 0 + is_template: false + template_id: 0 + size: 0 + is_fsck_enabled: true + close_issues_via_commit_in_any_branch: false diff --git a/models/fixtures/user.yml b/models/fixtures/user.yml index 0e3348e146..1b870e8999 100644 --- a/models/fixtures/user.yml +++ b/models/fixtures/user.yml @@ -1102,7 +1102,7 @@ num_followers: 0 num_following: 0 num_stars: 0 - num_repos: 3 + num_repos: 4 num_teams: 0 num_members: 0 visibility: 0 diff --git a/models/foreignreference/error.go b/models/foreignreference/error.go index a1db773cd2..07ed1052a6 100644 --- a/models/foreignreference/error.go +++ b/models/foreignreference/error.go @@ -1,6 +1,5 @@ // Copyright 2022 Gitea. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package foreignreference diff --git a/models/foreignreference/foreignreference.go b/models/foreignreference/foreignreference.go index cc657a0fbe..2d2ad04c5a 100644 --- a/models/foreignreference/foreignreference.go +++ b/models/foreignreference/foreignreference.go @@ -1,6 +1,5 @@ // Copyright 2022 Gitea. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package foreignreference diff --git a/models/git/branches.go b/models/git/branches.go index b17d762dbe..c02ab0a888 100644 --- a/models/git/branches.go +++ b/models/git/branches.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package git @@ -74,10 +73,10 @@ func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool { } if !protectBranch.EnableWhitelist { - if user, err := user_model.GetUserByID(userID); err != nil { + if user, err := user_model.GetUserByID(db.DefaultContext, userID); err != nil { log.Error("GetUserByID: %v", err) return false - } else if repo, err := repo_model.GetRepositoryByID(protectBranch.RepoID); err != nil { + } else if repo, err := repo_model.GetRepositoryByID(db.DefaultContext, protectBranch.RepoID); err != nil { log.Error("repo_model.GetRepositoryByID: %v", err) return false } else if writeAccess, err := access_model.HasAccessUnit(db.DefaultContext, user, repo, unit.TypeCode, perm.AccessModeWrite); err != nil { @@ -128,13 +127,8 @@ func IsUserMergeWhitelisted(ctx context.Context, protectBranch *ProtectedBranch, } // IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals) -func IsUserOfficialReviewer(protectBranch *ProtectedBranch, user *user_model.User) (bool, error) { - return IsUserOfficialReviewerCtx(db.DefaultContext, protectBranch, user) -} - -// IsUserOfficialReviewerCtx check if user is official reviewer for the branch (counts towards required approvals) -func IsUserOfficialReviewerCtx(ctx context.Context, protectBranch *ProtectedBranch, user *user_model.User) (bool, error) { - repo, err := repo_model.GetRepositoryByIDCtx(ctx, protectBranch.RepoID) +func IsUserOfficialReviewer(ctx context.Context, protectBranch *ProtectedBranch, user *user_model.User) (bool, error) { + repo, err := repo_model.GetRepositoryByID(ctx, protectBranch.RepoID) if err != nil { return false, err } @@ -376,7 +370,7 @@ func updateUserWhitelist(ctx context.Context, repo *repo_model.Repository, curre whitelist = make([]int64, 0, len(newWhitelist)) for _, userID := range newWhitelist { - user, err := user_model.GetUserByIDCtx(ctx, userID) + user, err := user_model.GetUserByID(ctx, userID) if err != nil { return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %w", userID, repo.ID, err) } @@ -495,8 +489,8 @@ func RemoveDeletedBranchByID(repoID, id int64) (err error) { // LoadUser loads the user that deleted the branch // When there's no user found it returns a user_model.NewGhostUser -func (deletedBranch *DeletedBranch) LoadUser() { - user, err := user_model.GetUserByID(deletedBranch.DeletedByID) +func (deletedBranch *DeletedBranch) LoadUser(ctx context.Context) { + user, err := user_model.GetUserByID(ctx, deletedBranch.DeletedByID) if err != nil { user = user_model.NewGhostUser() } @@ -544,7 +538,7 @@ func FindRenamedBranch(repoID int64, from string) (branch *RenamedBranch, exist // RenameBranch rename a branch func RenameBranch(repo *repo_model.Repository, from, to string, gitAction func(isDefault bool) error) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/git/branches_test.go b/models/git/branches_test.go index 58c4ad027b..56f416622e 100644 --- a/models/git/branches_test.go +++ b/models/git/branches_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package git_test @@ -49,13 +48,13 @@ func TestDeletedBranchLoadUser(t *testing.T) { branch := getDeletedBranch(t, firstBranch) assert.Nil(t, branch.DeletedBy) - branch.LoadUser() + branch.LoadUser(db.DefaultContext) assert.NotNil(t, branch.DeletedBy) assert.Equal(t, "user1", branch.DeletedBy.Name) branch = getDeletedBranch(t, secondBranch) assert.Nil(t, branch.DeletedBy) - branch.LoadUser() + branch.LoadUser(db.DefaultContext) assert.NotNil(t, branch.DeletedBy) assert.Equal(t, "Ghost", branch.DeletedBy.Name) } @@ -102,7 +101,7 @@ func TestRenameBranch(t *testing.T) { repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) _isDefault := false - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) defer committer.Close() assert.NoError(t, err) assert.NoError(t, git_model.UpdateProtectBranch(ctx, repo1, &git_model.ProtectedBranch{ diff --git a/models/git/commit_status.go b/models/git/commit_status.go index 620baa036c..0fb0bc66af 100644 --- a/models/git/commit_status.go +++ b/models/git/commit_status.go @@ -1,14 +1,15 @@ // Copyright 2017 Gitea. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package git import ( "context" "crypto/sha1" + "errors" "fmt" "net/url" + "strconv" "strings" "time" @@ -49,90 +50,77 @@ func init() { db.RegisterModel(new(CommitStatusIndex)) } -// upsertCommitStatusIndex the function will not return until it acquires the lock or receives an error. -func upsertCommitStatusIndex(ctx context.Context, repoID int64, sha string) (err error) { - // An atomic UPSERT operation (INSERT/UPDATE) is the only operation - // that ensures that the key is actually locked. - switch { - case setting.Database.UseSQLite3 || setting.Database.UsePostgreSQL: - _, err = db.Exec(ctx, "INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+ - "VALUES (?,?,1) ON CONFLICT (repo_id,sha) DO UPDATE SET max_index = `commit_status_index`.max_index+1", - repoID, sha) - case setting.Database.UseMySQL: - _, err = db.Exec(ctx, "INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+ - "VALUES (?,?,1) ON DUPLICATE KEY UPDATE max_index = max_index+1", - repoID, sha) - case setting.Database.UseMSSQL: - // https://weblogs.sqlteam.com/dang/2009/01/31/upsert-race-condition-with-merge/ - _, err = db.Exec(ctx, "MERGE `commit_status_index` WITH (HOLDLOCK) as target "+ - "USING (SELECT ? AS repo_id, ? AS sha) AS src "+ - "ON src.repo_id = target.repo_id AND src.sha = target.sha "+ - "WHEN MATCHED THEN UPDATE SET target.max_index = target.max_index+1 "+ - "WHEN NOT MATCHED THEN INSERT (repo_id, sha, max_index) "+ - "VALUES (src.repo_id, src.sha, 1);", - repoID, sha) - default: - return fmt.Errorf("database type not supported") +func postgresGetCommitStatusIndex(ctx context.Context, repoID int64, sha string) (int64, error) { + res, err := db.GetEngine(ctx).Query("INSERT INTO `commit_status_index` (repo_id, sha, max_index) "+ + "VALUES (?,?,1) ON CONFLICT (repo_id, sha) DO UPDATE SET max_index = `commit_status_index`.max_index+1 RETURNING max_index", + repoID, sha) + if err != nil { + return 0, err } - return err + if len(res) == 0 { + return 0, db.ErrGetResourceIndexFailed + } + return strconv.ParseInt(string(res[0]["max_index"]), 10, 64) } // GetNextCommitStatusIndex retried 3 times to generate a resource index -func GetNextCommitStatusIndex(repoID int64, sha string) (int64, error) { - for i := 0; i < db.MaxDupIndexAttempts; i++ { - idx, err := getNextCommitStatusIndex(repoID, sha) - if err == db.ErrResouceOutdated { - continue - } +func GetNextCommitStatusIndex(ctx context.Context, repoID int64, sha string) (int64, error) { + if setting.Database.UsePostgreSQL { + return postgresGetCommitStatusIndex(ctx, repoID, sha) + } + + e := db.GetEngine(ctx) + + // try to update the max_index to next value, and acquire the write-lock for the record + res, err := e.Exec("UPDATE `commit_status_index` SET max_index=max_index+1 WHERE repo_id=? AND sha=?", repoID, sha) + if err != nil { + return 0, err + } + affected, err := res.RowsAffected() + if err != nil { + return 0, err + } + if affected == 0 { + // this slow path is only for the first time of creating a resource index + _, errIns := e.Exec("INSERT INTO `commit_status_index` (repo_id, sha, max_index) VALUES (?, ?, 0)", repoID, sha) + res, err = e.Exec("UPDATE `commit_status_index` SET max_index=max_index+1 WHERE repo_id=? AND sha=?", repoID, sha) if err != nil { return 0, err } - return idx, nil - } - return 0, db.ErrGetResourceIndexFailed -} - -// getNextCommitStatusIndex return the next index -func getNextCommitStatusIndex(repoID int64, sha string) (int64, error) { - ctx, commiter, err := db.TxContext() - if err != nil { - return 0, err - } - defer commiter.Close() - - var preIdx int64 - _, err = db.GetEngine(ctx).SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id = ? AND sha = ?", repoID, sha).Get(&preIdx) - if err != nil { - return 0, err + affected, err = res.RowsAffected() + if err != nil { + return 0, err + } + // if the update still can not update any records, the record must not exist and there must be some errors (insert error) + if affected == 0 { + if errIns == nil { + return 0, errors.New("impossible error when GetNextCommitStatusIndex, insert and update both succeeded but no record is updated") + } + return 0, errIns + } } - if err := upsertCommitStatusIndex(ctx, repoID, sha); err != nil { - return 0, err - } - - var curIdx int64 - has, err := db.GetEngine(ctx).SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id = ? AND sha = ? AND max_index=?", repoID, sha, preIdx+1).Get(&curIdx) + // now, the new index is in database (protected by the transaction and write-lock) + var newIdx int64 + has, err := e.SQL("SELECT max_index FROM `commit_status_index` WHERE repo_id=? AND sha=?", repoID, sha).Get(&newIdx) if err != nil { return 0, err } if !has { - return 0, db.ErrResouceOutdated + return 0, errors.New("impossible error when GetNextCommitStatusIndex, upsert succeeded but no record can be selected") } - if err := commiter.Commit(); err != nil { - return 0, err - } - return curIdx, nil + return newIdx, nil } func (status *CommitStatus) loadAttributes(ctx context.Context) (err error) { if status.Repo == nil { - status.Repo, err = repo_model.GetRepositoryByIDCtx(ctx, status.RepoID) + status.Repo, err = repo_model.GetRepositoryByID(ctx, status.RepoID) if err != nil { return fmt.Errorf("getRepositoryByID [%d]: %w", status.RepoID, err) } } if status.Creator == nil && status.CreatorID > 0 { - status.Creator, err = user_model.GetUserByIDCtx(ctx, status.CreatorID) + status.Creator, err = user_model.GetUserByID(ctx, status.CreatorID) if err != nil { return fmt.Errorf("getUserByID [%d]: %w", status.CreatorID, err) } @@ -291,18 +279,18 @@ func NewCommitStatus(opts NewCommitStatusOptions) error { return fmt.Errorf("NewCommitStatus[%s, %s]: no user specified", repoPath, opts.SHA) } - // Get the next Status Index - idx, err := GetNextCommitStatusIndex(opts.Repo.ID, opts.SHA) - if err != nil { - return fmt.Errorf("generate commit status index failed: %w", err) - } - - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return fmt.Errorf("NewCommitStatus[repo_id: %d, user_id: %d, sha: %s]: %w", opts.Repo.ID, opts.Creator.ID, opts.SHA, err) } defer committer.Close() + // Get the next Status Index + idx, err := GetNextCommitStatusIndex(ctx, opts.Repo.ID, opts.SHA) + if err != nil { + return fmt.Errorf("generate commit status index failed: %w", err) + } + opts.CommitStatus.Description = strings.TrimSpace(opts.CommitStatus.Description) opts.CommitStatus.Context = strings.TrimSpace(opts.CommitStatus.Context) opts.CommitStatus.TargetURL = strings.TrimSpace(opts.CommitStatus.TargetURL) @@ -316,7 +304,7 @@ func NewCommitStatus(opts NewCommitStatusOptions) error { // Insert new CommitStatus if _, err = db.GetEngine(ctx).Insert(opts.CommitStatus); err != nil { - return fmt.Errorf("Insert CommitStatus[%s, %s]: %w", repoPath, opts.SHA, err) + return fmt.Errorf("insert CommitStatus[%s, %s]: %w", repoPath, opts.SHA, err) } return committer.Commit() diff --git a/models/git/commit_status_test.go b/models/git/commit_status_test.go index 7b81b1549c..c829673014 100644 --- a/models/git/commit_status_test.go +++ b/models/git/commit_status_test.go @@ -1,6 +1,5 @@ // Copyright 2017 Gitea. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package git_test diff --git a/models/git/lfs.go b/models/git/lfs.go index 58042edfdb..8d418b928d 100644 --- a/models/git/lfs.go +++ b/models/git/lfs.go @@ -1,12 +1,12 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package git import ( "context" "fmt" + "time" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/perm" @@ -15,6 +15,7 @@ import ( user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/lfs" "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/util" @@ -137,7 +138,7 @@ var ErrLFSObjectNotExist = db.ErrNotExist{Resource: "LFS Meta object"} func NewLFSMetaObject(m *LFSMetaObject) (*LFSMetaObject, error) { var err error - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } @@ -181,11 +182,17 @@ func GetLFSMetaObjectByOid(repoID int64, oid string) (*LFSMetaObject, error) { // RemoveLFSMetaObjectByOid removes a LFSMetaObject entry from database by its OID. // It may return ErrLFSObjectNotExist or a database error. func RemoveLFSMetaObjectByOid(repoID int64, oid string) (int64, error) { + return RemoveLFSMetaObjectByOidFn(repoID, oid, nil) +} + +// RemoveLFSMetaObjectByOidFn removes a LFSMetaObject entry from database by its OID. +// It may return ErrLFSObjectNotExist or a database error. It will run Fn with the current count within the transaction +func RemoveLFSMetaObjectByOidFn(repoID int64, oid string, fn func(count int64) error) (int64, error) { if len(oid) == 0 { return 0, ErrLFSObjectNotExist } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return 0, err } @@ -201,6 +208,12 @@ func RemoveLFSMetaObjectByOid(repoID int64, oid string) (int64, error) { return count, err } + if fn != nil { + if err := fn(count); err != nil { + return count, err + } + } + return count, committer.Commit() } @@ -235,14 +248,14 @@ func LFSObjectAccessible(user *user_model.User, oid string) (bool, error) { return count > 0, err } -// LFSObjectIsAssociated checks if a provided Oid is associated -func LFSObjectIsAssociated(oid string) (bool, error) { - return db.GetEngine(db.DefaultContext).Exist(&LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}}) +// ExistsLFSObject checks if a provided Oid exists within the DB +func ExistsLFSObject(ctx context.Context, oid string) (bool, error) { + return db.GetEngine(ctx).Exist(&LFSMetaObject{Pointer: lfs.Pointer{Oid: oid}}) } // LFSAutoAssociate auto associates accessible LFSMetaObjects func LFSAutoAssociate(metas []*LFSMetaObject, user *user_model.User, repoID int64) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -320,3 +333,43 @@ func GetRepoLFSSize(ctx context.Context, repoID int64) (int64, error) { } return lfsSize, nil } + +type IterateLFSMetaObjectsForRepoOptions struct { + OlderThan time.Time +} + +// IterateLFSMetaObjectsForRepo provides a iterator for LFSMetaObjects per Repo +func IterateLFSMetaObjectsForRepo(ctx context.Context, repoID int64, f func(context.Context, *LFSMetaObject, int64) error, opts *IterateLFSMetaObjectsForRepoOptions) error { + var start int + batchSize := setting.Database.IterateBufferSize + engine := db.GetEngine(ctx) + type CountLFSMetaObject struct { + Count int64 + LFSMetaObject + } + + for { + beans := make([]*CountLFSMetaObject, 0, batchSize) + // SELECT `lfs_meta_object`.*, COUNT(`l1`.id) as `count` FROM lfs_meta_object INNER JOIN lfs_meta_object AS l1 ON l1.oid = lfs_meta_object.oid WHERE lfs_meta_object.repository_id = ? GROUP BY lfs_meta_object.id + sess := engine.Select("`lfs_meta_object`.*, COUNT(`l1`.oid) AS `count`"). + Join("INNER", "`lfs_meta_object` AS l1", "`lfs_meta_object`.oid = `l1`.oid"). + Where("`lfs_meta_object`.repository_id = ?", repoID) + if !opts.OlderThan.IsZero() { + sess.And("`lfs_meta_object`.created_unix < ?", opts.OlderThan) + } + sess.GroupBy("`lfs_meta_object`.id") + if err := sess.Limit(batchSize, start).Find(&beans); err != nil { + return err + } + if len(beans) == 0 { + return nil + } + start += len(beans) + + for _, bean := range beans { + if err := f(ctx, &bean.LFSMetaObject, bean.Count); err != nil { + return err + } + } + } +} diff --git a/models/git/lfs_lock.go b/models/git/lfs_lock.go index 016db899a9..dc5b0a2ced 100644 --- a/models/git/lfs_lock.go +++ b/models/git/lfs_lock.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package git @@ -44,7 +43,7 @@ func cleanPath(p string) string { // CreateLFSLock creates a new lock. func CreateLFSLock(repo *repo_model.Repository, lock *LFSLock) (*LFSLock, error) { - dbCtx, committer, err := db.TxContext() + dbCtx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } @@ -137,7 +136,7 @@ func CountLFSLockByRepoID(repoID int64) (int64, error) { // DeleteLFSLockByID deletes a lock by given ID. func DeleteLFSLockByID(id int64, repo *repo_model.Repository, u *user_model.User, force bool) (*LFSLock, error) { - dbCtx, committer, err := db.TxContext() + dbCtx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } @@ -168,7 +167,7 @@ func CheckLFSAccessForRepo(ctx context.Context, ownerID int64, repo *repo_model. if ownerID == 0 { return ErrLFSUnauthorizedAction{repo.ID, "undefined", mode} } - u, err := user_model.GetUserByIDCtx(ctx, ownerID) + u, err := user_model.GetUserByID(ctx, ownerID) if err != nil { return err } diff --git a/models/git/main_test.go b/models/git/main_test.go index 41e6ac4704..5ef9cde607 100644 --- a/models/git/main_test.go +++ b/models/git/main_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package git_test diff --git a/models/git/protected_tag.go b/models/git/protected_tag.go index 7c3881643d..1d32b11366 100644 --- a/models/git/protected_tag.go +++ b/models/git/protected_tag.go @@ -1,10 +1,10 @@ // 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. +// SPDX-License-Identifier: MIT package git import ( + "context" "regexp" "strings" @@ -69,13 +69,13 @@ func UpdateProtectedTag(pt *ProtectedTag) error { } // DeleteProtectedTag deletes a protected tag by ID -func DeleteProtectedTag(pt *ProtectedTag) error { - _, err := db.GetEngine(db.DefaultContext).ID(pt.ID).Delete(&ProtectedTag{}) +func DeleteProtectedTag(ctx context.Context, pt *ProtectedTag) error { + _, err := db.GetEngine(ctx).ID(pt.ID).Delete(&ProtectedTag{}) return err } // IsUserAllowedModifyTag returns true if the user is allowed to modify the tag -func IsUserAllowedModifyTag(pt *ProtectedTag, userID int64) (bool, error) { +func IsUserAllowedModifyTag(ctx context.Context, pt *ProtectedTag, userID int64) (bool, error) { if base.Int64sContains(pt.AllowlistUserIDs, userID) { return true, nil } @@ -84,7 +84,7 @@ func IsUserAllowedModifyTag(pt *ProtectedTag, userID int64) (bool, error) { return false, nil } - in, err := organization.IsUserInTeams(db.DefaultContext, userID, pt.AllowlistTeamIDs) + in, err := organization.IsUserInTeams(ctx, userID, pt.AllowlistTeamIDs) if err != nil { return false, err } @@ -92,9 +92,9 @@ func IsUserAllowedModifyTag(pt *ProtectedTag, userID int64) (bool, error) { } // GetProtectedTags gets all protected tags of the repository -func GetProtectedTags(repoID int64) ([]*ProtectedTag, error) { +func GetProtectedTags(ctx context.Context, repoID int64) ([]*ProtectedTag, error) { tags := make([]*ProtectedTag, 0) - return tags, db.GetEngine(db.DefaultContext).Find(&tags, &ProtectedTag{RepoID: repoID}) + return tags, db.GetEngine(ctx).Find(&tags, &ProtectedTag{RepoID: repoID}) } // GetProtectedTagByID gets the protected tag with the specific id @@ -112,7 +112,7 @@ func GetProtectedTagByID(id int64) (*ProtectedTag, error) { // IsUserAllowedToControlTag checks if a user can control the specific tag. // It returns true if the tag name is not protected or the user is allowed to control it. -func IsUserAllowedToControlTag(tags []*ProtectedTag, tagName string, userID int64) (bool, error) { +func IsUserAllowedToControlTag(ctx context.Context, tags []*ProtectedTag, tagName string, userID int64) (bool, error) { isAllowed := true for _, tag := range tags { err := tag.EnsureCompiledPattern() @@ -124,7 +124,7 @@ func IsUserAllowedToControlTag(tags []*ProtectedTag, tagName string, userID int6 continue } - isAllowed, err = IsUserAllowedModifyTag(tag, userID) + isAllowed, err = IsUserAllowedModifyTag(ctx, tag, userID) if err != nil { return false, err } diff --git a/models/git/protected_tag_test.go b/models/git/protected_tag_test.go index b496688b25..164c33e28f 100644 --- a/models/git/protected_tag_test.go +++ b/models/git/protected_tag_test.go @@ -1,12 +1,12 @@ // 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. +// SPDX-License-Identifier: MIT package git_test import ( "testing" + "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" "code.gitea.io/gitea/models/unittest" @@ -17,29 +17,29 @@ func TestIsUserAllowed(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) pt := &git_model.ProtectedTag{} - allowed, err := git_model.IsUserAllowedModifyTag(pt, 1) + allowed, err := git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1) assert.NoError(t, err) assert.False(t, allowed) pt = &git_model.ProtectedTag{ AllowlistUserIDs: []int64{1}, } - allowed, err = git_model.IsUserAllowedModifyTag(pt, 1) + allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1) assert.NoError(t, err) assert.True(t, allowed) - allowed, err = git_model.IsUserAllowedModifyTag(pt, 2) + allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2) assert.NoError(t, err) assert.False(t, allowed) pt = &git_model.ProtectedTag{ AllowlistTeamIDs: []int64{1}, } - allowed, err = git_model.IsUserAllowedModifyTag(pt, 1) + allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1) assert.NoError(t, err) assert.False(t, allowed) - allowed, err = git_model.IsUserAllowedModifyTag(pt, 2) + allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2) assert.NoError(t, err) assert.True(t, allowed) @@ -47,11 +47,11 @@ func TestIsUserAllowed(t *testing.T) { AllowlistUserIDs: []int64{1}, AllowlistTeamIDs: []int64{1}, } - allowed, err = git_model.IsUserAllowedModifyTag(pt, 1) + allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1) assert.NoError(t, err) assert.True(t, allowed) - allowed, err = git_model.IsUserAllowedModifyTag(pt, 2) + allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2) assert.NoError(t, err) assert.True(t, allowed) } @@ -135,7 +135,7 @@ func TestIsUserAllowedToControlTag(t *testing.T) { } for n, c := range cases { - isAllowed, err := git_model.IsUserAllowedToControlTag(protectedTags, c.name, c.userid) + isAllowed, err := git_model.IsUserAllowedToControlTag(db.DefaultContext, protectedTags, c.name, c.userid) assert.NoError(t, err) assert.Equal(t, c.allowed, isAllowed, "case %d: error should match", n) } @@ -157,7 +157,7 @@ func TestIsUserAllowedToControlTag(t *testing.T) { } for n, c := range cases { - isAllowed, err := git_model.IsUserAllowedToControlTag(protectedTags, c.name, c.userid) + isAllowed, err := git_model.IsUserAllowedToControlTag(db.DefaultContext, protectedTags, c.name, c.userid) assert.NoError(t, err) assert.Equal(t, c.allowed, isAllowed, "case %d: error should match", n) } diff --git a/models/issues/assignees.go b/models/issues/assignees.go index d960d5ebaf..159086bd01 100644 --- a/models/issues/assignees.go +++ b/models/issues/assignees.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package issues @@ -48,9 +47,10 @@ func (issue *Issue) LoadAssignees(ctx context.Context) (err error) { // GetAssigneeIDsByIssue returns the IDs of users assigned to an issue // but skips joining with `user` for performance reasons. // User permissions must be verified elsewhere if required. -func GetAssigneeIDsByIssue(issueID int64) ([]int64, error) { +func GetAssigneeIDsByIssue(ctx context.Context, issueID int64) ([]int64, error) { userIDs := make([]int64, 0, 5) - return userIDs, db.GetEngine(db.DefaultContext).Table("issue_assignees"). + return userIDs, db.GetEngine(ctx). + Table("issue_assignees"). Cols("assignee_id"). Where("issue_id = ?", issueID). Distinct("assignee_id"). @@ -64,7 +64,7 @@ func IsUserAssignedToIssue(ctx context.Context, issue *Issue, user *user_model.U // ToggleIssueAssignee changes a user between assigned and not assigned for this issue, and make issue comment for it. func ToggleIssueAssignee(issue *Issue, doer *user_model.User, assigneeID int64) (removed bool, comment *Comment, err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return false, nil, err } @@ -102,7 +102,7 @@ func toggleIssueAssignee(ctx context.Context, issue *Issue, doer *user_model.Use AssigneeID: assigneeID, } // Comment - comment, err = CreateCommentCtx(ctx, opts) + comment, err = CreateComment(ctx, opts) if err != nil { return false, nil, fmt.Errorf("createComment: %w", err) } @@ -118,7 +118,7 @@ func toggleIssueAssignee(ctx context.Context, issue *Issue, doer *user_model.Use // toggles user assignee state in database func toggleUserAssignee(ctx context.Context, issue *Issue, assigneeID int64) (removed bool, err error) { // Check if the user exists - assignee, err := user_model.GetUserByIDCtx(ctx, assigneeID) + assignee, err := user_model.GetUserByID(ctx, assigneeID) if err != nil { return false, err } @@ -151,7 +151,7 @@ func toggleUserAssignee(ctx context.Context, issue *Issue, assigneeID int64) (re } // MakeIDsFromAPIAssigneesToAdd returns an array with all assignee IDs -func MakeIDsFromAPIAssigneesToAdd(oneAssignee string, multipleAssignees []string) (assigneeIDs []int64, err error) { +func MakeIDsFromAPIAssigneesToAdd(ctx context.Context, oneAssignee string, multipleAssignees []string) (assigneeIDs []int64, err error) { var requestAssignees []string // Keeping the old assigning method for compatibility reasons @@ -165,7 +165,7 @@ func MakeIDsFromAPIAssigneesToAdd(oneAssignee string, multipleAssignees []string } // Get the IDs of all assignees - assigneeIDs, err = user_model.GetUserIDsByNames(requestAssignees, false) + assigneeIDs, err = user_model.GetUserIDsByNames(ctx, requestAssignees, false) return assigneeIDs, err } diff --git a/models/issues/assignees_test.go b/models/issues/assignees_test.go index 291bb673da..8a2cef8acd 100644 --- a/models/issues/assignees_test.go +++ b/models/issues/assignees_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package issues_test @@ -23,17 +22,17 @@ func TestUpdateAssignee(t *testing.T) { assert.NoError(t, err) // Assign multiple users - user2, err := user_model.GetUserByID(2) + user2, err := user_model.GetUserByID(db.DefaultContext, 2) assert.NoError(t, err) _, _, err = issues_model.ToggleIssueAssignee(issue, &user_model.User{ID: 1}, user2.ID) assert.NoError(t, err) - user3, err := user_model.GetUserByID(3) + user3, err := user_model.GetUserByID(db.DefaultContext, 3) assert.NoError(t, err) _, _, err = issues_model.ToggleIssueAssignee(issue, &user_model.User{ID: 1}, user3.ID) assert.NoError(t, err) - user1, err := user_model.GetUserByID(1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him + user1, err := user_model.GetUserByID(db.DefaultContext, 1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him assert.NoError(t, err) _, _, err = issues_model.ToggleIssueAssignee(issue, &user_model.User{ID: 1}, user1.ID) assert.NoError(t, err) @@ -71,22 +70,22 @@ func TestMakeIDsFromAPIAssigneesToAdd(t *testing.T) { _ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) _ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - IDs, err := issues_model.MakeIDsFromAPIAssigneesToAdd("", []string{""}) + IDs, err := issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{""}) assert.NoError(t, err) assert.Equal(t, []int64{}, IDs) - _, err = issues_model.MakeIDsFromAPIAssigneesToAdd("", []string{"none_existing_user"}) + _, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{"none_existing_user"}) assert.Error(t, err) - IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd("user1", []string{"user1"}) + IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "user1", []string{"user1"}) assert.NoError(t, err) assert.Equal(t, []int64{1}, IDs) - IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd("user2", []string{""}) + IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "user2", []string{""}) assert.NoError(t, err) assert.Equal(t, []int64{2}, IDs) - IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd("", []string{"user1", "user2"}) + IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{"user1", "user2"}) assert.NoError(t, err) assert.Equal(t, []int64{1, 2}, IDs) } diff --git a/models/issues/comment.go b/models/issues/comment.go index fe692bd588..8716774832 100644 --- a/models/issues/comment.go +++ b/models/issues/comment.go @@ -1,8 +1,7 @@ // Copyright 2018 The Gitea Authors. // Copyright 2016 The Gogs Authors. // All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package issues @@ -310,13 +309,8 @@ type PushActionContent struct { CommitIDs []string `json:"commit_ids"` } -// LoadIssue loads issue from database -func (c *Comment) LoadIssue() (err error) { - return c.LoadIssueCtx(db.DefaultContext) -} - -// LoadIssueCtx loads issue from database -func (c *Comment) LoadIssueCtx(ctx context.Context) (err error) { +// LoadIssue loads the issue reference for the comment +func (c *Comment) LoadIssue(ctx context.Context) (err error) { if c.Issue != nil { return nil } @@ -351,12 +345,13 @@ func (c *Comment) AfterLoad(session *xorm.Session) { } } -func (c *Comment) loadPoster(ctx context.Context) (err error) { +// LoadPoster loads comment poster +func (c *Comment) LoadPoster(ctx context.Context) (err error) { if c.PosterID <= 0 || c.Poster != nil { return nil } - c.Poster, err = user_model.GetUserByIDCtx(ctx, c.PosterID) + c.Poster, err = user_model.GetUserByID(ctx, c.PosterID) if err != nil { if user_model.IsErrUserNotExist(err) { c.PosterID = -1 @@ -382,7 +377,7 @@ func (c *Comment) AfterDelete() { // HTMLURL formats a URL-string to the issue-comment func (c *Comment) HTMLURL() string { - err := c.LoadIssue() + err := c.LoadIssue(db.DefaultContext) if err != nil { // Silently dropping errors :unamused: log.Error("LoadIssue(%d): %v", c.IssueID, err) return "" @@ -411,7 +406,7 @@ func (c *Comment) HTMLURL() string { // APIURL formats a API-string to the issue-comment func (c *Comment) APIURL() string { - err := c.LoadIssue() + err := c.LoadIssue(db.DefaultContext) if err != nil { // Silently dropping errors :unamused: log.Error("LoadIssue(%d): %v", c.IssueID, err) return "" @@ -427,7 +422,7 @@ func (c *Comment) APIURL() string { // IssueURL formats a URL-string to the issue func (c *Comment) IssueURL() string { - err := c.LoadIssue() + err := c.LoadIssue(db.DefaultContext) if err != nil { // Silently dropping errors :unamused: log.Error("LoadIssue(%d): %v", c.IssueID, err) return "" @@ -447,7 +442,7 @@ func (c *Comment) IssueURL() string { // PRURL formats a URL-string to the pull-request func (c *Comment) PRURL() string { - err := c.LoadIssue() + err := c.LoadIssue(db.DefaultContext) if err != nil { // Silently dropping errors :unamused: log.Error("LoadIssue(%d): %v", c.IssueID, err) return "" @@ -522,10 +517,10 @@ func (c *Comment) LoadProject() error { } // LoadMilestone if comment.Type is CommentTypeMilestone, then load milestone -func (c *Comment) LoadMilestone() error { +func (c *Comment) LoadMilestone(ctx context.Context) error { if c.OldMilestoneID > 0 { var oldMilestone Milestone - has, err := db.GetEngine(db.DefaultContext).ID(c.OldMilestoneID).Get(&oldMilestone) + has, err := db.GetEngine(ctx).ID(c.OldMilestoneID).Get(&oldMilestone) if err != nil { return err } else if has { @@ -535,7 +530,7 @@ func (c *Comment) LoadMilestone() error { if c.MilestoneID > 0 { var milestone Milestone - has, err := db.GetEngine(db.DefaultContext).ID(c.MilestoneID).Get(&milestone) + has, err := db.GetEngine(ctx).ID(c.MilestoneID).Get(&milestone) if err != nil { return err } else if has { @@ -545,19 +540,14 @@ func (c *Comment) LoadMilestone() error { return nil } -// LoadPoster loads comment poster -func (c *Comment) LoadPoster() error { - return c.loadPoster(db.DefaultContext) -} - // LoadAttachments loads attachments (it never returns error, the error during `GetAttachmentsByCommentIDCtx` is ignored) -func (c *Comment) LoadAttachments() error { +func (c *Comment) LoadAttachments(ctx context.Context) error { if len(c.Attachments) > 0 { return nil } var err error - c.Attachments, err = repo_model.GetAttachmentsByCommentID(db.DefaultContext, c.ID) + c.Attachments, err = repo_model.GetAttachmentsByCommentID(ctx, c.ID) if err != nil { log.Error("getAttachmentsByCommentID[%d]: %v", c.ID, err) } @@ -566,7 +556,7 @@ func (c *Comment) LoadAttachments() error { // UpdateAttachments update attachments by UUIDs for the comment func (c *Comment) UpdateAttachments(uuids []string) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -591,7 +581,7 @@ func (c *Comment) LoadAssigneeUserAndTeam() error { var err error if c.AssigneeID > 0 && c.Assignee == nil { - c.Assignee, err = user_model.GetUserByIDCtx(db.DefaultContext, c.AssigneeID) + c.Assignee, err = user_model.GetUserByID(db.DefaultContext, c.AssigneeID) if err != nil { if !user_model.IsErrUserNotExist(err) { return err @@ -599,7 +589,7 @@ func (c *Comment) LoadAssigneeUserAndTeam() error { c.Assignee = user_model.NewGhostUser() } } else if c.AssigneeTeamID > 0 && c.AssigneeTeam == nil { - if err = c.LoadIssue(); err != nil { + if err = c.LoadIssue(db.DefaultContext); err != nil { return err } @@ -626,7 +616,7 @@ func (c *Comment) LoadResolveDoer() (err error) { if c.ResolveDoerID == 0 || c.Type != CommentTypeCode { return nil } - c.ResolveDoer, err = user_model.GetUserByIDCtx(db.DefaultContext, c.ResolveDoerID) + c.ResolveDoer, err = user_model.GetUserByID(db.DefaultContext, c.ResolveDoerID) if err != nil { if user_model.IsErrUserNotExist(err) { c.ResolveDoer = user_model.NewGhostUser() @@ -741,7 +731,7 @@ func (c *Comment) UnsignedLine() uint64 { // CodeCommentURL returns the url to a comment in code func (c *Comment) CodeCommentURL() string { - err := c.LoadIssue() + err := c.LoadIssue(db.DefaultContext) if err != nil { // Silently dropping errors :unamused: log.Error("LoadIssue(%d): %v", c.IssueID, err) return "" @@ -790,8 +780,8 @@ func (c *Comment) LoadPushCommits(ctx context.Context) (err error) { return err } -// CreateCommentCtx creates comment with context -func CreateCommentCtx(ctx context.Context, opts *CreateCommentOptions) (_ *Comment, err error) { +// CreateComment creates comment with context +func CreateComment(ctx context.Context, opts *CreateCommentOptions) (_ *Comment, err error) { e := db.GetEngine(ctx) var LabelID int64 if opts.Label != nil { @@ -886,6 +876,8 @@ func updateCommentInfos(ctx context.Context, opts *CreateCommentOptions, comment return fmt.Errorf("update attachment [%d]: %w", attachments[i].ID, err) } } + + comment.Attachments = attachments case CommentTypeReopen, CommentTypeClose: if err = repo_model.UpdateRepoIssueNumbers(ctx, opts.Issue.RepoID, opts.Issue.IsPull, true); err != nil { return err @@ -924,7 +916,7 @@ func createDeadlineComment(ctx context.Context, doer *user_model.User, issue *Is Issue: issue, Content: content, } - comment, err := CreateCommentCtx(ctx, opts) + comment, err := CreateComment(ctx, opts) if err != nil { return nil, err } @@ -949,7 +941,7 @@ func createIssueDependencyComment(ctx context.Context, doer *user_model.User, is Issue: issue, DependentIssueID: dependentIssue.ID, } - if _, err = CreateCommentCtx(ctx, opts); err != nil { + if _, err = CreateComment(ctx, opts); err != nil { return } @@ -960,7 +952,7 @@ func createIssueDependencyComment(ctx context.Context, doer *user_model.User, is Issue: dependentIssue, DependentIssueID: issue.ID, } - _, err = CreateCommentCtx(ctx, opts) + _, err = CreateComment(ctx, opts) return err } @@ -1002,55 +994,6 @@ type CreateCommentOptions struct { Invalidated bool } -// CreateComment creates comment of issue or commit. -func CreateComment(opts *CreateCommentOptions) (comment *Comment, err error) { - ctx, committer, err := db.TxContext() - if err != nil { - return nil, err - } - defer committer.Close() - - comment, err = CreateCommentCtx(ctx, opts) - if err != nil { - return nil, err - } - - if err = committer.Commit(); err != nil { - return nil, err - } - - return comment, nil -} - -// CreateRefComment creates a commit reference comment to issue. -func CreateRefComment(doer *user_model.User, repo *repo_model.Repository, issue *Issue, content, commitSHA string) error { - if len(commitSHA) == 0 { - return fmt.Errorf("cannot create reference with empty commit SHA") - } - - // Check if same reference from same commit has already existed. - has, err := db.GetEngine(db.DefaultContext).Get(&Comment{ - Type: CommentTypeCommitRef, - IssueID: issue.ID, - CommitSHA: commitSHA, - }) - if err != nil { - return fmt.Errorf("check reference comment: %w", err) - } else if has { - return nil - } - - _, err = CreateComment(&CreateCommentOptions{ - Type: CommentTypeCommitRef, - Doer: doer, - Repo: repo, - Issue: issue, - CommitSHA: commitSHA, - Content: content, - }) - return err -} - // GetCommentByID returns the comment by given ID. func GetCommentByID(ctx context.Context, id int64) (*Comment, error) { c := new(Comment) @@ -1136,7 +1079,7 @@ func CountComments(opts *FindCommentsOptions) (int64, error) { // UpdateComment updates information of comment. func UpdateComment(c *Comment, doer *user_model.User) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -1146,7 +1089,7 @@ func UpdateComment(c *Comment, doer *user_model.User) error { if _, err := sess.ID(c.ID).AllCols().Update(c); err != nil { return err } - if err := c.LoadIssueCtx(ctx); err != nil { + if err := c.LoadIssue(ctx); err != nil { return err } if err := c.AddCrossReferences(ctx, doer, true); err != nil { @@ -1246,7 +1189,7 @@ func findCodeComments(ctx context.Context, opts FindCommentsOptions, issue *Issu return nil, err } - if err := CommentList(comments).loadPosters(ctx); err != nil { + if err := CommentList(comments).LoadPosters(ctx); err != nil { return nil, err } @@ -1326,53 +1269,20 @@ func UpdateCommentsMigrationsByType(tp structs.GitServiceType, originalAuthorID return err } -// CreatePushPullComment create push code to pull base comment -func CreatePushPullComment(ctx context.Context, pusher *user_model.User, pr *PullRequest, oldCommitID, newCommitID string) (comment *Comment, err error) { - if pr.HasMerged || oldCommitID == "" || newCommitID == "" { - return nil, nil - } - - ops := &CreateCommentOptions{ - Type: CommentTypePullRequestPush, - Doer: pusher, - Repo: pr.BaseRepo, - } - - var data PushActionContent - - data.CommitIDs, data.IsForcePush, err = getCommitIDsFromRepo(ctx, pr.BaseRepo, oldCommitID, newCommitID, pr.BaseBranch) - if err != nil { - return nil, err - } - - ops.Issue = pr.Issue - - dataJSON, err := json.Marshal(data) - if err != nil { - return nil, err - } - - ops.Content = string(dataJSON) - - comment, err = CreateComment(ops) - - return comment, err -} - // CreateAutoMergeComment is a internal function, only use it for CommentTypePRScheduledToAutoMerge and CommentTypePRUnScheduledToAutoMerge CommentTypes func CreateAutoMergeComment(ctx context.Context, typ CommentType, pr *PullRequest, doer *user_model.User) (comment *Comment, err error) { if typ != CommentTypePRScheduledToAutoMerge && typ != CommentTypePRUnScheduledToAutoMerge { return nil, fmt.Errorf("comment type %d cannot be used to create an auto merge comment", typ) } - if err = pr.LoadIssueCtx(ctx); err != nil { + if err = pr.LoadIssue(ctx); err != nil { return } - if err = pr.LoadBaseRepoCtx(ctx); err != nil { + if err = pr.LoadBaseRepo(ctx); err != nil { return } - comment, err = CreateCommentCtx(ctx, &CreateCommentOptions{ + comment, err = CreateComment(ctx, &CreateCommentOptions{ Type: typ, Doer: doer, Repo: pr.BaseRepo, @@ -1381,120 +1291,6 @@ func CreateAutoMergeComment(ctx context.Context, typ CommentType, pr *PullReques return comment, err } -// getCommitsFromRepo get commit IDs from repo in between oldCommitID and newCommitID -// isForcePush will be true if oldCommit isn't on the branch -// Commit on baseBranch will skip -func getCommitIDsFromRepo(ctx context.Context, repo *repo_model.Repository, oldCommitID, newCommitID, baseBranch string) (commitIDs []string, isForcePush bool, err error) { - repoPath := repo.RepoPath() - gitRepo, closer, err := git.RepositoryFromContextOrOpen(ctx, repoPath) - if err != nil { - return nil, false, err - } - defer closer.Close() - - oldCommit, err := gitRepo.GetCommit(oldCommitID) - if err != nil { - return nil, false, err - } - - if err = oldCommit.LoadBranchName(); err != nil { - return nil, false, err - } - - if len(oldCommit.Branch) == 0 { - commitIDs = make([]string, 2) - commitIDs[0] = oldCommitID - commitIDs[1] = newCommitID - - return commitIDs, true, err - } - - newCommit, err := gitRepo.GetCommit(newCommitID) - if err != nil { - return nil, false, err - } - - commits, err := newCommit.CommitsBeforeUntil(oldCommitID) - if err != nil { - return nil, false, err - } - - commitIDs = make([]string, 0, len(commits)) - commitChecks := make(map[string]*commitBranchCheckItem) - - for _, commit := range commits { - commitChecks[commit.ID.String()] = &commitBranchCheckItem{ - Commit: commit, - Checked: false, - } - } - - if err = commitBranchCheck(gitRepo, newCommit, oldCommitID, baseBranch, commitChecks); err != nil { - return - } - - for i := len(commits) - 1; i >= 0; i-- { - commitID := commits[i].ID.String() - if item, ok := commitChecks[commitID]; ok && item.Checked { - commitIDs = append(commitIDs, commitID) - } - } - - return commitIDs, isForcePush, err -} - -type commitBranchCheckItem struct { - Commit *git.Commit - Checked bool -} - -func commitBranchCheck(gitRepo *git.Repository, startCommit *git.Commit, endCommitID, baseBranch string, commitList map[string]*commitBranchCheckItem) error { - if startCommit.ID.String() == endCommitID { - return nil - } - - checkStack := make([]string, 0, 10) - checkStack = append(checkStack, startCommit.ID.String()) - - for len(checkStack) > 0 { - commitID := checkStack[0] - checkStack = checkStack[1:] - - item, ok := commitList[commitID] - if !ok { - continue - } - - if item.Commit.ID.String() == endCommitID { - continue - } - - if err := item.Commit.LoadBranchName(); err != nil { - return err - } - - if item.Commit.Branch == baseBranch { - continue - } - - if item.Checked { - continue - } - - item.Checked = true - - parentNum := item.Commit.ParentCount() - for i := 0; i < parentNum; i++ { - parentCommit, err := item.Commit.Parent(i) - if err != nil { - return err - } - checkStack = append(checkStack, parentCommit.ID.String()) - } - } - return nil -} - // RemapExternalUser ExternalUserRemappable interface func (c *Comment) RemapExternalUser(externalName string, externalID, userID int64) error { c.OriginalAuthor = externalName @@ -1513,18 +1309,18 @@ func (c *Comment) GetExternalName() string { return c.OriginalAuthor } func (c *Comment) GetExternalID() int64 { return c.OriginalAuthorID } // CountCommentTypeLabelWithEmptyLabel count label comments with empty label -func CountCommentTypeLabelWithEmptyLabel() (int64, error) { - return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Count(new(Comment)) +func CountCommentTypeLabelWithEmptyLabel(ctx context.Context) (int64, error) { + return db.GetEngine(ctx).Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Count(new(Comment)) } // FixCommentTypeLabelWithEmptyLabel count label comments with empty label -func FixCommentTypeLabelWithEmptyLabel() (int64, error) { - return db.GetEngine(db.DefaultContext).Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Delete(new(Comment)) +func FixCommentTypeLabelWithEmptyLabel(ctx context.Context) (int64, error) { + return db.GetEngine(ctx).Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Delete(new(Comment)) } // CountCommentTypeLabelWithOutsideLabels count label comments with outside label -func CountCommentTypeLabelWithOutsideLabels() (int64, error) { - return db.GetEngine(db.DefaultContext).Where("comment.type = ? AND ((label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id))", CommentTypeLabel). +func CountCommentTypeLabelWithOutsideLabels(ctx context.Context) (int64, error) { + return db.GetEngine(ctx).Where("comment.type = ? AND ((label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id))", CommentTypeLabel). Table("comment"). Join("inner", "label", "label.id = comment.label_id"). Join("inner", "issue", "issue.id = comment.issue_id "). @@ -1533,8 +1329,8 @@ func CountCommentTypeLabelWithOutsideLabels() (int64, error) { } // FixCommentTypeLabelWithOutsideLabels count label comments with outside label -func FixCommentTypeLabelWithOutsideLabels() (int64, error) { - res, err := db.GetEngine(db.DefaultContext).Exec(`DELETE FROM comment WHERE comment.id IN ( +func FixCommentTypeLabelWithOutsideLabels(ctx context.Context) (int64, error) { + res, err := db.GetEngine(ctx).Exec(`DELETE FROM comment WHERE comment.id IN ( SELECT il_too.id FROM ( SELECT com.id FROM comment AS com @@ -1552,7 +1348,7 @@ func FixCommentTypeLabelWithOutsideLabels() (int64, error) { } func (c *Comment) GetIRI() string { - err := c.LoadIssue() + err := c.LoadIssue(db.DefaultContext) if err != nil { return "" } diff --git a/models/issues/comment_list.go b/models/issues/comment_list.go index 70105d7ff0..2b55bc212f 100644 --- a/models/issues/comment_list.go +++ b/models/issues/comment_list.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package issues @@ -24,7 +23,8 @@ func (comments CommentList) getPosterIDs() []int64 { return posterIDs.Values() } -func (comments CommentList) loadPosters(ctx context.Context) error { +// LoadPosters loads posters +func (comments CommentList) LoadPosters(ctx context.Context) error { if len(comments) == 0 { return nil } @@ -277,7 +277,8 @@ func (comments CommentList) Issues() IssueList { return issueList } -func (comments CommentList) loadIssues(ctx context.Context) error { +// LoadIssues loads issues of comments +func (comments CommentList) LoadIssues(ctx context.Context) error { if len(comments) == 0 { return nil } @@ -382,7 +383,8 @@ func (comments CommentList) loadDependentIssues(ctx context.Context) error { return nil } -func (comments CommentList) loadAttachments(ctx context.Context) (err error) { +// LoadAttachments loads attachments +func (comments CommentList) LoadAttachments(ctx context.Context) (err error) { if len(comments) == 0 { return nil } @@ -476,7 +478,7 @@ func (comments CommentList) loadReviews(ctx context.Context) error { //nolint // loadAttributes loads all attributes func (comments CommentList) loadAttributes(ctx context.Context) (err error) { - if err = comments.loadPosters(ctx); err != nil { + if err = comments.LoadPosters(ctx); err != nil { return } @@ -496,7 +498,7 @@ func (comments CommentList) loadAttributes(ctx context.Context) (err error) { return } - if err = comments.loadAttachments(ctx); err != nil { + if err = comments.LoadAttachments(ctx); err != nil { return } @@ -504,7 +506,7 @@ func (comments CommentList) loadAttributes(ctx context.Context) (err error) { return } - if err = comments.loadIssues(ctx); err != nil { + if err = comments.LoadIssues(ctx); err != nil { return } @@ -520,18 +522,3 @@ func (comments CommentList) loadAttributes(ctx context.Context) (err error) { func (comments CommentList) LoadAttributes() error { return comments.loadAttributes(db.DefaultContext) } - -// LoadAttachments loads attachments -func (comments CommentList) LoadAttachments() error { - return comments.loadAttachments(db.DefaultContext) -} - -// LoadPosters loads posters -func (comments CommentList) LoadPosters() error { - return comments.loadPosters(db.DefaultContext) -} - -// LoadIssues loads issues of comments -func (comments CommentList) LoadIssues() error { - return comments.loadIssues(db.DefaultContext) -} diff --git a/models/issues/comment_test.go b/models/issues/comment_test.go index f12da0177f..0d0570ae34 100644 --- a/models/issues/comment_test.go +++ b/models/issues/comment_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues_test @@ -25,7 +24,7 @@ func TestCreateComment(t *testing.T) { doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) now := time.Now().Unix() - comment, err := issues_model.CreateComment(&issues_model.CreateCommentOptions{ + comment, err := issues_model.CreateComment(db.DefaultContext, &issues_model.CreateCommentOptions{ Type: issues_model.CommentTypeComment, Doer: doer, Repo: repo, diff --git a/models/issues/content_history.go b/models/issues/content_history.go index f5cfa65b8f..cc06b184d7 100644 --- a/models/issues/content_history.go +++ b/models/issues/content_history.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package issues diff --git a/models/issues/content_history_test.go b/models/issues/content_history_test.go index 1218d871d0..7d52f1bcc6 100644 --- a/models/issues/content_history_test.go +++ b/models/issues/content_history_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package issues_test diff --git a/models/issues/dependency.go b/models/issues/dependency.go index 4754ed0f5f..bd39824369 100644 --- a/models/issues/dependency.go +++ b/models/issues/dependency.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package issues @@ -129,7 +128,7 @@ const ( // CreateIssueDependency creates a new dependency for an issue func CreateIssueDependency(user *user_model.User, issue, dep *Issue) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -170,7 +169,7 @@ func CreateIssueDependency(user *user_model.User, issue, dep *Issue) error { // RemoveIssueDependency removes a dependency from an issue func RemoveIssueDependency(user *user_model.User, issue, dep *Issue, depType DependencyType) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/issues/dependency_test.go b/models/issues/dependency_test.go index 3ea0b4ff5c..cdc8e3182d 100644 --- a/models/issues/dependency_test.go +++ b/models/issues/dependency_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package issues_test @@ -19,7 +18,7 @@ func TestCreateIssueDependency(t *testing.T) { // Prepare assert.NoError(t, unittest.PrepareTestDatabase()) - user1, err := user_model.GetUserByID(1) + user1, err := user_model.GetUserByID(db.DefaultContext, 1) assert.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) diff --git a/models/issues/issue.go b/models/issues/issue.go index 7ae0494a3a..dcd1e55938 100644 --- a/models/issues/issue.go +++ b/models/issues/issue.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2020 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. +// SPDX-License-Identifier: MIT package issues @@ -195,7 +194,7 @@ func (issue *Issue) IsOverdue() bool { // LoadRepo loads issue's repository func (issue *Issue) LoadRepo(ctx context.Context) (err error) { if issue.Repo == nil { - issue.Repo, err = repo_model.GetRepositoryByIDCtx(ctx, issue.RepoID) + issue.Repo, err = repo_model.GetRepositoryByID(ctx, issue.RepoID) if err != nil { return fmt.Errorf("getRepositoryByID [%d]: %w", issue.RepoID, err) } @@ -204,16 +203,12 @@ func (issue *Issue) LoadRepo(ctx context.Context) (err error) { } // IsTimetrackerEnabled returns true if the repo enables timetracking -func (issue *Issue) IsTimetrackerEnabled() bool { - return issue.isTimetrackerEnabled(db.DefaultContext) -} - -func (issue *Issue) isTimetrackerEnabled(ctx context.Context) bool { +func (issue *Issue) IsTimetrackerEnabled(ctx context.Context) bool { if err := issue.LoadRepo(ctx); err != nil { log.Error(fmt.Sprintf("loadRepo: %v", err)) return false } - return issue.Repo.IsTimetrackerEnabledCtx(ctx) + return issue.Repo.IsTimetrackerEnabled(ctx) } // GetPullRequest returns the issue pull request @@ -242,13 +237,9 @@ func (issue *Issue) LoadLabels(ctx context.Context) (err error) { } // LoadPoster loads poster -func (issue *Issue) LoadPoster() error { - return issue.loadPoster(db.DefaultContext) -} - -func (issue *Issue) loadPoster(ctx context.Context) (err error) { +func (issue *Issue) LoadPoster(ctx context.Context) (err error) { if issue.Poster == nil { - issue.Poster, err = user_model.GetUserByIDCtx(ctx, issue.PosterID) + issue.Poster, err = user_model.GetUserByID(ctx, issue.PosterID) if err != nil { issue.PosterID = -1 issue.Poster = user_model.NewGhostUser() @@ -262,7 +253,8 @@ func (issue *Issue) loadPoster(ctx context.Context) (err error) { return err } -func (issue *Issue) loadPullRequest(ctx context.Context) (err error) { +// LoadPullRequest loads pull request info +func (issue *Issue) LoadPullRequest(ctx context.Context) (err error) { if issue.IsPull && issue.PullRequest == nil { issue.PullRequest, err = GetPullRequestByIssueID(ctx, issue.ID) if err != nil { @@ -276,18 +268,13 @@ func (issue *Issue) loadPullRequest(ctx context.Context) (err error) { return nil } -// LoadPullRequest loads pull request info -func (issue *Issue) LoadPullRequest() error { - return issue.loadPullRequest(db.DefaultContext) -} - func (issue *Issue) loadComments(ctx context.Context) (err error) { return issue.loadCommentsByType(ctx, CommentTypeUnknown) } // LoadDiscussComments loads discuss comments -func (issue *Issue) LoadDiscussComments() error { - return issue.loadCommentsByType(db.DefaultContext, CommentTypeComment) +func (issue *Issue) LoadDiscussComments(ctx context.Context) error { + return issue.loadCommentsByType(ctx, CommentTypeComment) } func (issue *Issue) loadCommentsByType(ctx context.Context, tp CommentType) (err error) { @@ -358,7 +345,8 @@ func (issue *Issue) loadForeignReference(ctx context.Context) (err error) { return nil } -func (issue *Issue) loadMilestone(ctx context.Context) (err error) { +// LoadMilestone load milestone of this issue. +func (issue *Issue) LoadMilestone(ctx context.Context) (err error) { if (issue.Milestone == nil || issue.Milestone.ID != issue.MilestoneID) && issue.MilestoneID > 0 { issue.Milestone, err = GetMilestoneByRepoID(ctx, issue.RepoID, issue.MilestoneID) if err != nil && !IsErrMilestoneNotExist(err) { @@ -374,7 +362,7 @@ func (issue *Issue) LoadAttributes(ctx context.Context) (err error) { return } - if err = issue.loadPoster(ctx); err != nil { + if err = issue.LoadPoster(ctx); err != nil { return } @@ -382,7 +370,7 @@ func (issue *Issue) LoadAttributes(ctx context.Context) (err error) { return } - if err = issue.loadMilestone(ctx); err != nil { + if err = issue.LoadMilestone(ctx); err != nil { return } @@ -394,7 +382,7 @@ func (issue *Issue) LoadAttributes(ctx context.Context) (err error) { return } - if err = issue.loadPullRequest(ctx); err != nil && !IsErrPullRequestNotExist(err) { + if err = issue.LoadPullRequest(ctx); err != nil && !IsErrPullRequestNotExist(err) { // It is possible pull request is not yet created. return err } @@ -413,7 +401,7 @@ func (issue *Issue) LoadAttributes(ctx context.Context) (err error) { if err = CommentList(issue.Comments).loadAttributes(ctx); err != nil { return err } - if issue.isTimetrackerEnabled(ctx) { + if issue.IsTimetrackerEnabled(ctx) { if err = issue.LoadTotalTimes(ctx); err != nil { return err } @@ -426,11 +414,6 @@ func (issue *Issue) LoadAttributes(ctx context.Context) (err error) { return issue.loadReactions(ctx) } -// LoadMilestone load milestone of this issue. -func (issue *Issue) LoadMilestone() error { - return issue.loadMilestone(db.DefaultContext) -} - // GetIsRead load the `IsRead` field of the issue func (issue *Issue) GetIsRead(userID int64) error { issueUser := &IssueUser{IssueID: issue.ID, UID: userID} @@ -541,7 +524,7 @@ func clearIssueLabels(ctx context.Context, issue *Issue, doer *user_model.User) // ClearIssueLabels removes all issue labels as the given user. // Triggers appropriate WebHooks, if any. func ClearIssueLabels(issue *Issue, doer *user_model.User) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -549,7 +532,7 @@ func ClearIssueLabels(issue *Issue, doer *user_model.User) (err error) { if err := issue.LoadRepo(ctx); err != nil { return err - } else if err = issue.loadPullRequest(ctx); err != nil { + } else if err = issue.LoadPullRequest(ctx); err != nil { return err } @@ -589,7 +572,7 @@ func (ts labelSorter) Swap(i, j int) { // ReplaceIssueLabels removes all current labels and add new labels to the issue. // Triggers appropriate WebHooks, if any. func ReplaceIssueLabels(issue *Issue, labels []*Label, doer *user_model.User) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -687,7 +670,7 @@ func changeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.User, func doChangeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.User, isMergePull bool) (*Comment, error) { // Check for open dependencies - if issue.IsClosed && issue.Repo.IsDependenciesEnabledCtx(ctx) { + if issue.IsClosed && issue.Repo.IsDependenciesEnabled(ctx) { // only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies noDeps, err := IssueNoDependenciesLeft(ctx, issue) if err != nil { @@ -739,7 +722,7 @@ func doChangeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.Use cmtType = CommentTypeMergePull } - return CreateCommentCtx(ctx, &CreateCommentOptions{ + return CreateComment(ctx, &CreateCommentOptions{ Type: cmtType, Doer: doer, Repo: issue.Repo, @@ -752,7 +735,7 @@ func ChangeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.User, if err := issue.LoadRepo(ctx); err != nil { return nil, err } - if err := issue.loadPoster(ctx); err != nil { + if err := issue.LoadPoster(ctx); err != nil { return nil, err } @@ -761,7 +744,7 @@ func ChangeIssueStatus(ctx context.Context, issue *Issue, doer *user_model.User, // ChangeIssueTitle changes the title of this issue, as the given user. func ChangeIssueTitle(issue *Issue, doer *user_model.User, oldTitle string) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -783,7 +766,7 @@ func ChangeIssueTitle(issue *Issue, doer *user_model.User, oldTitle string) (err OldTitle: oldTitle, NewTitle: issue.Title, } - if _, err = CreateCommentCtx(ctx, opts); err != nil { + if _, err = CreateComment(ctx, opts); err != nil { return fmt.Errorf("createComment: %w", err) } if err = issue.AddCrossReferences(ctx, doer, true); err != nil { @@ -795,7 +778,7 @@ func ChangeIssueTitle(issue *Issue, doer *user_model.User, oldTitle string) (err // ChangeIssueRef changes the branch of this issue, as the given user. func ChangeIssueRef(issue *Issue, doer *user_model.User, oldRef string) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -819,7 +802,7 @@ func ChangeIssueRef(issue *Issue, doer *user_model.User, oldRef string) (err err OldRef: oldRefFriendly, NewRef: newRefFriendly, } - if _, err = CreateCommentCtx(ctx, opts); err != nil { + if _, err = CreateComment(ctx, opts); err != nil { return fmt.Errorf("createComment: %w", err) } @@ -839,13 +822,13 @@ func AddDeletePRBranchComment(ctx context.Context, doer *user_model.User, repo * Issue: issue, OldRef: branchName, } - _, err = CreateCommentCtx(ctx, opts) + _, err = CreateComment(ctx, opts) return err } // UpdateIssueAttachments update attachments by UUIDs for the issue func UpdateIssueAttachments(issueID int64, uuids []string) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -865,7 +848,7 @@ func UpdateIssueAttachments(issueID int64, uuids []string) (err error) { // ChangeIssueContent changes issue content, as the given user. func ChangeIssueContent(issue *Issue, doer *user_model.User, content string) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -1006,17 +989,12 @@ func NewIssueWithIndex(ctx context.Context, doer *user_model.User, opts NewIssue OldMilestoneID: 0, MilestoneID: opts.Issue.MilestoneID, } - if _, err = CreateCommentCtx(ctx, opts); err != nil { + if _, err = CreateComment(ctx, opts); err != nil { return err } } - if opts.IsPull { - _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID) - } else { - _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID) - } - if err != nil { + if err := repo_model.UpdateRepoIssueNumbers(ctx, opts.Issue.RepoID, opts.IsPull, false); err != nil { return err } @@ -1028,7 +1006,7 @@ func NewIssueWithIndex(ctx context.Context, doer *user_model.User, opts NewIssue return fmt.Errorf("find all labels [label_ids: %v]: %w", opts.LabelIDs, err) } - if err = opts.Issue.loadPoster(ctx); err != nil { + if err = opts.Issue.LoadPoster(ctx); err != nil { return err } @@ -1070,7 +1048,7 @@ func NewIssueWithIndex(ctx context.Context, doer *user_model.User, opts NewIssue // NewIssue creates new issue with labels for repository. func NewIssue(repo *repo_model.Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -1506,10 +1484,9 @@ func applySubscribedCondition(sess *xorm.Session, subscriberID int64) *xorm.Sess } // CountIssuesByRepo map from repoID to number of issues matching the options -func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) { - e := db.GetEngine(db.DefaultContext) - - sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") +func CountIssuesByRepo(ctx context.Context, opts *IssuesOptions) (map[int64]int64, error) { + sess := db.GetEngine(ctx). + Join("INNER", "repository", "`issue`.repo_id = `repository`.id") opts.setupSessionNoLimit(sess) @@ -1552,10 +1529,9 @@ func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *user_model.User) ([]i } // Issues returns a list of issues by given conditions. -func Issues(opts *IssuesOptions) ([]*Issue, error) { - e := db.GetEngine(db.DefaultContext) - - sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") +func Issues(ctx context.Context, opts *IssuesOptions) ([]*Issue, error) { + sess := db.GetEngine(ctx). + Join("INNER", "repository", "`issue`.repo_id = `repository`.id") opts.setupSessionWithLimit(sess) sortIssuesSession(sess, opts.SortType, opts.PriorityRepoID) @@ -1573,11 +1549,11 @@ func Issues(opts *IssuesOptions) ([]*Issue, error) { } // CountIssues number return of issues by given conditions. -func CountIssues(opts *IssuesOptions) (int64, error) { - e := db.GetEngine(db.DefaultContext) - - sess := e.Select("COUNT(issue.id) AS count").Table("issue") - sess.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") +func CountIssues(ctx context.Context, opts *IssuesOptions) (int64, error) { + sess := db.GetEngine(ctx). + Select("COUNT(issue.id) AS count"). + Table("issue"). + Join("INNER", "repository", "`issue`.repo_id = `repository`.id") opts.setupSessionNoLimit(sess) return sess.Count() @@ -1586,9 +1562,10 @@ func CountIssues(opts *IssuesOptions) (int64, error) { // GetParticipantsIDsByIssueID returns the IDs of all users who participated in comments of an issue, // but skips joining with `user` for performance reasons. // User permissions must be verified elsewhere if required. -func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) { +func GetParticipantsIDsByIssueID(ctx context.Context, issueID int64) ([]int64, error) { userIDs := make([]int64, 0, 5) - return userIDs, db.GetEngine(db.DefaultContext).Table("comment"). + return userIDs, db.GetEngine(ctx). + Table("comment"). Cols("poster_id"). Where("issue_id = ?", issueID). And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview). @@ -1987,7 +1964,7 @@ func SearchIssueIDsByKeyword(ctx context.Context, kw string, repoIDs []int64, li // If the issue status is changed a statusChangeComment is returned // similarly if the title is changed the titleChanged bool is set to true func UpdateIssueByAPI(issue *Issue, doer *user_model.User) (statusChangeComment *Comment, titleChanged bool, err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, false, err } @@ -2020,7 +1997,7 @@ func UpdateIssueByAPI(issue *Issue, doer *user_model.User) (statusChangeComment OldTitle: currentIssue.Title, NewTitle: issue.Title, } - _, err := CreateCommentCtx(ctx, opts) + _, err := CreateComment(ctx, opts) if err != nil { return nil, false, fmt.Errorf("createComment: %w", err) } @@ -2045,7 +2022,7 @@ func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *us if issue.DeadlineUnix == deadlineUnix { return nil } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -2427,8 +2404,9 @@ func (issue *Issue) GetExternalName() string { return issue.OriginalAuthor } func (issue *Issue) GetExternalID() int64 { return issue.OriginalAuthorID } // CountOrphanedIssues count issues without a repo -func CountOrphanedIssues() (int64, error) { - return db.GetEngine(db.DefaultContext).Table("issue"). +func CountOrphanedIssues(ctx context.Context) (int64, error) { + return db.GetEngine(ctx). + Table("issue"). Join("LEFT", "repository", "issue.repo_id=repository.id"). Where(builder.IsNull{"repository.id"}). Select("COUNT(`issue`.`id`)"). @@ -2436,35 +2414,31 @@ func CountOrphanedIssues() (int64, error) { } // DeleteOrphanedIssues delete issues without a repo -func DeleteOrphanedIssues() error { - ctx, committer, err := db.TxContext() +func DeleteOrphanedIssues(ctx context.Context) error { + var attachmentPaths []string + err := db.AutoTx(ctx, func(ctx context.Context) error { + var ids []int64 + + if err := db.GetEngine(ctx).Table("issue").Distinct("issue.repo_id"). + Join("LEFT", "repository", "issue.repo_id=repository.id"). + Where(builder.IsNull{"repository.id"}).GroupBy("issue.repo_id"). + Find(&ids); err != nil { + return err + } + + for i := range ids { + paths, err := DeleteIssuesByRepoID(ctx, ids[i]) + if err != nil { + return err + } + attachmentPaths = append(attachmentPaths, paths...) + } + + return nil + }) if err != nil { return err } - defer committer.Close() - - var ids []int64 - - if err := db.GetEngine(ctx).Table("issue").Distinct("issue.repo_id"). - Join("LEFT", "repository", "issue.repo_id=repository.id"). - Where(builder.IsNull{"repository.id"}).GroupBy("issue.repo_id"). - Find(&ids); err != nil { - return err - } - - var attachmentPaths []string - for i := range ids { - paths, err := DeleteIssuesByRepoID(ctx, ids[i]) - if err != nil { - return err - } - attachmentPaths = append(attachmentPaths, paths...) - } - - if err := committer.Commit(); err != nil { - return err - } - committer.Close() // Remove issue attachment files. for i := range attachmentPaths { diff --git a/models/issues/issue_index.go b/models/issues/issue_index.go index f4acc5aa1b..b480cc683f 100644 --- a/models/issues/issue_index.go +++ b/models/issues/issue_index.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues @@ -9,7 +8,7 @@ import "code.gitea.io/gitea/models/db" // RecalculateIssueIndexForRepo create issue_index for repo if not exist and // update it based on highest index of existing issues assigned to a repo func RecalculateIssueIndexForRepo(repoID int64) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/issues/issue_list.go b/models/issues/issue_list.go index bbe2292dd1..e22e48c0bb 100644 --- a/models/issues/issue_list.go +++ b/models/issues/issue_list.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues @@ -34,7 +33,8 @@ func (issues IssueList) getRepoIDs() []int64 { return repoIDs.Values() } -func (issues IssueList) loadRepositories(ctx context.Context) ([]*repo_model.Repository, error) { +// LoadRepositories loads issues' all repositories +func (issues IssueList) LoadRepositories(ctx context.Context) ([]*repo_model.Repository, error) { if len(issues) == 0 { return nil, nil } @@ -73,11 +73,6 @@ func (issues IssueList) loadRepositories(ctx context.Context) ([]*repo_model.Rep return repo_model.ValuesRepository(repoMaps), nil } -// LoadRepositories loads issues' all repositories -func (issues IssueList) LoadRepositories() ([]*repo_model.Repository, error) { - return issues.loadRepositories(db.DefaultContext) -} - func (issues IssueList) getPosterIDs() []int64 { posterIDs := make(container.Set[int64], len(issues)) for _, issue := range issues { @@ -317,7 +312,8 @@ func (issues IssueList) getPullIssueIDs() []int64 { return ids } -func (issues IssueList) loadPullRequests(ctx context.Context) error { +// LoadPullRequests loads pull requests +func (issues IssueList) LoadPullRequests(ctx context.Context) error { issuesIDs := issues.getPullIssueIDs() if len(issuesIDs) == 0 { return nil @@ -361,7 +357,8 @@ func (issues IssueList) loadPullRequests(ctx context.Context) error { return nil } -func (issues IssueList) loadAttachments(ctx context.Context) (err error) { +// LoadAttachments loads attachments +func (issues IssueList) LoadAttachments(ctx context.Context) (err error) { if len(issues) == 0 { return nil } @@ -464,7 +461,7 @@ func (issues IssueList) loadTotalTrackedTimes(ctx context.Context) (err error) { ids := make([]int64, 0, len(issues)) for _, issue := range issues { - if issue.Repo.IsTimetrackerEnabled() { + if issue.Repo.IsTimetrackerEnabled(ctx) { ids = append(ids, issue.ID) } } @@ -513,8 +510,8 @@ func (issues IssueList) loadTotalTrackedTimes(ctx context.Context) (err error) { // loadAttributes loads all attributes, expect for attachments and comments func (issues IssueList) loadAttributes(ctx context.Context) error { - if _, err := issues.loadRepositories(ctx); err != nil { - return fmt.Errorf("issue.loadAttributes: loadRepositories: %w", err) + if _, err := issues.LoadRepositories(ctx); err != nil { + return fmt.Errorf("issue.loadAttributes: LoadRepositories: %w", err) } if err := issues.loadPosters(ctx); err != nil { @@ -537,7 +534,7 @@ func (issues IssueList) loadAttributes(ctx context.Context) error { return fmt.Errorf("issue.loadAttributes: loadAssignees: %w", err) } - if err := issues.loadPullRequests(ctx); err != nil { + if err := issues.LoadPullRequests(ctx); err != nil { return fmt.Errorf("issue.loadAttributes: loadPullRequests: %w", err) } @@ -554,24 +551,14 @@ func (issues IssueList) LoadAttributes() error { return issues.loadAttributes(db.DefaultContext) } -// LoadAttachments loads attachments -func (issues IssueList) LoadAttachments() error { - return issues.loadAttachments(db.DefaultContext) -} - // LoadComments loads comments -func (issues IssueList) LoadComments() error { - return issues.loadComments(db.DefaultContext, builder.NewCond()) +func (issues IssueList) LoadComments(ctx context.Context) error { + return issues.loadComments(ctx, builder.NewCond()) } // LoadDiscussComments loads discuss comments -func (issues IssueList) LoadDiscussComments() error { - return issues.loadComments(db.DefaultContext, builder.Eq{"comment.type": CommentTypeComment}) -} - -// LoadPullRequests loads pull requests -func (issues IssueList) LoadPullRequests() error { - return issues.loadPullRequests(db.DefaultContext) +func (issues IssueList) LoadDiscussComments(ctx context.Context) error { + return issues.loadComments(ctx, builder.Eq{"comment.type": CommentTypeComment}) } // GetApprovalCounts returns a map of issue ID to slice of approval counts diff --git a/models/issues/issue_list_test.go b/models/issues/issue_list_test.go index f2cfca9bc0..954a20ffe4 100644 --- a/models/issues/issue_list_test.go +++ b/models/issues/issue_list_test.go @@ -1,12 +1,12 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues_test import ( "testing" + "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" @@ -23,7 +23,7 @@ func TestIssueList_LoadRepositories(t *testing.T) { unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 4}), } - repos, err := issueList.LoadRepositories() + repos, err := issueList.LoadRepositories(db.DefaultContext) assert.NoError(t, err) assert.Len(t, repos, 2) for _, issue := range issueList { diff --git a/models/issues/issue_lock.go b/models/issues/issue_lock.go index 7b52429ef7..19cd6d3167 100644 --- a/models/issues/issue_lock.go +++ b/models/issues/issue_lock.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issues @@ -40,7 +39,7 @@ func updateIssueLock(opts *IssueLockOptions, lock bool) error { commentType = CommentTypeUnlock } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -57,7 +56,7 @@ func updateIssueLock(opts *IssueLockOptions, lock bool) error { Type: commentType, Content: opts.Reason, } - if _, err := CreateCommentCtx(ctx, opt); err != nil { + if _, err := CreateComment(ctx, opt); err != nil { return err } diff --git a/models/issues/issue_project.go b/models/issues/issue_project.go index 8299087c5b..8e559f13c9 100644 --- a/models/issues/issue_project.go +++ b/models/issues/issue_project.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package issues @@ -61,11 +60,11 @@ func (issue *Issue) projectBoardID(ctx context.Context) int64 { } // LoadIssuesFromBoard load issues assigned to this board -func LoadIssuesFromBoard(b *project_model.Board) (IssueList, error) { +func LoadIssuesFromBoard(ctx context.Context, b *project_model.Board) (IssueList, error) { issueList := make([]*Issue, 0, 10) if b.ID != 0 { - issues, err := Issues(&IssuesOptions{ + issues, err := Issues(ctx, &IssuesOptions{ ProjectBoardID: b.ID, ProjectID: b.ProjectID, SortType: "project-column-sorting", @@ -77,7 +76,7 @@ func LoadIssuesFromBoard(b *project_model.Board) (IssueList, error) { } if b.Default { - issues, err := Issues(&IssuesOptions{ + issues, err := Issues(ctx, &IssuesOptions{ ProjectBoardID: -1, // Issues without ProjectBoardID ProjectID: b.ProjectID, SortType: "project-column-sorting", @@ -88,7 +87,7 @@ func LoadIssuesFromBoard(b *project_model.Board) (IssueList, error) { issueList = append(issueList, issues...) } - if err := IssueList(issueList).LoadComments(); err != nil { + if err := IssueList(issueList).LoadComments(ctx); err != nil { return nil, err } @@ -96,10 +95,10 @@ func LoadIssuesFromBoard(b *project_model.Board) (IssueList, error) { } // LoadIssuesFromBoardList load issues assigned to the boards -func LoadIssuesFromBoardList(bs project_model.BoardList) (map[int64]IssueList, error) { +func LoadIssuesFromBoardList(ctx context.Context, bs project_model.BoardList) (map[int64]IssueList, error) { issuesMap := make(map[int64]IssueList, len(bs)) for i := range bs { - il, err := LoadIssuesFromBoard(bs[i]) + il, err := LoadIssuesFromBoard(ctx, bs[i]) if err != nil { return nil, err } @@ -110,7 +109,7 @@ func LoadIssuesFromBoardList(bs project_model.BoardList) (map[int64]IssueList, e // ChangeProjectAssign changes the project associated with an issue func ChangeProjectAssign(issue *Issue, doer *user_model.User, newProjectID int64) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -146,7 +145,7 @@ func addUpdateIssueProject(ctx context.Context, issue *Issue, doer *user_model.U } if oldProjectID > 0 || newProjectID > 0 { - if _, err := CreateCommentCtx(ctx, &CreateCommentOptions{ + if _, err := CreateComment(ctx, &CreateCommentOptions{ Type: CommentTypeProject, Doer: doer, Repo: issue.Repo, @@ -166,7 +165,7 @@ func addUpdateIssueProject(ctx context.Context, issue *Issue, doer *user_model.U // MoveIssueAcrossProjectBoards move a card from one board to another func MoveIssueAcrossProjectBoards(issue *Issue, board *project_model.Board) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/issues/issue_test.go b/models/issues/issue_test.go index bef5d03e8a..6764a9e626 100644 --- a/models/issues/issue_test.go +++ b/models/issues/issue_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues_test @@ -189,7 +188,7 @@ func TestIssues(t *testing.T) { []int64{}, // issues with **both** label 1 and 2, none of these issues matches, TODO: add more tests }, } { - issues, err := issues_model.Issues(&test.Opts) + issues, err := issues_model.Issues(db.DefaultContext, &test.Opts) assert.NoError(t, err) if assert.Len(t, issues, len(test.ExpectedIssueIDs)) { for i, issue := range issues { @@ -556,7 +555,7 @@ func TestLoadTotalTrackedTime(t *testing.T) { func TestCountIssues(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - count, err := issues_model.CountIssues(&issues_model.IssuesOptions{}) + count, err := issues_model.CountIssues(db.DefaultContext, &issues_model.IssuesOptions{}) assert.NoError(t, err) assert.EqualValues(t, 17, count) } diff --git a/models/issues/issue_user.go b/models/issues/issue_user.go index c1a68c96e8..4a537752a2 100644 --- a/models/issues/issue_user.go +++ b/models/issues/issue_user.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues diff --git a/models/issues/issue_user_test.go b/models/issues/issue_user_test.go index 7dd84ed68c..0daace6c9b 100644 --- a/models/issues/issue_user_test.go +++ b/models/issues/issue_user_test.go @@ -1,6 +1,5 @@ // Copyright 2017 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package issues_test diff --git a/models/issues/issue_watch.go b/models/issues/issue_watch.go index cb9d7e7125..1efc0ea687 100644 --- a/models/issues/issue_watch.go +++ b/models/issues/issue_watch.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues diff --git a/models/issues/issue_watch_test.go b/models/issues/issue_watch_test.go index 7aaf9f7f5d..4f44487f56 100644 --- a/models/issues/issue_watch_test.go +++ b/models/issues/issue_watch_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues_test diff --git a/models/issues/issue_xref.go b/models/issues/issue_xref.go index e389f63d72..21ee24210f 100644 --- a/models/issues/issue_xref.go +++ b/models/issues/issue_xref.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issues @@ -122,7 +121,7 @@ func (issue *Issue) createCrossReferences(stdCtx context.Context, ctx *crossRefe RefAction: xref.Action, RefIsPull: ctx.OrigIssue.IsPull, } - _, err := CreateCommentCtx(stdCtx, opts) + _, err := CreateComment(stdCtx, opts) if err != nil { return err } @@ -149,7 +148,7 @@ func (issue *Issue) getCrossReferences(stdCtx context.Context, ctx *crossReferen refRepo = ctx.OrigIssue.Repo } else { // Issues in other repositories - refRepo, err = repo_model.GetRepositoryByOwnerAndNameCtx(stdCtx, ref.Owner, ref.Name) + refRepo, err = repo_model.GetRepositoryByOwnerAndName(stdCtx, ref.Owner, ref.Name) if err != nil { if repo_model.IsErrRepoNotExist(err) { continue @@ -235,7 +234,7 @@ func (c *Comment) AddCrossReferences(stdCtx context.Context, doer *user_model.Us if c.Type != CommentTypeCode && c.Type != CommentTypeComment { return nil } - if err := c.LoadIssueCtx(stdCtx); err != nil { + if err := c.LoadIssue(stdCtx); err != nil { return err } ctx := &crossReferencesContext{ diff --git a/models/issues/issue_xref_test.go b/models/issues/issue_xref_test.go index 0f72fc7ca6..6d96c398d0 100644 --- a/models/issues/issue_xref_test.go +++ b/models/issues/issue_xref_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issues_test @@ -131,7 +130,7 @@ func testCreateIssue(t *testing.T, repo, doer int64, title, content string, ispu r := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo}) d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: doer}) - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) assert.NoError(t, err) defer committer.Close() @@ -174,7 +173,7 @@ func testCreateComment(t *testing.T, repo, doer, issue int64, content string) *i i := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: issue}) c := &issues_model.Comment{Type: issues_model.CommentTypeComment, PosterID: doer, Poster: d, IssueID: issue, Issue: i, Content: content} - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) assert.NoError(t, err) defer committer.Close() err = db.Insert(ctx, c) diff --git a/models/issues/label.go b/models/issues/label.go index bbdc99e265..dbb7a139ef 100644 --- a/models/issues/label.go +++ b/models/issues/label.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package issues @@ -116,8 +115,8 @@ func (label *Label) CalOpenIssues() { } // CalOpenOrgIssues calculates the open issues of a label for a specific repo -func (label *Label) CalOpenOrgIssues(repoID, labelID int64) { - counts, _ := CountIssuesByRepo(&IssuesOptions{ +func (label *Label) CalOpenOrgIssues(ctx context.Context, repoID, labelID int64) { + counts, _ := CountIssuesByRepo(ctx, &IssuesOptions{ RepoID: repoID, LabelIDs: []int64{labelID}, IsClosed: util.OptionalBoolFalse, @@ -232,7 +231,7 @@ func NewLabel(ctx context.Context, label *Label) error { // NewLabels creates new labels func NewLabels(labels ...*Label) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -267,7 +266,7 @@ func DeleteLabel(id, labelID int64) error { return err } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -395,9 +394,9 @@ func BuildLabelNamesIssueIDsCondition(labelNames []string) *builder.Builder { // GetLabelsInRepoByIDs returns a list of labels by IDs in given repository, // it silently ignores label IDs that do not belong to the repository. -func GetLabelsInRepoByIDs(repoID int64, labelIDs []int64) ([]*Label, error) { +func GetLabelsInRepoByIDs(ctx context.Context, repoID int64, labelIDs []int64) ([]*Label, error) { labels := make([]*Label, 0, len(labelIDs)) - return labels, db.GetEngine(db.DefaultContext). + return labels, db.GetEngine(ctx). Where("repo_id = ?", repoID). In("id", labelIDs). Asc("name"). @@ -498,9 +497,9 @@ func GetLabelIDsInOrgByNames(orgID int64, labelNames []string) ([]int64, error) // GetLabelsInOrgByIDs returns a list of labels by IDs in given organization, // it silently ignores label IDs that do not belong to the organization. -func GetLabelsInOrgByIDs(orgID int64, labelIDs []int64) ([]*Label, error) { +func GetLabelsInOrgByIDs(ctx context.Context, orgID int64, labelIDs []int64) ([]*Label, error) { labels := make([]*Label, 0, len(labelIDs)) - return labels, db.GetEngine(db.DefaultContext). + return labels, db.GetEngine(ctx). Where("org_id = ?", orgID). In("id", labelIDs). Asc("name"). @@ -614,7 +613,7 @@ func newIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *user_m Label: label, Content: "1", } - if _, err = CreateCommentCtx(ctx, opts); err != nil { + if _, err = CreateComment(ctx, opts); err != nil { return err } @@ -627,7 +626,7 @@ func NewIssueLabel(issue *Issue, label *Label, doer *user_model.User) (err error return nil } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -676,7 +675,7 @@ func newIssueLabels(ctx context.Context, issue *Issue, labels []*Label, doer *us // NewIssueLabels creates a list of issue-label relations. func NewIssueLabels(issue *Issue, labels []*Label, doer *user_model.User) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -715,7 +714,7 @@ func deleteIssueLabel(ctx context.Context, issue *Issue, label *Label, doer *use Issue: issue, Label: label, } - if _, err = CreateCommentCtx(ctx, opts); err != nil { + if _, err = CreateComment(ctx, opts); err != nil { return err } @@ -746,13 +745,13 @@ func DeleteLabelsByRepoID(ctx context.Context, repoID int64) error { } // CountOrphanedLabels return count of labels witch are broken and not accessible via ui anymore -func CountOrphanedLabels() (int64, error) { - noref, err := db.GetEngine(db.DefaultContext).Table("label").Where("repo_id=? AND org_id=?", 0, 0).Count() +func CountOrphanedLabels(ctx context.Context) (int64, error) { + noref, err := db.GetEngine(ctx).Table("label").Where("repo_id=? AND org_id=?", 0, 0).Count() if err != nil { return 0, err } - norepo, err := db.GetEngine(db.DefaultContext).Table("label"). + norepo, err := db.GetEngine(ctx).Table("label"). Where(builder.And( builder.Gt{"repo_id": 0}, builder.NotIn("repo_id", builder.Select("id").From("repository")), @@ -762,7 +761,7 @@ func CountOrphanedLabels() (int64, error) { return 0, err } - noorg, err := db.GetEngine(db.DefaultContext).Table("label"). + noorg, err := db.GetEngine(ctx).Table("label"). Where(builder.And( builder.Gt{"org_id": 0}, builder.NotIn("org_id", builder.Select("id").From("user")), @@ -776,14 +775,14 @@ func CountOrphanedLabels() (int64, error) { } // DeleteOrphanedLabels delete labels witch are broken and not accessible via ui anymore -func DeleteOrphanedLabels() error { +func DeleteOrphanedLabels(ctx context.Context) error { // delete labels with no reference - if _, err := db.GetEngine(db.DefaultContext).Table("label").Where("repo_id=? AND org_id=?", 0, 0).Delete(new(Label)); err != nil { + if _, err := db.GetEngine(ctx).Table("label").Where("repo_id=? AND org_id=?", 0, 0).Delete(new(Label)); err != nil { return err } // delete labels with none existing repos - if _, err := db.GetEngine(db.DefaultContext). + if _, err := db.GetEngine(ctx). Where(builder.And( builder.Gt{"repo_id": 0}, builder.NotIn("repo_id", builder.Select("id").From("repository")), @@ -793,7 +792,7 @@ func DeleteOrphanedLabels() error { } // delete labels with none existing orgs - if _, err := db.GetEngine(db.DefaultContext). + if _, err := db.GetEngine(ctx). Where(builder.And( builder.Gt{"org_id": 0}, builder.NotIn("org_id", builder.Select("id").From("user")), @@ -806,23 +805,23 @@ func DeleteOrphanedLabels() error { } // CountOrphanedIssueLabels return count of IssueLabels witch have no label behind anymore -func CountOrphanedIssueLabels() (int64, error) { - return db.GetEngine(db.DefaultContext).Table("issue_label"). +func CountOrphanedIssueLabels(ctx context.Context) (int64, error) { + return db.GetEngine(ctx).Table("issue_label"). NotIn("label_id", builder.Select("id").From("label")). Count() } // DeleteOrphanedIssueLabels delete IssueLabels witch have no label behind anymore -func DeleteOrphanedIssueLabels() error { - _, err := db.GetEngine(db.DefaultContext). +func DeleteOrphanedIssueLabels(ctx context.Context) error { + _, err := db.GetEngine(ctx). NotIn("label_id", builder.Select("id").From("label")). Delete(IssueLabel{}) return err } // CountIssueLabelWithOutsideLabels count label comments with outside label -func CountIssueLabelWithOutsideLabels() (int64, error) { - return db.GetEngine(db.DefaultContext).Where(builder.Expr("(label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id)")). +func CountIssueLabelWithOutsideLabels(ctx context.Context) (int64, error) { + return db.GetEngine(ctx).Where(builder.Expr("(label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id)")). Table("issue_label"). Join("inner", "label", "issue_label.label_id = label.id "). Join("inner", "issue", "issue.id = issue_label.issue_id "). @@ -831,8 +830,8 @@ func CountIssueLabelWithOutsideLabels() (int64, error) { } // FixIssueLabelWithOutsideLabels fix label comments with outside label -func FixIssueLabelWithOutsideLabels() (int64, error) { - res, err := db.GetEngine(db.DefaultContext).Exec(`DELETE FROM issue_label WHERE issue_label.id IN ( +func FixIssueLabelWithOutsideLabels(ctx context.Context) (int64, error) { + res, err := db.GetEngine(ctx).Exec(`DELETE FROM issue_label WHERE issue_label.id IN ( SELECT il_too.id FROM ( SELECT il_too_too.id FROM issue_label AS il_too_too diff --git a/models/issues/label_test.go b/models/issues/label_test.go index 9ad6fd427b..239e328d47 100644 --- a/models/issues/label_test.go +++ b/models/issues/label_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues_test @@ -121,7 +120,7 @@ func TestGetLabelInRepoByID(t *testing.T) { func TestGetLabelsInRepoByIDs(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - labels, err := issues_model.GetLabelsInRepoByIDs(1, []int64{1, 2, unittest.NonexistentID}) + labels, err := issues_model.GetLabelsInRepoByIDs(db.DefaultContext, 1, []int64{1, 2, unittest.NonexistentID}) assert.NoError(t, err) if assert.Len(t, labels, 2) { assert.EqualValues(t, 1, labels[0].ID) @@ -212,7 +211,7 @@ func TestGetLabelInOrgByID(t *testing.T) { func TestGetLabelsInOrgByIDs(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - labels, err := issues_model.GetLabelsInOrgByIDs(3, []int64{3, 4, unittest.NonexistentID}) + labels, err := issues_model.GetLabelsInOrgByIDs(db.DefaultContext, 3, []int64{3, 4, unittest.NonexistentID}) assert.NoError(t, err) if assert.Len(t, labels, 2) { assert.EqualValues(t, 3, labels[0].ID) @@ -370,7 +369,7 @@ func TestDeleteIssueLabel(t *testing.T) { } } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) defer committer.Close() assert.NoError(t, err) assert.NoError(t, issues_model.DeleteIssueLabel(ctx, issue, label, doer)) diff --git a/models/issues/main_test.go b/models/issues/main_test.go index 89f9e1c999..93e05f33f6 100644 --- a/models/issues/main_test.go +++ b/models/issues/main_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package issues_test diff --git a/models/issues/milestone.go b/models/issues/milestone.go index 3ccade7411..8255db38f9 100644 --- a/models/issues/milestone.go +++ b/models/issues/milestone.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues @@ -111,7 +110,7 @@ func (m *Milestone) State() api.StateType { // NewMilestone creates new milestone of repository. func NewMilestone(m *Milestone) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -161,7 +160,7 @@ func GetMilestoneByRepoIDANDName(repoID int64, name string) (*Milestone, error) // UpdateMilestone updates information of given milestone. func UpdateMilestone(m *Milestone, oldIsClosed bool) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -219,7 +218,7 @@ func UpdateMilestoneCounters(ctx context.Context, id int64) error { // ChangeMilestoneStatusByRepoIDAndID changes a milestone open/closed status if the milestone ID is in the repo. func ChangeMilestoneStatusByRepoIDAndID(repoID, milestoneID int64, isClosed bool) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -246,7 +245,7 @@ func ChangeMilestoneStatusByRepoIDAndID(repoID, milestoneID int64, isClosed bool // ChangeMilestoneStatus changes the milestone open/closed status. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -285,12 +284,12 @@ func DeleteMilestoneByRepoID(repoID, id int64) error { return err } - repo, err := repo_model.GetRepositoryByID(m.RepoID) + repo, err := repo_model.GetRepositoryByID(db.DefaultContext, m.RepoID) if err != nil { return err } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/issues/milestone_test.go b/models/issues/milestone_test.go index f04a2b2b3b..5db5655906 100644 --- a/models/issues/milestone_test.go +++ b/models/issues/milestone_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues_test diff --git a/models/issues/pull.go b/models/issues/pull.go index f03cabc3c8..7af9400d17 100644 --- a/models/issues/pull.go +++ b/models/issues/pull.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issues @@ -205,8 +204,8 @@ func DeletePullsByBaseRepoID(ctx context.Context, repoID int64) error { } // MustHeadUserName returns the HeadRepo's username if failed return blank -func (pr *PullRequest) MustHeadUserName() string { - if err := pr.LoadHeadRepo(); err != nil { +func (pr *PullRequest) MustHeadUserName(ctx context.Context) string { + if err := pr.LoadHeadRepo(ctx); err != nil { if !repo_model.IsErrRepoNotExist(err) { log.Error("LoadHeadRepo: %v", err) } else { @@ -220,10 +219,11 @@ func (pr *PullRequest) MustHeadUserName() string { return pr.HeadRepo.OwnerName } +// LoadAttributes loads pull request attributes from database // Note: don't try to get Issue because will end up recursive querying. -func (pr *PullRequest) loadAttributes(ctx context.Context) (err error) { +func (pr *PullRequest) LoadAttributes(ctx context.Context) (err error) { if pr.HasMerged && pr.Merger == nil { - pr.Merger, err = user_model.GetUserByIDCtx(ctx, pr.MergerID) + pr.Merger, err = user_model.GetUserByID(ctx, pr.MergerID) if user_model.IsErrUserNotExist(err) { pr.MergerID = -1 pr.Merger = user_model.NewGhostUser() @@ -235,13 +235,8 @@ func (pr *PullRequest) loadAttributes(ctx context.Context) (err error) { return nil } -// LoadAttributes loads pull request attributes from database -func (pr *PullRequest) LoadAttributes() error { - return pr.loadAttributes(db.DefaultContext) -} - -// LoadHeadRepoCtx loads the head repository -func (pr *PullRequest) LoadHeadRepoCtx(ctx context.Context) (err error) { +// LoadHeadRepo loads the head repository +func (pr *PullRequest) LoadHeadRepo(ctx context.Context) (err error) { if !pr.isHeadRepoLoaded && pr.HeadRepo == nil && pr.HeadRepoID > 0 { if pr.HeadRepoID == pr.BaseRepoID { if pr.BaseRepo != nil { @@ -253,27 +248,17 @@ func (pr *PullRequest) LoadHeadRepoCtx(ctx context.Context) (err error) { } } - pr.HeadRepo, err = repo_model.GetRepositoryByIDCtx(ctx, pr.HeadRepoID) + pr.HeadRepo, err = repo_model.GetRepositoryByID(ctx, pr.HeadRepoID) if err != nil && !repo_model.IsErrRepoNotExist(err) { // Head repo maybe deleted, but it should still work - return fmt.Errorf("getRepositoryByID(head): %w", err) + return fmt.Errorf("GetRepositoryByID(head): %w", err) } pr.isHeadRepoLoaded = true } return nil } -// LoadHeadRepo loads the head repository -func (pr *PullRequest) LoadHeadRepo() error { - return pr.LoadHeadRepoCtx(db.DefaultContext) -} - // LoadBaseRepo loads the target repository -func (pr *PullRequest) LoadBaseRepo() error { - return pr.LoadBaseRepoCtx(db.DefaultContext) -} - -// LoadBaseRepoCtx loads the target repository -func (pr *PullRequest) LoadBaseRepoCtx(ctx context.Context) (err error) { +func (pr *PullRequest) LoadBaseRepo(ctx context.Context) (err error) { if pr.BaseRepo != nil { return nil } @@ -288,7 +273,7 @@ func (pr *PullRequest) LoadBaseRepoCtx(ctx context.Context) (err error) { return nil } - pr.BaseRepo, err = repo_model.GetRepositoryByIDCtx(ctx, pr.BaseRepoID) + pr.BaseRepo, err = repo_model.GetRepositoryByID(ctx, pr.BaseRepoID) if err != nil { return fmt.Errorf("repo_model.GetRepositoryByID(base): %w", err) } @@ -296,12 +281,7 @@ func (pr *PullRequest) LoadBaseRepoCtx(ctx context.Context) (err error) { } // LoadIssue loads issue information from database -func (pr *PullRequest) LoadIssue() (err error) { - return pr.LoadIssueCtx(db.DefaultContext) -} - -// LoadIssueCtx loads issue information from database -func (pr *PullRequest) LoadIssueCtx(ctx context.Context) (err error) { +func (pr *PullRequest) LoadIssue(ctx context.Context) (err error) { if pr.Issue != nil { return nil } @@ -314,18 +294,13 @@ func (pr *PullRequest) LoadIssueCtx(ctx context.Context) (err error) { } // LoadProtectedBranch loads the protected branch of the base branch -func (pr *PullRequest) LoadProtectedBranch() (err error) { - return pr.LoadProtectedBranchCtx(db.DefaultContext) -} - -// LoadProtectedBranchCtx loads the protected branch of the base branch -func (pr *PullRequest) LoadProtectedBranchCtx(ctx context.Context) (err error) { +func (pr *PullRequest) LoadProtectedBranch(ctx context.Context) (err error) { if pr.ProtectedBranch == nil { if pr.BaseRepo == nil { if pr.BaseRepoID == 0 { return nil } - pr.BaseRepo, err = repo_model.GetRepositoryByIDCtx(ctx, pr.BaseRepoID) + pr.BaseRepo, err = repo_model.GetRepositoryByID(ctx, pr.BaseRepoID) if err != nil { return } @@ -368,7 +343,7 @@ func (pr *PullRequest) getReviewedByLines(writer io.Writer) error { return nil } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -392,7 +367,7 @@ func (pr *PullRequest) getReviewedByLines(writer io.Writer) error { break } - if err := review.loadReviewer(ctx); err != nil && !user_model.IsErrUserNotExist(err) { + if err := review.LoadReviewer(ctx); err != nil && !user_model.IsErrUserNotExist(err) { log.Error("Unable to LoadReviewer[%d] for PR ID %d : %v", review.ReviewerID, pr.ID, err) return err } else if review.Reviewer == nil { @@ -458,7 +433,7 @@ func (pr *PullRequest) SetMerged(ctx context.Context) (bool, error) { } pr.Issue = nil - if err := pr.LoadIssueCtx(ctx); err != nil { + if err := pr.LoadIssue(ctx); err != nil { return false, err } @@ -498,7 +473,7 @@ func (pr *PullRequest) SetMerged(ctx context.Context) (bool, error) { // NewPullRequest creates new pull request with labels for repository. func NewPullRequest(outerCtx context.Context, repo *repo_model.Repository, issue *Issue, labelIDs []int64, uuids []string, pr *PullRequest) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(outerCtx) if err != nil { return err } @@ -541,9 +516,9 @@ func NewPullRequest(outerCtx context.Context, repo *repo_model.Repository, issue // GetUnmergedPullRequest returns a pull request that is open and has not been merged // by given head/base and repo/branch. -func GetUnmergedPullRequest(headRepoID, baseRepoID int64, headBranch, baseBranch string, flow PullRequestFlow) (*PullRequest, error) { +func GetUnmergedPullRequest(ctx context.Context, headRepoID, baseRepoID int64, headBranch, baseBranch string, flow PullRequestFlow) (*PullRequest, error) { pr := new(PullRequest) - has, err := db.GetEngine(db.DefaultContext). + has, err := db.GetEngine(ctx). Where("head_repo_id=? AND head_branch=? AND base_repo_id=? AND base_branch=? AND has_merged=? AND flow = ? AND issue.is_closed=?", headRepoID, headBranch, baseRepoID, baseBranch, false, flow, false). Join("INNER", "issue", "issue.id=pull_request.issue_id"). @@ -588,10 +563,10 @@ func GetPullRequestByIndex(ctx context.Context, repoID, index int64) (*PullReque return nil, ErrPullRequestNotExist{0, 0, 0, repoID, "", ""} } - if err = pr.loadAttributes(ctx); err != nil { + if err = pr.LoadAttributes(ctx); err != nil { return nil, err } - if err = pr.LoadIssueCtx(ctx); err != nil { + if err = pr.LoadIssue(ctx); err != nil { return nil, err } @@ -607,7 +582,7 @@ func GetPullRequestByID(ctx context.Context, id int64) (*PullRequest, error) { } else if !has { return nil, ErrPullRequestNotExist{id, 0, 0, 0, "", ""} } - return pr, pr.loadAttributes(ctx) + return pr, pr.LoadAttributes(ctx) } // GetPullRequestByIssueIDWithNoAttributes returns pull request with no attributes loaded by given issue ID. @@ -634,7 +609,7 @@ func GetPullRequestByIssueID(ctx context.Context, issueID int64) (*PullRequest, } else if !has { return nil, ErrPullRequestNotExist{0, issueID, 0, 0, "", ""} } - return pr, pr.loadAttributes(ctx) + return pr, pr.LoadAttributes(ctx) } // GetAllUnmergedAgitPullRequestByPoster get all unmerged agit flow pull request @@ -664,14 +639,15 @@ func (pr *PullRequest) UpdateCols(cols ...string) error { } // UpdateColsIfNotMerged updates specific fields of a pull request if it has not been merged -func (pr *PullRequest) UpdateColsIfNotMerged(cols ...string) error { - _, err := db.GetEngine(db.DefaultContext).Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr) +func (pr *PullRequest) UpdateColsIfNotMerged(ctx context.Context, cols ...string) error { + _, err := db.GetEngine(ctx).Where("id = ? AND has_merged = ?", pr.ID, false).Cols(cols...).Update(pr) return err } // IsWorkInProgress determine if the Pull Request is a Work In Progress by its title +// Issue must be set before this method can be called. func (pr *PullRequest) IsWorkInProgress() bool { - if err := pr.LoadIssue(); err != nil { + if err := pr.LoadIssue(db.DefaultContext); err != nil { log.Error("LoadIssue: %v", err) return false } @@ -695,8 +671,8 @@ func (pr *PullRequest) IsFilesConflicted() bool { // GetWorkInProgressPrefix returns the prefix used to mark the pull request as a work in progress. // It returns an empty string when none were found -func (pr *PullRequest) GetWorkInProgressPrefix() string { - if err := pr.LoadIssue(); err != nil { +func (pr *PullRequest) GetWorkInProgressPrefix(ctx context.Context) string { + if err := pr.LoadIssue(ctx); err != nil { log.Error("LoadIssue: %v", err) return "" } @@ -739,7 +715,7 @@ func GetPullRequestsByHeadBranch(ctx context.Context, headBranch string, headRep // GetBaseBranchHTMLURL returns the HTML URL of the base branch func (pr *PullRequest) GetBaseBranchHTMLURL() string { - if err := pr.LoadBaseRepo(); err != nil { + if err := pr.LoadBaseRepo(db.DefaultContext); err != nil { log.Error("LoadBaseRepo: %v", err) return "" } @@ -755,7 +731,7 @@ func (pr *PullRequest) GetHeadBranchHTMLURL() string { return "" } - if err := pr.LoadHeadRepo(); err != nil { + if err := pr.LoadHeadRepo(db.DefaultContext); err != nil { log.Error("LoadHeadRepo: %v", err) return "" } diff --git a/models/issues/pull_list.go b/models/issues/pull_list.go index c69f18492b..432e848e97 100644 --- a/models/issues/pull_list.go +++ b/models/issues/pull_list.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issues @@ -79,7 +78,7 @@ func CanMaintainerWriteToBranch(p access_model.Permission, branch string, user * for _, pr := range prs { if pr.AllowMaintainerEdit { - err = pr.LoadBaseRepo() + err = pr.LoadBaseRepo(db.DefaultContext) if err != nil { continue } diff --git a/models/issues/pull_test.go b/models/issues/pull_test.go index fb46e3071e..8ce8eecc4a 100644 --- a/models/issues/pull_test.go +++ b/models/issues/pull_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues_test @@ -17,7 +16,7 @@ import ( func TestPullRequest_LoadAttributes(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) - assert.NoError(t, pr.LoadAttributes()) + assert.NoError(t, pr.LoadAttributes(db.DefaultContext)) assert.NotNil(t, pr.Merger) assert.Equal(t, pr.MergerID, pr.Merger.ID) } @@ -25,10 +24,10 @@ func TestPullRequest_LoadAttributes(t *testing.T) { func TestPullRequest_LoadIssue(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) - assert.NoError(t, pr.LoadIssue()) + assert.NoError(t, pr.LoadIssue(db.DefaultContext)) assert.NotNil(t, pr.Issue) assert.Equal(t, int64(2), pr.Issue.ID) - assert.NoError(t, pr.LoadIssue()) + assert.NoError(t, pr.LoadIssue(db.DefaultContext)) assert.NotNil(t, pr.Issue) assert.Equal(t, int64(2), pr.Issue.ID) } @@ -36,10 +35,10 @@ func TestPullRequest_LoadIssue(t *testing.T) { func TestPullRequest_LoadBaseRepo(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) - assert.NoError(t, pr.LoadBaseRepo()) + assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) assert.NotNil(t, pr.BaseRepo) assert.Equal(t, pr.BaseRepoID, pr.BaseRepo.ID) - assert.NoError(t, pr.LoadBaseRepo()) + assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) assert.NotNil(t, pr.BaseRepo) assert.Equal(t, pr.BaseRepoID, pr.BaseRepo.ID) } @@ -47,7 +46,7 @@ func TestPullRequest_LoadBaseRepo(t *testing.T) { func TestPullRequest_LoadHeadRepo(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) - assert.NoError(t, pr.LoadHeadRepo()) + assert.NoError(t, pr.LoadHeadRepo(db.DefaultContext)) assert.NotNil(t, pr.HeadRepo) assert.Equal(t, pr.HeadRepoID, pr.HeadRepo.ID) } @@ -96,11 +95,11 @@ func TestPullRequestsOldest(t *testing.T) { func TestGetUnmergedPullRequest(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - pr, err := issues_model.GetUnmergedPullRequest(1, 1, "branch2", "master", issues_model.PullRequestFlowGithub) + pr, err := issues_model.GetUnmergedPullRequest(db.DefaultContext, 1, 1, "branch2", "master", issues_model.PullRequestFlowGithub) assert.NoError(t, err) assert.Equal(t, int64(2), pr.ID) - _, err = issues_model.GetUnmergedPullRequest(1, 9223372036854775807, "branch1", "master", issues_model.PullRequestFlowGithub) + _, err = issues_model.GetUnmergedPullRequest(db.DefaultContext, 1, 9223372036854775807, "branch1", "master", issues_model.PullRequestFlowGithub) assert.Error(t, err) assert.True(t, issues_model.IsErrPullRequestNotExist(err)) } @@ -228,7 +227,7 @@ func TestPullRequest_IsWorkInProgress(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) - pr.LoadIssue() + pr.LoadIssue(db.DefaultContext) assert.False(t, pr.IsWorkInProgress()) @@ -243,16 +242,16 @@ func TestPullRequest_GetWorkInProgressPrefixWorkInProgress(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) - pr.LoadIssue() + pr.LoadIssue(db.DefaultContext) - assert.Empty(t, pr.GetWorkInProgressPrefix()) + assert.Empty(t, pr.GetWorkInProgressPrefix(db.DefaultContext)) original := pr.Issue.Title pr.Issue.Title = "WIP: " + original - assert.Equal(t, "WIP:", pr.GetWorkInProgressPrefix()) + assert.Equal(t, "WIP:", pr.GetWorkInProgressPrefix(db.DefaultContext)) pr.Issue.Title = "[wip] " + original - assert.Equal(t, "[wip]", pr.GetWorkInProgressPrefix()) + assert.Equal(t, "[wip]", pr.GetWorkInProgressPrefix(db.DefaultContext)) } func TestDeleteOrphanedObjects(t *testing.T) { @@ -264,11 +263,11 @@ func TestDeleteOrphanedObjects(t *testing.T) { _, err = db.GetEngine(db.DefaultContext).Insert(&issues_model.PullRequest{IssueID: 1000}, &issues_model.PullRequest{IssueID: 1001}, &issues_model.PullRequest{IssueID: 1003}) assert.NoError(t, err) - orphaned, err := db.CountOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id") + orphaned, err := db.CountOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id") assert.NoError(t, err) assert.EqualValues(t, 3, orphaned) - err = db.DeleteOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id") + err = db.DeleteOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id") assert.NoError(t, err) countAfter, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{}) diff --git a/models/issues/reaction.go b/models/issues/reaction.go index c7503c23a2..293dfa3fd1 100644 --- a/models/issues/reaction.go +++ b/models/issues/reaction.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues @@ -76,7 +75,7 @@ func (r *Reaction) LoadUser() (*user_model.User, error) { if r.User != nil { return r.User, nil } - user, err := user_model.GetUserByIDCtx(db.DefaultContext, r.UserID) + user, err := user_model.GetUserByID(db.DefaultContext, r.UserID) if err != nil { return nil, err } @@ -224,7 +223,7 @@ func CreateReaction(opts *ReactionOptions) (*Reaction, error) { return nil, ErrForbiddenIssueReaction{opts.Type} } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } diff --git a/models/issues/reaction_test.go b/models/issues/reaction_test.go index 835a667619..ddd0e2d04c 100644 --- a/models/issues/reaction_test.go +++ b/models/issues/reaction_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues_test diff --git a/models/issues/review.go b/models/issues/review.go index 3d2fceda2d..7dee28fe97 100644 --- a/models/issues/review.go +++ b/models/issues/review.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package issues @@ -154,15 +153,17 @@ func (r *Review) loadIssue(ctx context.Context) (err error) { return err } -func (r *Review) loadReviewer(ctx context.Context) (err error) { +// LoadReviewer loads reviewer +func (r *Review) LoadReviewer(ctx context.Context) (err error) { if r.ReviewerID == 0 || r.Reviewer != nil { return } - r.Reviewer, err = user_model.GetUserByIDCtx(ctx, r.ReviewerID) + r.Reviewer, err = user_model.GetUserByID(ctx, r.ReviewerID) return err } -func (r *Review) loadReviewerTeam(ctx context.Context) (err error) { +// LoadReviewerTeam loads reviewer team +func (r *Review) LoadReviewerTeam(ctx context.Context) (err error) { if r.ReviewerTeamID == 0 || r.ReviewerTeam != nil { return } @@ -171,16 +172,6 @@ func (r *Review) loadReviewerTeam(ctx context.Context) (err error) { return err } -// LoadReviewer loads reviewer -func (r *Review) LoadReviewer() error { - return r.loadReviewer(db.DefaultContext) -} - -// LoadReviewerTeam loads reviewer team -func (r *Review) LoadReviewerTeam() error { - return r.loadReviewerTeam(db.DefaultContext) -} - // LoadAttributes loads all attributes except CodeComments func (r *Review) LoadAttributes(ctx context.Context) (err error) { if err = r.loadIssue(ctx); err != nil { @@ -189,10 +180,10 @@ func (r *Review) LoadAttributes(ctx context.Context) (err error) { if err = r.LoadCodeComments(ctx); err != nil { return } - if err = r.loadReviewer(ctx); err != nil { + if err = r.LoadReviewer(ctx); err != nil { return } - if err = r.loadReviewerTeam(ctx); err != nil { + if err = r.LoadReviewerTeam(ctx); err != nil { return } return err @@ -272,7 +263,7 @@ func IsOfficialReviewer(ctx context.Context, issue *Issue, reviewers ...*user_mo if err != nil { return false, err } - if err = pr.LoadProtectedBranchCtx(ctx); err != nil { + if err = pr.LoadProtectedBranch(ctx); err != nil { return false, err } if pr.ProtectedBranch == nil { @@ -280,7 +271,7 @@ func IsOfficialReviewer(ctx context.Context, issue *Issue, reviewers ...*user_mo } for _, reviewer := range reviewers { - official, err := git_model.IsUserOfficialReviewerCtx(ctx, pr.ProtectedBranch, reviewer) + official, err := git_model.IsUserOfficialReviewer(ctx, pr.ProtectedBranch, reviewer) if official || err != nil { return official, err } @@ -295,7 +286,7 @@ func IsOfficialReviewerTeam(ctx context.Context, issue *Issue, team *organizatio if err != nil { return false, err } - if err = pr.LoadProtectedBranchCtx(ctx); err != nil { + if err = pr.LoadProtectedBranch(ctx); err != nil { return false, err } if pr.ProtectedBranch == nil { @@ -303,7 +294,7 @@ func IsOfficialReviewerTeam(ctx context.Context, issue *Issue, team *organizatio } if !pr.ProtectedBranch.EnableApprovalsWhitelist { - return team.UnitAccessModeCtx(ctx, unit.TypeCode) >= perm.AccessModeWrite, nil + return team.UnitAccessMode(ctx, unit.TypeCode) >= perm.AccessModeWrite, nil } return base.Int64sContains(pr.ProtectedBranch.ApprovalsWhitelistTeamIDs, team.ID), nil @@ -374,7 +365,7 @@ func IsContentEmptyErr(err error) bool { // SubmitReview creates a review out of the existing pending review or creates a new one if no pending review exist func SubmitReview(doer *user_model.User, issue *Issue, reviewType ReviewType, content, commitID string, stale bool, attachmentUUIDs []string) (*Review, *Comment, error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, nil, err } @@ -445,7 +436,7 @@ func SubmitReview(doer *user_model.User, issue *Issue, reviewType ReviewType, co } } - comm, err := CreateCommentCtx(ctx, &CreateCommentOptions{ + comm, err := CreateComment(ctx, &CreateCommentOptions{ Type: CommentTypeReview, Doer: doer, Content: review.Content, @@ -622,7 +613,7 @@ func DismissReview(review *Review, isDismiss bool) (err error) { // InsertReviews inserts review and review comments func InsertReviews(reviews []*Review) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -664,7 +655,7 @@ func InsertReviews(reviews []*Review) error { // AddReviewRequest add a review request from one reviewer func AddReviewRequest(issue *Issue, reviewer, doer *user_model.User) (*Comment, error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } @@ -701,7 +692,7 @@ func AddReviewRequest(issue *Issue, reviewer, doer *user_model.User) (*Comment, return nil, err } - comment, err := CreateCommentCtx(ctx, &CreateCommentOptions{ + comment, err := CreateComment(ctx, &CreateCommentOptions{ Type: CommentTypeReviewRequest, Doer: doer, Repo: issue.Repo, @@ -719,7 +710,7 @@ func AddReviewRequest(issue *Issue, reviewer, doer *user_model.User) (*Comment, // RemoveReviewRequest remove a review request from one reviewer func RemoveReviewRequest(issue *Issue, reviewer, doer *user_model.User) (*Comment, error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } @@ -755,7 +746,7 @@ func RemoveReviewRequest(issue *Issue, reviewer, doer *user_model.User) (*Commen } } - comment, err := CreateCommentCtx(ctx, &CreateCommentOptions{ + comment, err := CreateComment(ctx, &CreateCommentOptions{ Type: CommentTypeReviewRequest, Doer: doer, Repo: issue.Repo, @@ -772,7 +763,7 @@ func RemoveReviewRequest(issue *Issue, reviewer, doer *user_model.User) (*Commen // AddTeamReviewRequest add a review request from one team func AddTeamReviewRequest(issue *Issue, reviewer *organization.Team, doer *user_model.User) (*Comment, error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } @@ -813,7 +804,7 @@ func AddTeamReviewRequest(issue *Issue, reviewer *organization.Team, doer *user_ } } - comment, err := CreateCommentCtx(ctx, &CreateCommentOptions{ + comment, err := CreateComment(ctx, &CreateCommentOptions{ Type: CommentTypeReviewRequest, Doer: doer, Repo: issue.Repo, @@ -823,7 +814,7 @@ func AddTeamReviewRequest(issue *Issue, reviewer *organization.Team, doer *user_ ReviewID: review.ID, }) if err != nil { - return nil, fmt.Errorf("CreateCommentCtx(): %w", err) + return nil, fmt.Errorf("CreateComment(): %w", err) } return comment, committer.Commit() @@ -831,7 +822,7 @@ func AddTeamReviewRequest(issue *Issue, reviewer *organization.Team, doer *user_ // RemoveTeamReviewRequest remove a review request from one team func RemoveTeamReviewRequest(issue *Issue, reviewer *organization.Team, doer *user_model.User) (*Comment, error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } @@ -873,7 +864,7 @@ func RemoveTeamReviewRequest(issue *Issue, reviewer *organization.Team, doer *us return nil, committer.Commit() } - comment, err := CreateCommentCtx(ctx, &CreateCommentOptions{ + comment, err := CreateComment(ctx, &CreateCommentOptions{ Type: CommentTypeReviewRequest, Doer: doer, Repo: issue.Repo, @@ -882,7 +873,7 @@ func RemoveTeamReviewRequest(issue *Issue, reviewer *organization.Team, doer *us AssigneeTeamID: reviewer.ID, // Use AssigneeTeamID as reviewer team ID }) if err != nil { - return nil, fmt.Errorf("CreateCommentCtx(): %w", err) + return nil, fmt.Errorf("CreateComment(): %w", err) } return comment, committer.Commit() @@ -949,7 +940,7 @@ func CanMarkConversation(issue *Issue, doer *user_model.User) (permResult bool, // DeleteReview delete a review and it's code comments func DeleteReview(r *Review) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/issues/review_test.go b/models/issues/review_test.go index 46d1cc777b..cc4c13f9e2 100644 --- a/models/issues/review_test.go +++ b/models/issues/review_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package issues_test @@ -135,7 +134,7 @@ func TestGetReviewersByIssueID(t *testing.T) { allReviews, err := issues_model.GetReviewersByIssueID(issue.ID) for _, reviewer := range allReviews { - assert.NoError(t, reviewer.LoadReviewer()) + assert.NoError(t, reviewer.LoadReviewer(db.DefaultContext)) } assert.NoError(t, err) if assert.Len(t, allReviews, 3) { diff --git a/models/issues/stopwatch.go b/models/issues/stopwatch.go index a87fbfafa2..6bf936c5d4 100644 --- a/models/issues/stopwatch.go +++ b/models/issues/stopwatch.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues @@ -197,7 +196,7 @@ func FinishIssueStopwatch(ctx context.Context, user *user_model.User, issue *Iss return err } - if _, err := CreateCommentCtx(ctx, &CreateCommentOptions{ + if _, err := CreateComment(ctx, &CreateCommentOptions{ Doer: user, Issue: issue, Repo: issue.Repo, @@ -247,7 +246,7 @@ func CreateIssueStopwatch(ctx context.Context, user *user_model.User, issue *Iss return err } - if _, err := CreateCommentCtx(ctx, &CreateCommentOptions{ + if _, err := CreateComment(ctx, &CreateCommentOptions{ Doer: user, Issue: issue, Repo: issue.Repo, @@ -261,7 +260,7 @@ func CreateIssueStopwatch(ctx context.Context, user *user_model.User, issue *Iss // CancelStopwatch removes the given stopwatch and logs it into issue's timeline. func CancelStopwatch(user *user_model.User, issue *Issue) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -288,7 +287,7 @@ func cancelStopwatch(ctx context.Context, user *user_model.User, issue *Issue) e return err } - if _, err := CreateCommentCtx(ctx, &CreateCommentOptions{ + if _, err := CreateComment(ctx, &CreateCommentOptions{ Doer: user, Issue: issue, Repo: issue.Repo, diff --git a/models/issues/stopwatch_test.go b/models/issues/stopwatch_test.go index a5e33f1cf6..ec2778aa81 100644 --- a/models/issues/stopwatch_test.go +++ b/models/issues/stopwatch_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package issues_test @@ -19,7 +18,7 @@ import ( func TestCancelStopwatch(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - user1, err := user_model.GetUserByID(1) + user1, err := user_model.GetUserByID(db.DefaultContext, 1) assert.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) @@ -59,9 +58,9 @@ func TestHasUserStopwatch(t *testing.T) { func TestCreateOrStopIssueStopwatch(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - user2, err := user_model.GetUserByID(2) + user2, err := user_model.GetUserByID(db.DefaultContext, 2) assert.NoError(t, err) - user3, err := user_model.GetUserByID(3) + user3, err := user_model.GetUserByID(db.DefaultContext, 3) assert.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) diff --git a/models/issues/tracked_time.go b/models/issues/tracked_time.go index ca21eb5149..ac65d654f2 100644 --- a/models/issues/tracked_time.go +++ b/models/issues/tracked_time.go @@ -1,11 +1,11 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issues import ( "context" + "errors" "time" "code.gitea.io/gitea/models/db" @@ -47,33 +47,41 @@ func (t *TrackedTime) LoadAttributes() (err error) { } func (t *TrackedTime) loadAttributes(ctx context.Context) (err error) { + // Load the issue if t.Issue == nil { t.Issue, err = GetIssueByID(ctx, t.IssueID) - if err != nil { - return - } - err = t.Issue.LoadRepo(ctx) - if err != nil { - return - } - } - if t.User == nil { - t.User, err = user_model.GetUserByIDCtx(ctx, t.UserID) - if err != nil { - return - } - } - return err -} - -// LoadAttributes load Issue, User -func (tl TrackedTimeList) LoadAttributes() (err error) { - for _, t := range tl { - if err = t.LoadAttributes(); err != nil { + if err != nil && !errors.Is(err, util.ErrNotExist) { return err } } - return err + // Now load the repo for the issue (which we may have just loaded) + if t.Issue != nil { + err = t.Issue.LoadRepo(ctx) + if err != nil && !errors.Is(err, util.ErrNotExist) { + return err + } + } + // Load the user + if t.User == nil { + t.User, err = user_model.GetUserByID(ctx, t.UserID) + if err != nil { + if !errors.Is(err, util.ErrNotExist) { + return err + } + t.User = user_model.NewGhostUser() + } + } + return nil +} + +// LoadAttributes load Issue, User +func (tl TrackedTimeList) LoadAttributes() error { + for _, t := range tl { + if err := t.LoadAttributes(); err != nil { + return err + } + } + return nil } // FindTrackedTimesOptions represent the filters for tracked times. If an ID is 0 it will be ignored. @@ -149,7 +157,7 @@ func GetTrackedSeconds(ctx context.Context, opts FindTrackedTimesOptions) (track // AddTime will add the given time (in seconds) to the issue func AddTime(user *user_model.User, issue *Issue, amount int64, created time.Time) (*TrackedTime, error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } @@ -164,7 +172,7 @@ func AddTime(user *user_model.User, issue *Issue, amount int64, created time.Tim return nil, err } - if _, err := CreateCommentCtx(ctx, &CreateCommentOptions{ + if _, err := CreateComment(ctx, &CreateCommentOptions{ Issue: issue, Repo: issue.Repo, Doer: user, @@ -206,7 +214,7 @@ func TotalTimes(options *FindTrackedTimesOptions) (map[*user_model.User]string, totalTimes := make(map[*user_model.User]string) // Fetching User and making time human readable for userID, total := range totalTimesByUser { - user, err := user_model.GetUserByID(userID) + user, err := user_model.GetUserByID(db.DefaultContext, userID) if err != nil { if user_model.IsErrUserNotExist(err) { continue @@ -220,7 +228,7 @@ func TotalTimes(options *FindTrackedTimesOptions) (map[*user_model.User]string, // DeleteIssueUserTimes deletes times for issue func DeleteIssueUserTimes(issue *Issue, user *user_model.User) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -242,7 +250,7 @@ func DeleteIssueUserTimes(issue *Issue, user *user_model.User) error { if err := issue.LoadRepo(ctx); err != nil { return err } - if _, err := CreateCommentCtx(ctx, &CreateCommentOptions{ + if _, err := CreateComment(ctx, &CreateCommentOptions{ Issue: issue, Repo: issue.Repo, Doer: user, @@ -257,7 +265,7 @@ func DeleteIssueUserTimes(issue *Issue, user *user_model.User) error { // DeleteTime delete a specific Time func DeleteTime(t *TrackedTime) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -271,7 +279,7 @@ func DeleteTime(t *TrackedTime) error { return err } - if _, err := CreateCommentCtx(ctx, &CreateCommentOptions{ + if _, err := CreateComment(ctx, &CreateCommentOptions{ Issue: t.Issue, Repo: t.Issue.Repo, Doer: t.User, diff --git a/models/issues/tracked_time_test.go b/models/issues/tracked_time_test.go index ba8b242d99..becfd79d41 100644 --- a/models/issues/tracked_time_test.go +++ b/models/issues/tracked_time_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issues_test @@ -19,7 +18,7 @@ import ( func TestAddTime(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - user3, err := user_model.GetUserByID(3) + user3, err := user_model.GetUserByID(db.DefaultContext, 3) assert.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) diff --git a/models/main_test.go b/models/main_test.go index 3584001569..cc4eebfe76 100644 --- a/models/main_test.go +++ b/models/main_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package models diff --git a/models/migrate.go b/models/migrate.go index d842fb967b..b1b5568126 100644 --- a/models/migrate.go +++ b/models/migrate.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package models @@ -20,7 +19,7 @@ func InsertMilestones(ms ...*issues_model.Milestone) (err error) { return nil } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -42,7 +41,7 @@ func InsertMilestones(ms ...*issues_model.Milestone) (err error) { // InsertIssues insert issues to database func InsertIssues(issues ...*issues_model.Issue) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -105,7 +104,7 @@ func InsertIssueComments(comments []*issues_model.Comment) error { issueIDs.Add(comment.IssueID) } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -137,7 +136,7 @@ func InsertIssueComments(comments []*issues_model.Comment) error { // InsertPullRequests inserted pull requests func InsertPullRequests(prs ...*issues_model.PullRequest) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -157,7 +156,7 @@ func InsertPullRequests(prs ...*issues_model.PullRequest) error { // InsertReleases migrates release func InsertReleases(rels ...*repo_model.Release) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/migrate_test.go b/models/migrate_test.go index bc7729673a..48cd905e4c 100644 --- a/models/migrate_test.go +++ b/models/migrate_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package models diff --git a/models/migrations/base/db.go b/models/migrations/base/db.go index 5466b76220..dcf99c96ae 100644 --- a/models/migrations/base/db.go +++ b/models/migrations/base/db.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package base diff --git a/models/migrations/base/db_test.go b/models/migrations/base/db_test.go index ee227b7978..5145e19e86 100644 --- a/models/migrations/base/db_test.go +++ b/models/migrations/base/db_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package base diff --git a/models/migrations/base/hash.go b/models/migrations/base/hash.go index 0f078dd70f..00fd1efd4a 100644 --- a/models/migrations/base/hash.go +++ b/models/migrations/base/hash.go @@ -1,17 +1,16 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package base import ( "crypto/sha256" - "fmt" + "encoding/hex" "golang.org/x/crypto/pbkdf2" ) func HashToken(token, salt string) string { tempHash := pbkdf2.Key([]byte(token), []byte(salt), 10000, 50, sha256.New) - return fmt.Sprintf("%x", tempHash) + return hex.EncodeToString(tempHash) } diff --git a/models/migrations/base/main_test.go b/models/migrations/base/main_test.go index 290d87214a..c1c789150f 100644 --- a/models/migrations/base/main_test.go +++ b/models/migrations/base/main_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package base diff --git a/models/migrations/base/testlogger.go b/models/migrations/base/testlogger.go index 0f35a078ec..7cbf4602be 100644 --- a/models/migrations/base/testlogger.go +++ b/models/migrations/base/testlogger.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package base diff --git a/models/migrations/base/tests.go b/models/migrations/base/tests.go index dafc0df2f2..a9bcd20f67 100644 --- a/models/migrations/base/tests.go +++ b/models/migrations/base/tests.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package base diff --git a/models/migrations/fixtures/Test_addConfidentialClientColumnToOAuth2ApplicationTable/o_auth2_application.yml b/models/migrations/fixtures/Test_AddConfidentialClientColumnToOAuth2ApplicationTable/o_auth2_application.yml similarity index 100% rename from models/migrations/fixtures/Test_addConfidentialClientColumnToOAuth2ApplicationTable/o_auth2_application.yml rename to models/migrations/fixtures/Test_AddConfidentialClientColumnToOAuth2ApplicationTable/o_auth2_application.yml diff --git a/models/migrations/fixtures/Test_addHeaderAuthorizationEncryptedColWebhook/expected_webhook.yml b/models/migrations/fixtures/Test_AddHeaderAuthorizationEncryptedColWebhook/expected_webhook.yml similarity index 100% rename from models/migrations/fixtures/Test_addHeaderAuthorizationEncryptedColWebhook/expected_webhook.yml rename to models/migrations/fixtures/Test_AddHeaderAuthorizationEncryptedColWebhook/expected_webhook.yml diff --git a/models/migrations/fixtures/Test_addHeaderAuthorizationEncryptedColWebhook/hook_task.yml b/models/migrations/fixtures/Test_AddHeaderAuthorizationEncryptedColWebhook/hook_task.yml similarity index 100% rename from models/migrations/fixtures/Test_addHeaderAuthorizationEncryptedColWebhook/hook_task.yml rename to models/migrations/fixtures/Test_AddHeaderAuthorizationEncryptedColWebhook/hook_task.yml diff --git a/models/migrations/fixtures/Test_addHeaderAuthorizationEncryptedColWebhook/webhook.yml b/models/migrations/fixtures/Test_AddHeaderAuthorizationEncryptedColWebhook/webhook.yml similarity index 100% rename from models/migrations/fixtures/Test_addHeaderAuthorizationEncryptedColWebhook/webhook.yml rename to models/migrations/fixtures/Test_AddHeaderAuthorizationEncryptedColWebhook/webhook.yml diff --git a/models/migrations/fixtures/Test_deleteOrphanedIssueLabels/issue_label.yml b/models/migrations/fixtures/Test_DeleteOrphanedIssueLabels/issue_label.yml similarity index 100% rename from models/migrations/fixtures/Test_deleteOrphanedIssueLabels/issue_label.yml rename to models/migrations/fixtures/Test_DeleteOrphanedIssueLabels/issue_label.yml diff --git a/models/migrations/fixtures/Test_deleteOrphanedIssueLabels/label.yml b/models/migrations/fixtures/Test_DeleteOrphanedIssueLabels/label.yml similarity index 100% rename from models/migrations/fixtures/Test_deleteOrphanedIssueLabels/label.yml rename to models/migrations/fixtures/Test_DeleteOrphanedIssueLabels/label.yml diff --git a/models/migrations/fixtures/Test_remigrateU2FCredentials/expected_webauthn_credential.yml b/models/migrations/fixtures/Test_RemigrateU2FCredentials/expected_webauthn_credential.yml similarity index 100% rename from models/migrations/fixtures/Test_remigrateU2FCredentials/expected_webauthn_credential.yml rename to models/migrations/fixtures/Test_RemigrateU2FCredentials/expected_webauthn_credential.yml diff --git a/models/migrations/fixtures/Test_remigrateU2FCredentials/u2f_registration.yml b/models/migrations/fixtures/Test_RemigrateU2FCredentials/u2f_registration.yml similarity index 100% rename from models/migrations/fixtures/Test_remigrateU2FCredentials/u2f_registration.yml rename to models/migrations/fixtures/Test_RemigrateU2FCredentials/u2f_registration.yml diff --git a/models/migrations/fixtures/Test_remigrateU2FCredentials/webauthn_credential.yml b/models/migrations/fixtures/Test_RemigrateU2FCredentials/webauthn_credential.yml similarity index 100% rename from models/migrations/fixtures/Test_remigrateU2FCredentials/webauthn_credential.yml rename to models/migrations/fixtures/Test_RemigrateU2FCredentials/webauthn_credential.yml diff --git a/models/migrations/fixtures/Test_removeInvalidLabels/comment.yml b/models/migrations/fixtures/Test_RemoveInvalidLabels/comment.yml similarity index 100% rename from models/migrations/fixtures/Test_removeInvalidLabels/comment.yml rename to models/migrations/fixtures/Test_RemoveInvalidLabels/comment.yml diff --git a/models/migrations/fixtures/Test_removeInvalidLabels/issue.yml b/models/migrations/fixtures/Test_RemoveInvalidLabels/issue.yml similarity index 100% rename from models/migrations/fixtures/Test_removeInvalidLabels/issue.yml rename to models/migrations/fixtures/Test_RemoveInvalidLabels/issue.yml diff --git a/models/migrations/fixtures/Test_removeInvalidLabels/issue_label.yml b/models/migrations/fixtures/Test_RemoveInvalidLabels/issue_label.yml similarity index 100% rename from models/migrations/fixtures/Test_removeInvalidLabels/issue_label.yml rename to models/migrations/fixtures/Test_RemoveInvalidLabels/issue_label.yml diff --git a/models/migrations/fixtures/Test_removeInvalidLabels/label.yml b/models/migrations/fixtures/Test_RemoveInvalidLabels/label.yml similarity index 100% rename from models/migrations/fixtures/Test_removeInvalidLabels/label.yml rename to models/migrations/fixtures/Test_RemoveInvalidLabels/label.yml diff --git a/models/migrations/fixtures/Test_removeInvalidLabels/repository.yml b/models/migrations/fixtures/Test_RemoveInvalidLabels/repository.yml similarity index 100% rename from models/migrations/fixtures/Test_removeInvalidLabels/repository.yml rename to models/migrations/fixtures/Test_RemoveInvalidLabels/repository.yml diff --git a/models/migrations/fixtures/Test_storeWebauthnCredentialIDAsBytes/expected_webauthn_credential.yml b/models/migrations/fixtures/Test_StoreWebauthnCredentialIDAsBytes/expected_webauthn_credential.yml similarity index 100% rename from models/migrations/fixtures/Test_storeWebauthnCredentialIDAsBytes/expected_webauthn_credential.yml rename to models/migrations/fixtures/Test_StoreWebauthnCredentialIDAsBytes/expected_webauthn_credential.yml diff --git a/models/migrations/fixtures/Test_storeWebauthnCredentialIDAsBytes/webauthn_credential.yml b/models/migrations/fixtures/Test_StoreWebauthnCredentialIDAsBytes/webauthn_credential.yml similarity index 100% rename from models/migrations/fixtures/Test_storeWebauthnCredentialIDAsBytes/webauthn_credential.yml rename to models/migrations/fixtures/Test_StoreWebauthnCredentialIDAsBytes/webauthn_credential.yml diff --git a/models/migrations/fixtures/Test_unwrapLDAPSourceCfg/login_source.yml b/models/migrations/fixtures/Test_UnwrapLDAPSourceCfg/login_source.yml similarity index 100% rename from models/migrations/fixtures/Test_unwrapLDAPSourceCfg/login_source.yml rename to models/migrations/fixtures/Test_UnwrapLDAPSourceCfg/login_source.yml diff --git a/models/migrations/fixtures/Test_updateOpenMilestoneCounts/expected_milestone.yml b/models/migrations/fixtures/Test_UpdateOpenMilestoneCounts/expected_milestone.yml similarity index 100% rename from models/migrations/fixtures/Test_updateOpenMilestoneCounts/expected_milestone.yml rename to models/migrations/fixtures/Test_UpdateOpenMilestoneCounts/expected_milestone.yml diff --git a/models/migrations/fixtures/Test_updateOpenMilestoneCounts/issue.yml b/models/migrations/fixtures/Test_UpdateOpenMilestoneCounts/issue.yml similarity index 100% rename from models/migrations/fixtures/Test_updateOpenMilestoneCounts/issue.yml rename to models/migrations/fixtures/Test_UpdateOpenMilestoneCounts/issue.yml diff --git a/models/migrations/fixtures/Test_updateOpenMilestoneCounts/milestone.yml b/models/migrations/fixtures/Test_UpdateOpenMilestoneCounts/milestone.yml similarity index 100% rename from models/migrations/fixtures/Test_updateOpenMilestoneCounts/milestone.yml rename to models/migrations/fixtures/Test_UpdateOpenMilestoneCounts/milestone.yml diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index 5f5ec8fdd7..e718355f83 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -1,11 +1,11 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2017 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. +// SPDX-License-Identifier: MIT package migrations import ( + "context" "fmt" "os" @@ -23,6 +23,7 @@ import ( "code.gitea.io/gitea/models/migrations/v1_7" "code.gitea.io/gitea/models/migrations/v1_8" "code.gitea.io/gitea/models/migrations/v1_9" + "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -437,6 +438,10 @@ var migrations = []Migration{ NewMigration("Alter package_version.metadata_json to LONGTEXT", v1_19.AlterPackageVersionMetadataToLongText), // v233 -> v234 NewMigration("Add header_authorization_encrypted column to webhook table", v1_19.AddHeaderAuthorizationEncryptedColWebhook), + // v234 -> v235 + NewMigration("Add package cleanup rule table", v1_19.CreatePackageCleanupRuleTable), + // v235 -> v236 + NewMigration("Add index for access_token", v1_19.AddIndexForAccessToken), } // GetCurrentDBVersion returns the current db version @@ -527,6 +532,13 @@ Please try upgrading to a lower version first (suggested v1.6.4), then upgrade t return nil } + // Some migration tasks depend on the git command + if git.DefaultContext == nil { + if err = git.InitSimple(context.Background()); err != nil { + return err + } + } + // Migrate for i, m := range migrations[v-minDBVersion:] { log.Info("Migration[%d]: %s", v+int64(i), m.Description()) diff --git a/models/migrations/v1_10/v100.go b/models/migrations/v1_10/v100.go index af58b4b21d..bd11790b98 100644 --- a/models/migrations/v1_10/v100.go +++ b/models/migrations/v1_10/v100.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_10 //nolint diff --git a/models/migrations/v1_10/v101.go b/models/migrations/v1_10/v101.go index 350e537a97..79b419e9d9 100644 --- a/models/migrations/v1_10/v101.go +++ b/models/migrations/v1_10/v101.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_10 //nolint diff --git a/models/migrations/v1_10/v88.go b/models/migrations/v1_10/v88.go index 32659006ea..e6376af62e 100644 --- a/models/migrations/v1_10/v88.go +++ b/models/migrations/v1_10/v88.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_10 //nolint diff --git a/models/migrations/v1_10/v89.go b/models/migrations/v1_10/v89.go index 4b21ef20ff..937068292c 100644 --- a/models/migrations/v1_10/v89.go +++ b/models/migrations/v1_10/v89.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_10 //nolint diff --git a/models/migrations/v1_10/v90.go b/models/migrations/v1_10/v90.go index aa08ac36bc..c9a69a6dfe 100644 --- a/models/migrations/v1_10/v90.go +++ b/models/migrations/v1_10/v90.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_10 //nolint diff --git a/models/migrations/v1_10/v91.go b/models/migrations/v1_10/v91.go index b8c083f8d4..9b5fefb1d0 100644 --- a/models/migrations/v1_10/v91.go +++ b/models/migrations/v1_10/v91.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_10 //nolint diff --git a/models/migrations/v1_10/v92.go b/models/migrations/v1_10/v92.go index c0552aaab5..9080108594 100644 --- a/models/migrations/v1_10/v92.go +++ b/models/migrations/v1_10/v92.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_10 //nolint diff --git a/models/migrations/v1_10/v93.go b/models/migrations/v1_10/v93.go index 6ce89f0d49..5b59065171 100644 --- a/models/migrations/v1_10/v93.go +++ b/models/migrations/v1_10/v93.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_10 //nolint diff --git a/models/migrations/v1_10/v94.go b/models/migrations/v1_10/v94.go index 542e45c139..fe3804aee4 100644 --- a/models/migrations/v1_10/v94.go +++ b/models/migrations/v1_10/v94.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_10 //nolint diff --git a/models/migrations/v1_10/v95.go b/models/migrations/v1_10/v95.go index 48a0c4ea7f..1b60eefb42 100644 --- a/models/migrations/v1_10/v95.go +++ b/models/migrations/v1_10/v95.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_10 //nolint diff --git a/models/migrations/v1_10/v96.go b/models/migrations/v1_10/v96.go index 372ca9e65a..422defe838 100644 --- a/models/migrations/v1_10/v96.go +++ b/models/migrations/v1_10/v96.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_10 //nolint @@ -31,19 +30,19 @@ func DeleteOrphanedAttachments(x *xorm.Engine) error { } for { - attachements := make([]Attachment, 0, limit) + attachments := make([]Attachment, 0, limit) if err := sess.Where("`issue_id` = 0 and (`release_id` = 0 or `release_id` not in (select `id` from `release`))"). Cols("id, uuid").Limit(limit). Asc("id"). - Find(&attachements); err != nil { + Find(&attachments); err != nil { return err } - if len(attachements) == 0 { + if len(attachments) == 0 { return nil } ids := make([]int64, 0, limit) - for _, attachment := range attachements { + for _, attachment := range attachments { ids = append(ids, attachment.ID) } if len(ids) > 0 { @@ -52,13 +51,13 @@ func DeleteOrphanedAttachments(x *xorm.Engine) error { } } - for _, attachment := range attachements { + for _, attachment := range attachments { uuid := attachment.UUID if err := util.RemoveAll(filepath.Join(setting.Attachment.Path, uuid[0:1], uuid[1:2], uuid)); err != nil { return err } } - if len(attachements) < limit { + if len(attachments) < limit { return nil } } diff --git a/models/migrations/v1_10/v97.go b/models/migrations/v1_10/v97.go index 4438a9ed50..8a1a4426ab 100644 --- a/models/migrations/v1_10/v97.go +++ b/models/migrations/v1_10/v97.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_10 //nolint diff --git a/models/migrations/v1_10/v98.go b/models/migrations/v1_10/v98.go index 8e9ebb7d97..cab9a63065 100644 --- a/models/migrations/v1_10/v98.go +++ b/models/migrations/v1_10/v98.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_10 //nolint diff --git a/models/migrations/v1_10/v99.go b/models/migrations/v1_10/v99.go index 21554f6eff..170a30631f 100644 --- a/models/migrations/v1_10/v99.go +++ b/models/migrations/v1_10/v99.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_10 //nolint diff --git a/models/migrations/v1_11/v102.go b/models/migrations/v1_11/v102.go index 49d9d3ae71..9358e4cef3 100644 --- a/models/migrations/v1_11/v102.go +++ b/models/migrations/v1_11/v102.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_11/v103.go b/models/migrations/v1_11/v103.go index e9114adeef..e4e16a054e 100644 --- a/models/migrations/v1_11/v103.go +++ b/models/migrations/v1_11/v103.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_11/v104.go b/models/migrations/v1_11/v104.go index 0ab3682f6e..c76554cf59 100644 --- a/models/migrations/v1_11/v104.go +++ b/models/migrations/v1_11/v104.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_11/v105.go b/models/migrations/v1_11/v105.go index 07aeedcd62..df261c992c 100644 --- a/models/migrations/v1_11/v105.go +++ b/models/migrations/v1_11/v105.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_11/v106.go b/models/migrations/v1_11/v106.go index af77508667..3e06309a8d 100644 --- a/models/migrations/v1_11/v106.go +++ b/models/migrations/v1_11/v106.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_11/v107.go b/models/migrations/v1_11/v107.go index 5cc0d5282d..1ffbd35dd7 100644 --- a/models/migrations/v1_11/v107.go +++ b/models/migrations/v1_11/v107.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_11/v108.go b/models/migrations/v1_11/v108.go index 06ff1b16e3..28132c377d 100644 --- a/models/migrations/v1_11/v108.go +++ b/models/migrations/v1_11/v108.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_11/v109.go b/models/migrations/v1_11/v109.go index 2bfd2536bf..d2ee9a6aaa 100644 --- a/models/migrations/v1_11/v109.go +++ b/models/migrations/v1_11/v109.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_11/v110.go b/models/migrations/v1_11/v110.go index 813a753e0c..81afa1331d 100644 --- a/models/migrations/v1_11/v110.go +++ b/models/migrations/v1_11/v110.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_11/v111.go b/models/migrations/v1_11/v111.go index f1f1d7cb0f..5b15c32163 100644 --- a/models/migrations/v1_11/v111.go +++ b/models/migrations/v1_11/v111.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_11/v112.go b/models/migrations/v1_11/v112.go index f8e84cf752..3478ffe449 100644 --- a/models/migrations/v1_11/v112.go +++ b/models/migrations/v1_11/v112.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_11/v113.go b/models/migrations/v1_11/v113.go index 36ab1bd9c4..dc9adb60b0 100644 --- a/models/migrations/v1_11/v113.go +++ b/models/migrations/v1_11/v113.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_11/v114.go b/models/migrations/v1_11/v114.go index 688dd06d42..95adcee989 100644 --- a/models/migrations/v1_11/v114.go +++ b/models/migrations/v1_11/v114.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_11/v115.go b/models/migrations/v1_11/v115.go index 1fbf0c4f25..da935f6514 100644 --- a/models/migrations/v1_11/v115.go +++ b/models/migrations/v1_11/v115.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_11/v116.go b/models/migrations/v1_11/v116.go index 6b6d91777b..73fddd1039 100644 --- a/models/migrations/v1_11/v116.go +++ b/models/migrations/v1_11/v116.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_11 //nolint diff --git a/models/migrations/v1_12/v117.go b/models/migrations/v1_12/v117.go index 6a102e0df7..bc768f3f0b 100644 --- a/models/migrations/v1_12/v117.go +++ b/models/migrations/v1_12/v117.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v118.go b/models/migrations/v1_12/v118.go index 227daffc45..9b893e2992 100644 --- a/models/migrations/v1_12/v118.go +++ b/models/migrations/v1_12/v118.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v119.go b/models/migrations/v1_12/v119.go index 998ca004d2..60bfe6a57d 100644 --- a/models/migrations/v1_12/v119.go +++ b/models/migrations/v1_12/v119.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v120.go b/models/migrations/v1_12/v120.go index cc35ce5f3e..f4e61215eb 100644 --- a/models/migrations/v1_12/v120.go +++ b/models/migrations/v1_12/v120.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v121.go b/models/migrations/v1_12/v121.go index 19864658d1..ac656b2d42 100644 --- a/models/migrations/v1_12/v121.go +++ b/models/migrations/v1_12/v121.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v122.go b/models/migrations/v1_12/v122.go index b0edae93bd..67ac9411fa 100644 --- a/models/migrations/v1_12/v122.go +++ b/models/migrations/v1_12/v122.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v123.go b/models/migrations/v1_12/v123.go index 1ecfdce736..ec56161afa 100644 --- a/models/migrations/v1_12/v123.go +++ b/models/migrations/v1_12/v123.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v124.go b/models/migrations/v1_12/v124.go index 0fc86378db..311690c039 100644 --- a/models/migrations/v1_12/v124.go +++ b/models/migrations/v1_12/v124.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v125.go b/models/migrations/v1_12/v125.go index d74f888e90..5540dfd626 100644 --- a/models/migrations/v1_12/v125.go +++ b/models/migrations/v1_12/v125.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v126.go b/models/migrations/v1_12/v126.go index 51dfb51673..ca9ec3aa3f 100644 --- a/models/migrations/v1_12/v126.go +++ b/models/migrations/v1_12/v126.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v127.go b/models/migrations/v1_12/v127.go index 5849b82566..b248eb4c06 100644 --- a/models/migrations/v1_12/v127.go +++ b/models/migrations/v1_12/v127.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v128.go b/models/migrations/v1_12/v128.go index 71e8e32077..44d44a26c5 100644 --- a/models/migrations/v1_12/v128.go +++ b/models/migrations/v1_12/v128.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v129.go b/models/migrations/v1_12/v129.go index 28bc5f604f..cf228242b9 100644 --- a/models/migrations/v1_12/v129.go +++ b/models/migrations/v1_12/v129.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v130.go b/models/migrations/v1_12/v130.go index ca3765be7b..391810c7ca 100644 --- a/models/migrations/v1_12/v130.go +++ b/models/migrations/v1_12/v130.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v131.go b/models/migrations/v1_12/v131.go index 14d954b4ba..a734d9fbf8 100644 --- a/models/migrations/v1_12/v131.go +++ b/models/migrations/v1_12/v131.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v132.go b/models/migrations/v1_12/v132.go index 8d93460f76..1708a57a7e 100644 --- a/models/migrations/v1_12/v132.go +++ b/models/migrations/v1_12/v132.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v133.go b/models/migrations/v1_12/v133.go index 1d69c47b9f..e1c392459b 100644 --- a/models/migrations/v1_12/v133.go +++ b/models/migrations/v1_12/v133.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v134.go b/models/migrations/v1_12/v134.go index 297db37a08..3d1c82f09e 100644 --- a/models/migrations/v1_12/v134.go +++ b/models/migrations/v1_12/v134.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v135.go b/models/migrations/v1_12/v135.go index 9453ecdd58..5a87d9911b 100644 --- a/models/migrations/v1_12/v135.go +++ b/models/migrations/v1_12/v135.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v136.go b/models/migrations/v1_12/v136.go index b114ddf508..0cecba7be9 100644 --- a/models/migrations/v1_12/v136.go +++ b/models/migrations/v1_12/v136.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v137.go b/models/migrations/v1_12/v137.go index 6eb6b1ebb3..371b1a3fdb 100644 --- a/models/migrations/v1_12/v137.go +++ b/models/migrations/v1_12/v137.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v138.go b/models/migrations/v1_12/v138.go index c101c6e4cd..a2bfdb59a8 100644 --- a/models/migrations/v1_12/v138.go +++ b/models/migrations/v1_12/v138.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_12/v139.go b/models/migrations/v1_12/v139.go index 69daa94f98..725b8fa305 100644 --- a/models/migrations/v1_12/v139.go +++ b/models/migrations/v1_12/v139.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_12 //nolint diff --git a/models/migrations/v1_13/v140.go b/models/migrations/v1_13/v140.go index 37aeeaeb6b..3de9eaaf7c 100644 --- a/models/migrations/v1_13/v140.go +++ b/models/migrations/v1_13/v140.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_13/v141.go b/models/migrations/v1_13/v141.go index 7dd1cc5d67..80796e6db9 100644 --- a/models/migrations/v1_13/v141.go +++ b/models/migrations/v1_13/v141.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_13/v142.go b/models/migrations/v1_13/v142.go index 3a2206b6c6..7c7c01ad47 100644 --- a/models/migrations/v1_13/v142.go +++ b/models/migrations/v1_13/v142.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_13/v143.go b/models/migrations/v1_13/v143.go index eee66c0a0d..ad1a8c66a5 100644 --- a/models/migrations/v1_13/v143.go +++ b/models/migrations/v1_13/v143.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_13/v144.go b/models/migrations/v1_13/v144.go index 0b8b91268b..f5a0bc5751 100644 --- a/models/migrations/v1_13/v144.go +++ b/models/migrations/v1_13/v144.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_13/v145.go b/models/migrations/v1_13/v145.go index b12da3c675..c96e79f8a0 100644 --- a/models/migrations/v1_13/v145.go +++ b/models/migrations/v1_13/v145.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_13/v146.go b/models/migrations/v1_13/v146.go index 7afd325371..5db8b0a437 100644 --- a/models/migrations/v1_13/v146.go +++ b/models/migrations/v1_13/v146.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_13/v147.go b/models/migrations/v1_13/v147.go index 1518b8dd24..d9c51145c4 100644 --- a/models/migrations/v1_13/v147.go +++ b/models/migrations/v1_13/v147.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_13/v148.go b/models/migrations/v1_13/v148.go index 40ede7174c..7bb8ab700b 100644 --- a/models/migrations/v1_13/v148.go +++ b/models/migrations/v1_13/v148.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_13/v149.go b/models/migrations/v1_13/v149.go index f0054b752d..e093b4f9db 100644 --- a/models/migrations/v1_13/v149.go +++ b/models/migrations/v1_13/v149.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_13/v150.go b/models/migrations/v1_13/v150.go index 99e6ddf685..d5ba489566 100644 --- a/models/migrations/v1_13/v150.go +++ b/models/migrations/v1_13/v150.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_13/v151.go b/models/migrations/v1_13/v151.go index 9efda93645..9490c1778c 100644 --- a/models/migrations/v1_13/v151.go +++ b/models/migrations/v1_13/v151.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_13/v152.go b/models/migrations/v1_13/v152.go index ec49a2fb97..7f7c414de8 100644 --- a/models/migrations/v1_13/v152.go +++ b/models/migrations/v1_13/v152.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_13/v153.go b/models/migrations/v1_13/v153.go index 1428edd3c1..4146d83387 100644 --- a/models/migrations/v1_13/v153.go +++ b/models/migrations/v1_13/v153.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_13/v154.go b/models/migrations/v1_13/v154.go index 8976db675c..8b4498be84 100644 --- a/models/migrations/v1_13/v154.go +++ b/models/migrations/v1_13/v154.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_13 //nolint diff --git a/models/migrations/v1_14/main_test.go b/models/migrations/v1_14/main_test.go index 859f7520ee..7a091b9b9a 100644 --- a/models/migrations/v1_14/main_test.go +++ b/models/migrations/v1_14/main_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v155.go b/models/migrations/v1_14/v155.go index 630eb94f1a..7c5dc5fbe2 100644 --- a/models/migrations/v1_14/v155.go +++ b/models/migrations/v1_14/v155.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v156.go b/models/migrations/v1_14/v156.go index 698c1c942b..2cf4954a15 100644 --- a/models/migrations/v1_14/v156.go +++ b/models/migrations/v1_14/v156.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v157.go b/models/migrations/v1_14/v157.go index 12f0876d61..b9d8225af8 100644 --- a/models/migrations/v1_14/v157.go +++ b/models/migrations/v1_14/v157.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v158.go b/models/migrations/v1_14/v158.go index e6c9e629f7..7ea80a659e 100644 --- a/models/migrations/v1_14/v158.go +++ b/models/migrations/v1_14/v158.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v159.go b/models/migrations/v1_14/v159.go index 60be2b12bd..149ae0f6a8 100644 --- a/models/migrations/v1_14/v159.go +++ b/models/migrations/v1_14/v159.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v160.go b/models/migrations/v1_14/v160.go index 5bdf180ef9..b9b7e7fbdd 100644 --- a/models/migrations/v1_14/v160.go +++ b/models/migrations/v1_14/v160.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v161.go b/models/migrations/v1_14/v161.go index cf661caa37..ef3c14d595 100644 --- a/models/migrations/v1_14/v161.go +++ b/models/migrations/v1_14/v161.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v162.go b/models/migrations/v1_14/v162.go index bfaa824fa2..972f771fd7 100644 --- a/models/migrations/v1_14/v162.go +++ b/models/migrations/v1_14/v162.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v163.go b/models/migrations/v1_14/v163.go index 8044dd4035..22f55f48d1 100644 --- a/models/migrations/v1_14/v163.go +++ b/models/migrations/v1_14/v163.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v164.go b/models/migrations/v1_14/v164.go index 0a14248503..a6791b16e0 100644 --- a/models/migrations/v1_14/v164.go +++ b/models/migrations/v1_14/v164.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v165.go b/models/migrations/v1_14/v165.go index d42dea96a5..a784832e1c 100644 --- a/models/migrations/v1_14/v165.go +++ b/models/migrations/v1_14/v165.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v166.go b/models/migrations/v1_14/v166.go index bdb18ffa64..f797930d6d 100644 --- a/models/migrations/v1_14/v166.go +++ b/models/migrations/v1_14/v166.go @@ -1,12 +1,11 @@ // 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint import ( "crypto/sha256" - "fmt" + "encoding/hex" "golang.org/x/crypto/argon2" "golang.org/x/crypto/bcrypt" @@ -54,7 +53,7 @@ func RecalculateUserEmptyPWD(x *xorm.Engine) (err error) { tempPasswd = pbkdf2.Key([]byte(passwd), []byte(salt), 10000, 50, sha256.New) } - return fmt.Sprintf("%x", tempPasswd) + return hex.EncodeToString(tempPasswd) } // ValidatePassword checks if given password matches the one belongs to the user. diff --git a/models/migrations/v1_14/v167.go b/models/migrations/v1_14/v167.go index 8098a76213..fb6b3b474a 100644 --- a/models/migrations/v1_14/v167.go +++ b/models/migrations/v1_14/v167.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v168.go b/models/migrations/v1_14/v168.go index e62ab909a0..a30a8859f7 100644 --- a/models/migrations/v1_14/v168.go +++ b/models/migrations/v1_14/v168.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v169.go b/models/migrations/v1_14/v169.go index f5fe332d97..5b81bb58b1 100644 --- a/models/migrations/v1_14/v169.go +++ b/models/migrations/v1_14/v169.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v170.go b/models/migrations/v1_14/v170.go index cb0f927a2f..adb28cae5e 100644 --- a/models/migrations/v1_14/v170.go +++ b/models/migrations/v1_14/v170.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v171.go b/models/migrations/v1_14/v171.go index 0c94fd4f93..35769342e8 100644 --- a/models/migrations/v1_14/v171.go +++ b/models/migrations/v1_14/v171.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v172.go b/models/migrations/v1_14/v172.go index 6518c03174..76519b9457 100644 --- a/models/migrations/v1_14/v172.go +++ b/models/migrations/v1_14/v172.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v173.go b/models/migrations/v1_14/v173.go index c8c9c39c69..3b7ecb8f9d 100644 --- a/models/migrations/v1_14/v173.go +++ b/models/migrations/v1_14/v173.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v174.go b/models/migrations/v1_14/v174.go index 9a139764c3..766d3a4208 100644 --- a/models/migrations/v1_14/v174.go +++ b/models/migrations/v1_14/v174.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v175.go b/models/migrations/v1_14/v175.go index e66871f5ee..f1b9b974c6 100644 --- a/models/migrations/v1_14/v175.go +++ b/models/migrations/v1_14/v175.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v176.go b/models/migrations/v1_14/v176.go index 4a343159ec..bd2484e49d 100644 --- a/models/migrations/v1_14/v176.go +++ b/models/migrations/v1_14/v176.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v176_test.go b/models/migrations/v1_14/v176_test.go index c088af9066..ea3e750d7f 100644 --- a/models/migrations/v1_14/v176_test.go +++ b/models/migrations/v1_14/v176_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v177.go b/models/migrations/v1_14/v177.go index c3086cd8e9..e72a9e53a9 100644 --- a/models/migrations/v1_14/v177.go +++ b/models/migrations/v1_14/v177.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_14/v177_test.go b/models/migrations/v1_14/v177_test.go index 4e061316d3..5568a18fec 100644 --- a/models/migrations/v1_14/v177_test.go +++ b/models/migrations/v1_14/v177_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_14 //nolint diff --git a/models/migrations/v1_15/main_test.go b/models/migrations/v1_15/main_test.go index d589734e37..366f19788e 100644 --- a/models/migrations/v1_15/main_test.go +++ b/models/migrations/v1_15/main_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_15 //nolint diff --git a/models/migrations/v1_15/v178.go b/models/migrations/v1_15/v178.go index 27ece98916..9bb6ed7f8d 100644 --- a/models/migrations/v1_15/v178.go +++ b/models/migrations/v1_15/v178.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_15 //nolint diff --git a/models/migrations/v1_15/v179.go b/models/migrations/v1_15/v179.go index c23bf91766..f6b142eb42 100644 --- a/models/migrations/v1_15/v179.go +++ b/models/migrations/v1_15/v179.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_15 //nolint diff --git a/models/migrations/v1_15/v180.go b/models/migrations/v1_15/v180.go index fc948bb1f5..17163ee2c6 100644 --- a/models/migrations/v1_15/v180.go +++ b/models/migrations/v1_15/v180.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_15 //nolint diff --git a/models/migrations/v1_15/v181.go b/models/migrations/v1_15/v181.go index 7ec3dae376..e2bb3208c4 100644 --- a/models/migrations/v1_15/v181.go +++ b/models/migrations/v1_15/v181.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_15 //nolint diff --git a/models/migrations/v1_15/v181_test.go b/models/migrations/v1_15/v181_test.go index f621d0d162..1b075be7a0 100644 --- a/models/migrations/v1_15/v181_test.go +++ b/models/migrations/v1_15/v181_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_15 //nolint diff --git a/models/migrations/v1_15/v182.go b/models/migrations/v1_15/v182.go index 32282089af..c584ef851d 100644 --- a/models/migrations/v1_15/v182.go +++ b/models/migrations/v1_15/v182.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_15 //nolint diff --git a/models/migrations/v1_15/v182_test.go b/models/migrations/v1_15/v182_test.go index b227e557ae..75ef8e1cd8 100644 --- a/models/migrations/v1_15/v182_test.go +++ b/models/migrations/v1_15/v182_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_15 //nolint diff --git a/models/migrations/v1_15/v183.go b/models/migrations/v1_15/v183.go index 48039f8dc4..4cc98f9efc 100644 --- a/models/migrations/v1_15/v183.go +++ b/models/migrations/v1_15/v183.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_15 //nolint diff --git a/models/migrations/v1_15/v184.go b/models/migrations/v1_15/v184.go index 195b419bc3..48f8b62165 100644 --- a/models/migrations/v1_15/v184.go +++ b/models/migrations/v1_15/v184.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_15 //nolint diff --git a/models/migrations/v1_15/v185.go b/models/migrations/v1_15/v185.go index 4b8ed2e038..382cb62147 100644 --- a/models/migrations/v1_15/v185.go +++ b/models/migrations/v1_15/v185.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_15 //nolint diff --git a/models/migrations/v1_15/v186.go b/models/migrations/v1_15/v186.go index 3f53ff6a11..310ac85f4c 100644 --- a/models/migrations/v1_15/v186.go +++ b/models/migrations/v1_15/v186.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_15 //nolint diff --git a/models/migrations/v1_15/v187.go b/models/migrations/v1_15/v187.go index c3f60d1db8..afd86bac45 100644 --- a/models/migrations/v1_15/v187.go +++ b/models/migrations/v1_15/v187.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_15 //nolint diff --git a/models/migrations/v1_15/v188.go b/models/migrations/v1_15/v188.go index 265b6f2f3f..71e45cab0e 100644 --- a/models/migrations/v1_15/v188.go +++ b/models/migrations/v1_15/v188.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_15 //nolint diff --git a/models/migrations/v1_16/main_test.go b/models/migrations/v1_16/main_test.go index 8109a8a263..817a0c13a4 100644 --- a/models/migrations/v1_16/main_test.go +++ b/models/migrations/v1_16/main_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v189.go b/models/migrations/v1_16/v189.go index b04115845e..32e3899a3a 100644 --- a/models/migrations/v1_16/v189.go +++ b/models/migrations/v1_16/v189.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v189_test.go b/models/migrations/v1_16/v189_test.go index 9c0f0967cd..96cb97c328 100644 --- a/models/migrations/v1_16/v189_test.go +++ b/models/migrations/v1_16/v189_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v190.go b/models/migrations/v1_16/v190.go index a669fc31fa..1853729ae9 100644 --- a/models/migrations/v1_16/v190.go +++ b/models/migrations/v1_16/v190.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v191.go b/models/migrations/v1_16/v191.go index 461ac653d4..2d2c3d1a58 100644 --- a/models/migrations/v1_16/v191.go +++ b/models/migrations/v1_16/v191.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v192.go b/models/migrations/v1_16/v192.go index e3ac2654fd..2d5d158a09 100644 --- a/models/migrations/v1_16/v192.go +++ b/models/migrations/v1_16/v192.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v193.go b/models/migrations/v1_16/v193.go index 8bf960feb3..dd50e353e3 100644 --- a/models/migrations/v1_16/v193.go +++ b/models/migrations/v1_16/v193.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v193_test.go b/models/migrations/v1_16/v193_test.go index b573a54bb0..17669a012e 100644 --- a/models/migrations/v1_16/v193_test.go +++ b/models/migrations/v1_16/v193_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v194.go b/models/migrations/v1_16/v194.go index 8486b1131a..ae7fe10bfc 100644 --- a/models/migrations/v1_16/v194.go +++ b/models/migrations/v1_16/v194.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v195.go b/models/migrations/v1_16/v195.go index a7165cbf75..9e390a971e 100644 --- a/models/migrations/v1_16/v195.go +++ b/models/migrations/v1_16/v195.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v195_test.go b/models/migrations/v1_16/v195_test.go index 06ff13b52b..742397bf32 100644 --- a/models/migrations/v1_16/v195_test.go +++ b/models/migrations/v1_16/v195_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v196.go b/models/migrations/v1_16/v196.go index b73a56607e..ed7f4185a1 100644 --- a/models/migrations/v1_16/v196.go +++ b/models/migrations/v1_16/v196.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v197.go b/models/migrations/v1_16/v197.go index da2e9ae76f..ef9d57a79e 100644 --- a/models/migrations/v1_16/v197.go +++ b/models/migrations/v1_16/v197.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v198.go b/models/migrations/v1_16/v198.go index 0e09ee5306..ed792de793 100644 --- a/models/migrations/v1_16/v198.go +++ b/models/migrations/v1_16/v198.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v199.go b/models/migrations/v1_16/v199.go index 53ed7e4e8a..6adcf890af 100644 --- a/models/migrations/v1_16/v199.go +++ b/models/migrations/v1_16/v199.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v200.go b/models/migrations/v1_16/v200.go index 70ee36354c..e39f4af9e8 100644 --- a/models/migrations/v1_16/v200.go +++ b/models/migrations/v1_16/v200.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v201.go b/models/migrations/v1_16/v201.go index 6a2eda77b1..35e0c9f2fb 100644 --- a/models/migrations/v1_16/v201.go +++ b/models/migrations/v1_16/v201.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v202.go b/models/migrations/v1_16/v202.go index de0576b8d6..79676f3fab 100644 --- a/models/migrations/v1_16/v202.go +++ b/models/migrations/v1_16/v202.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v203.go b/models/migrations/v1_16/v203.go index 78903cb595..26ec135a07 100644 --- a/models/migrations/v1_16/v203.go +++ b/models/migrations/v1_16/v203.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v204.go b/models/migrations/v1_16/v204.go index 8151866fa2..e7577c8da4 100644 --- a/models/migrations/v1_16/v204.go +++ b/models/migrations/v1_16/v204.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v205.go b/models/migrations/v1_16/v205.go index 9cca445d35..d6c577083c 100644 --- a/models/migrations/v1_16/v205.go +++ b/models/migrations/v1_16/v205.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v206.go b/models/migrations/v1_16/v206.go index b2530d1005..64c794a2d0 100644 --- a/models/migrations/v1_16/v206.go +++ b/models/migrations/v1_16/v206.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v207.go b/models/migrations/v1_16/v207.go index f93ae4c339..91208f066c 100644 --- a/models/migrations/v1_16/v207.go +++ b/models/migrations/v1_16/v207.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v208.go b/models/migrations/v1_16/v208.go index 40f8b05b80..1a11ef096a 100644 --- a/models/migrations/v1_16/v208.go +++ b/models/migrations/v1_16/v208.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v209.go b/models/migrations/v1_16/v209.go index e2f06bbfb0..be3100e02a 100644 --- a/models/migrations/v1_16/v209.go +++ b/models/migrations/v1_16/v209.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v210.go b/models/migrations/v1_16/v210.go index b59b356607..974e77fb84 100644 --- a/models/migrations/v1_16/v210.go +++ b/models/migrations/v1_16/v210.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_16/v210_test.go b/models/migrations/v1_16/v210_test.go index 20c430594e..d43fb03106 100644 --- a/models/migrations/v1_16/v210_test.go +++ b/models/migrations/v1_16/v210_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package v1_16 //nolint diff --git a/models/migrations/v1_17/main_test.go b/models/migrations/v1_17/main_test.go index 0f1708de8b..79cb3fa078 100644 --- a/models/migrations/v1_17/main_test.go +++ b/models/migrations/v1_17/main_test.go @@ -1,8 +1,7 @@ // 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint import ( "testing" diff --git a/models/migrations/v1_17/v211.go b/models/migrations/v1_17/v211.go index de9eb4b4b0..16ec518493 100644 --- a/models/migrations/v1_17/v211.go +++ b/models/migrations/v1_17/v211.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint import ( "fmt" diff --git a/models/migrations/v1_17/v212.go b/models/migrations/v1_17/v212.go index 5187f5e72f..536ba0a2c4 100644 --- a/models/migrations/v1_17/v212.go +++ b/models/migrations/v1_17/v212.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint import ( "code.gitea.io/gitea/modules/timeutil" diff --git a/models/migrations/v1_17/v213.go b/models/migrations/v1_17/v213.go index 7b1b158f9f..8607fdba47 100644 --- a/models/migrations/v1_17/v213.go +++ b/models/migrations/v1_17/v213.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint import ( "xorm.io/xorm" diff --git a/models/migrations/v1_17/v214.go b/models/migrations/v1_17/v214.go index e6fa53d4b8..3b2351d160 100644 --- a/models/migrations/v1_17/v214.go +++ b/models/migrations/v1_17/v214.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint import ( "xorm.io/xorm" diff --git a/models/migrations/v1_17/v215.go b/models/migrations/v1_17/v215.go index e148515964..0244be216c 100644 --- a/models/migrations/v1_17/v215.go +++ b/models/migrations/v1_17/v215.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint import ( "code.gitea.io/gitea/models/pull" diff --git a/models/migrations/v1_17/v216.go b/models/migrations/v1_17/v216.go index bde5825772..59b21d9b2c 100644 --- a/models/migrations/v1_17/v216.go +++ b/models/migrations/v1_17/v216.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint // This migration added non-ideal indices to the action table which on larger datasets slowed things down // it has been superceded by v218.go diff --git a/models/migrations/v1_17/v217.go b/models/migrations/v1_17/v217.go index abba9e8ec9..3ca9215f09 100644 --- a/models/migrations/v1_17/v217.go +++ b/models/migrations/v1_17/v217.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint import ( "code.gitea.io/gitea/modules/setting" diff --git a/models/migrations/v1_17/v218.go b/models/migrations/v1_17/v218.go index a5cd1c591a..675fd1df94 100644 --- a/models/migrations/v1_17/v218.go +++ b/models/migrations/v1_17/v218.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint import ( "code.gitea.io/gitea/modules/setting" diff --git a/models/migrations/v1_17/v219.go b/models/migrations/v1_17/v219.go index d22f4e6b8e..a2165212cc 100644 --- a/models/migrations/v1_17/v219.go +++ b/models/migrations/v1_17/v219.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint import ( "time" diff --git a/models/migrations/v1_17/v220.go b/models/migrations/v1_17/v220.go index bbceb933b3..904ddc5192 100644 --- a/models/migrations/v1_17/v220.go +++ b/models/migrations/v1_17/v220.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint import ( packages_model "code.gitea.io/gitea/models/packages" diff --git a/models/migrations/v1_17/v221.go b/models/migrations/v1_17/v221.go index 17744d53ab..8a58b0f105 100644 --- a/models/migrations/v1_17/v221.go +++ b/models/migrations/v1_17/v221.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint import ( "encoding/base32" diff --git a/models/migrations/v1_17/v221_test.go b/models/migrations/v1_17/v221_test.go index d635820f82..9ca54142e2 100644 --- a/models/migrations/v1_17/v221_test.go +++ b/models/migrations/v1_17/v221_test.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint import ( "encoding/base32" diff --git a/models/migrations/v1_17/v222.go b/models/migrations/v1_17/v222.go index 3aafb1848d..d1b77d845d 100644 --- a/models/migrations/v1_17/v222.go +++ b/models/migrations/v1_17/v222.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint import ( "context" diff --git a/models/migrations/v1_17/v223.go b/models/migrations/v1_17/v223.go index 530ddf0e05..a23d9916b3 100644 --- a/models/migrations/v1_17/v223.go +++ b/models/migrations/v1_17/v223.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_17 // nolint +package v1_17 //nolint import ( "context" diff --git a/models/migrations/v1_18/main_test.go b/models/migrations/v1_18/main_test.go index cb09340428..f71a21d1fb 100644 --- a/models/migrations/v1_18/main_test.go +++ b/models/migrations/v1_18/main_test.go @@ -1,8 +1,7 @@ // 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. +// SPDX-License-Identifier: MIT -package v1_18 // nolint +package v1_18 //nolint import ( "testing" diff --git a/models/migrations/v1_18/v224.go b/models/migrations/v1_18/v224.go index 34dbcc1aa1..afd34a5db0 100644 --- a/models/migrations/v1_18/v224.go +++ b/models/migrations/v1_18/v224.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_18 // nolint +package v1_18 //nolint import ( "xorm.io/xorm" diff --git a/models/migrations/v1_18/v225.go b/models/migrations/v1_18/v225.go index 8848a89825..786772c143 100644 --- a/models/migrations/v1_18/v225.go +++ b/models/migrations/v1_18/v225.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_18 // nolint +package v1_18 //nolint import ( "code.gitea.io/gitea/modules/setting" diff --git a/models/migrations/v1_18/v226.go b/models/migrations/v1_18/v226.go index bff88cbefa..f87e24b11d 100644 --- a/models/migrations/v1_18/v226.go +++ b/models/migrations/v1_18/v226.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_18 // nolint +package v1_18 //nolint import ( "xorm.io/builder" diff --git a/models/migrations/v1_18/v227.go b/models/migrations/v1_18/v227.go index 7dc468108c..c938028323 100644 --- a/models/migrations/v1_18/v227.go +++ b/models/migrations/v1_18/v227.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_18 // nolint +package v1_18 //nolint import ( "fmt" diff --git a/models/migrations/v1_18/v228.go b/models/migrations/v1_18/v228.go index 28ce171b53..58d3257528 100644 --- a/models/migrations/v1_18/v228.go +++ b/models/migrations/v1_18/v228.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_18 // nolint +package v1_18 //nolint import ( "code.gitea.io/gitea/modules/timeutil" diff --git a/models/migrations/v1_18/v229.go b/models/migrations/v1_18/v229.go index ea7c3ed329..10d9f35097 100644 --- a/models/migrations/v1_18/v229.go +++ b/models/migrations/v1_18/v229.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package v1_18 //nolint diff --git a/models/migrations/v1_18/v229_test.go b/models/migrations/v1_18/v229_test.go index caa24b26b8..d489328c00 100644 --- a/models/migrations/v1_18/v229_test.go +++ b/models/migrations/v1_18/v229_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package v1_18 //nolint diff --git a/models/migrations/v1_18/v230.go b/models/migrations/v1_18/v230.go index fe98e07a45..cf94926be1 100644 --- a/models/migrations/v1_18/v230.go +++ b/models/migrations/v1_18/v230.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_18 // nolint +package v1_18 //nolint import ( "xorm.io/xorm" diff --git a/models/migrations/v1_18/v230_test.go b/models/migrations/v1_18/v230_test.go index 0af13a1b9e..308f3a5023 100644 --- a/models/migrations/v1_18/v230_test.go +++ b/models/migrations/v1_18/v230_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package v1_18 //nolint diff --git a/models/migrations/v1_19/main_test.go b/models/migrations/v1_19/main_test.go new file mode 100644 index 0000000000..59f42af111 --- /dev/null +++ b/models/migrations/v1_19/main_test.go @@ -0,0 +1,14 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package v1_19 //nolint + +import ( + "testing" + + "code.gitea.io/gitea/models/migrations/base" +) + +func TestMain(m *testing.M) { + base.MainTest(m) +} diff --git a/models/migrations/v1_19/v231.go b/models/migrations/v1_19/v231.go index 809a1cfa57..79e46132f0 100644 --- a/models/migrations/v1_19/v231.go +++ b/models/migrations/v1_19/v231.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package v1_19 //nolint diff --git a/models/migrations/v1_19/v232.go b/models/migrations/v1_19/v232.go index 92c9ad84b7..89b595c543 100644 --- a/models/migrations/v1_19/v232.go +++ b/models/migrations/v1_19/v232.go @@ -1,8 +1,7 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT -package v1_19 // nolint +package v1_19 //nolint import ( "code.gitea.io/gitea/modules/setting" diff --git a/models/migrations/v1_19/v233.go b/models/migrations/v1_19/v233.go index 6443d58fbe..fe568b64eb 100644 --- a/models/migrations/v1_19/v233.go +++ b/models/migrations/v1_19/v233.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package v1_19 //nolint diff --git a/models/migrations/v1_19/v233_test.go b/models/migrations/v1_19/v233_test.go index f0a44df8cb..9902b7e4ae 100644 --- a/models/migrations/v1_19/v233_test.go +++ b/models/migrations/v1_19/v233_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package v1_19 //nolint @@ -16,7 +15,7 @@ import ( "github.com/stretchr/testify/assert" ) -func Test_addHeaderAuthorizationEncryptedColWebhook(t *testing.T) { +func Test_AddHeaderAuthorizationEncryptedColWebhook(t *testing.T) { // Create Webhook table type Webhook struct { ID int64 `xorm:"pk autoincr"` diff --git a/models/migrations/v1_19/v234.go b/models/migrations/v1_19/v234.go new file mode 100644 index 0000000000..4e98a2b7a9 --- /dev/null +++ b/models/migrations/v1_19/v234.go @@ -0,0 +1,28 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package v1_19 //nolint + +import ( + "code.gitea.io/gitea/modules/timeutil" + + "xorm.io/xorm" +) + +func CreatePackageCleanupRuleTable(x *xorm.Engine) error { + type PackageCleanupRule struct { + ID int64 `xorm:"pk autoincr"` + Enabled bool `xorm:"INDEX NOT NULL DEFAULT false"` + OwnerID int64 `xorm:"UNIQUE(s) INDEX NOT NULL DEFAULT 0"` + Type string `xorm:"UNIQUE(s) INDEX NOT NULL"` + KeepCount int `xorm:"NOT NULL DEFAULT 0"` + KeepPattern string `xorm:"NOT NULL DEFAULT ''"` + RemoveDays int `xorm:"NOT NULL DEFAULT 0"` + RemovePattern string `xorm:"NOT NULL DEFAULT ''"` + MatchFullName bool `xorm:"NOT NULL DEFAULT false"` + CreatedUnix timeutil.TimeStamp `xorm:"created NOT NULL DEFAULT 0"` + UpdatedUnix timeutil.TimeStamp `xorm:"updated NOT NULL DEFAULT 0"` + } + + return x.Sync2(new(PackageCleanupRule)) +} diff --git a/models/migrations/v1_19/v235.go b/models/migrations/v1_19/v235.go new file mode 100644 index 0000000000..3715de3920 --- /dev/null +++ b/models/migrations/v1_19/v235.go @@ -0,0 +1,16 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package v1_19 //nolint + +import ( + "xorm.io/xorm" +) + +func AddIndexForAccessToken(x *xorm.Engine) error { + type AccessToken struct { + TokenLastEight string `xorm:"INDEX token_last_eight"` + } + + return x.Sync(new(AccessToken)) +} diff --git a/models/migrations/v1_6/v70.go b/models/migrations/v1_6/v70.go index 880bcb8af7..fec88266ba 100644 --- a/models/migrations/v1_6/v70.go +++ b/models/migrations/v1_6/v70.go @@ -1,8 +1,7 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT -package v1_6 // nolint +package v1_6 //nolint import ( "fmt" diff --git a/models/migrations/v1_6/v71.go b/models/migrations/v1_6/v71.go index c021a24abc..effd2ebf99 100644 --- a/models/migrations/v1_6/v71.go +++ b/models/migrations/v1_6/v71.go @@ -1,8 +1,7 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT -package v1_6 // nolint +package v1_6 //nolint import ( "fmt" diff --git a/models/migrations/v1_6/v72.go b/models/migrations/v1_6/v72.go index 275512c4d0..ce963eb371 100644 --- a/models/migrations/v1_6/v72.go +++ b/models/migrations/v1_6/v72.go @@ -1,8 +1,7 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT -package v1_6 // nolint +package v1_6 //nolint import ( "fmt" diff --git a/models/migrations/v1_7/v73.go b/models/migrations/v1_7/v73.go index aa2cbba88a..1013daedbd 100644 --- a/models/migrations/v1_7/v73.go +++ b/models/migrations/v1_7/v73.go @@ -1,8 +1,7 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT -package v1_7 // nolint +package v1_7 //nolint import ( "xorm.io/xorm" diff --git a/models/migrations/v1_7/v74.go b/models/migrations/v1_7/v74.go index 3694d68d31..bdd89d1f34 100644 --- a/models/migrations/v1_7/v74.go +++ b/models/migrations/v1_7/v74.go @@ -1,8 +1,7 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT -package v1_7 // nolint +package v1_7 //nolint import "xorm.io/xorm" diff --git a/models/migrations/v1_7/v75.go b/models/migrations/v1_7/v75.go index df26667351..fa7430970c 100644 --- a/models/migrations/v1_7/v75.go +++ b/models/migrations/v1_7/v75.go @@ -1,8 +1,7 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT -package v1_7 // nolint +package v1_7 //nolint import ( "xorm.io/builder" diff --git a/models/migrations/v1_8/v76.go b/models/migrations/v1_8/v76.go index ef60eb7260..f35856cc60 100644 --- a/models/migrations/v1_8/v76.go +++ b/models/migrations/v1_8/v76.go @@ -1,8 +1,7 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT -package v1_8 // nolint +package v1_8 //nolint import ( "fmt" diff --git a/models/migrations/v1_8/v77.go b/models/migrations/v1_8/v77.go index 7d5dccc9b6..2305984c12 100644 --- a/models/migrations/v1_8/v77.go +++ b/models/migrations/v1_8/v77.go @@ -1,8 +1,7 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT -package v1_8 // nolint +package v1_8 //nolint import ( "xorm.io/xorm" diff --git a/models/migrations/v1_8/v78.go b/models/migrations/v1_8/v78.go index d7943fb0aa..637db451f5 100644 --- a/models/migrations/v1_8/v78.go +++ b/models/migrations/v1_8/v78.go @@ -1,8 +1,7 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT -package v1_8 // nolint +package v1_8 //nolint import ( "code.gitea.io/gitea/models/migrations/base" diff --git a/models/migrations/v1_8/v79.go b/models/migrations/v1_8/v79.go index 6a867f5055..e708d72294 100644 --- a/models/migrations/v1_8/v79.go +++ b/models/migrations/v1_8/v79.go @@ -1,8 +1,7 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT -package v1_8 // nolint +package v1_8 //nolint import ( "code.gitea.io/gitea/modules/setting" diff --git a/models/migrations/v1_8/v80.go b/models/migrations/v1_8/v80.go index 2e1b0631e1..7f2e0ff72b 100644 --- a/models/migrations/v1_8/v80.go +++ b/models/migrations/v1_8/v80.go @@ -1,8 +1,7 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT -package v1_8 // nolint +package v1_8 //nolint import "xorm.io/xorm" diff --git a/models/migrations/v1_8/v81.go b/models/migrations/v1_8/v81.go index b06f879ef5..a100dc1ef7 100644 --- a/models/migrations/v1_8/v81.go +++ b/models/migrations/v1_8/v81.go @@ -1,8 +1,7 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT -package v1_8 // nolint +package v1_8 //nolint import ( "fmt" diff --git a/models/migrations/v1_9/v82.go b/models/migrations/v1_9/v82.go index 82cb8b3ce1..26806dd645 100644 --- a/models/migrations/v1_9/v82.go +++ b/models/migrations/v1_9/v82.go @@ -1,8 +1,7 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT -package v1_9 // nolint +package v1_9 //nolint import ( "fmt" diff --git a/models/migrations/v1_9/v83.go b/models/migrations/v1_9/v83.go index 31cce268eb..afe504e9c5 100644 --- a/models/migrations/v1_9/v83.go +++ b/models/migrations/v1_9/v83.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_9 //nolint diff --git a/models/migrations/v1_9/v84.go b/models/migrations/v1_9/v84.go index 8aa7fbc07a..13fc238d48 100644 --- a/models/migrations/v1_9/v84.go +++ b/models/migrations/v1_9/v84.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_9 //nolint diff --git a/models/migrations/v1_9/v85.go b/models/migrations/v1_9/v85.go index 0cd32c3829..6cf7faaad6 100644 --- a/models/migrations/v1_9/v85.go +++ b/models/migrations/v1_9/v85.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_9 //nolint diff --git a/models/migrations/v1_9/v86.go b/models/migrations/v1_9/v86.go index 416e4fad93..a2a2c042c0 100644 --- a/models/migrations/v1_9/v86.go +++ b/models/migrations/v1_9/v86.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_9 //nolint diff --git a/models/migrations/v1_9/v87.go b/models/migrations/v1_9/v87.go index 97c8f621c6..b373a40bc0 100644 --- a/models/migrations/v1_9/v87.go +++ b/models/migrations/v1_9/v87.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package v1_9 //nolint diff --git a/models/org.go b/models/org.go index 150c41f55d..5f0e678ab4 100644 --- a/models/org.go +++ b/models/org.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package models @@ -44,7 +43,7 @@ func removeOrgUser(ctx context.Context, orgID, userID int64) error { return err } if t.NumMembers == 1 { - if err := t.GetMembersCtx(ctx); err != nil { + if err := t.LoadMembers(ctx); err != nil { return err } if t.Members[0].ID == userID { @@ -99,7 +98,7 @@ func removeOrgUser(ctx context.Context, orgID, userID int64) error { // RemoveOrgUser removes user from given organization. func RemoveOrgUser(orgID, userID int64) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/org_team.go b/models/org_team.go index 290b1c8b6a..a5a2575eec 100644 --- a/models/org_team.go +++ b/models/org_team.go @@ -1,7 +1,6 @@ // Copyright 2018 The Gitea Authors. All rights reserved. // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package models @@ -42,7 +41,7 @@ func AddRepository(ctx context.Context, t *organization.Team, repo *repo_model.R // Make all team members watch this repo if enabled in global settings if setting.Service.AutoWatchNewRepos { - if err = t.GetMembersCtx(ctx); err != nil { + if err = t.LoadMembers(ctx); err != nil { return fmt.Errorf("getMembers: %w", err) } for _, u := range t.Members { @@ -76,7 +75,7 @@ func addAllRepositories(ctx context.Context, t *organization.Team) error { // AddAllRepositories adds all repositories to the team func AddAllRepositories(t *organization.Team) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -95,7 +94,7 @@ func RemoveAllRepositories(t *organization.Team) (err error) { return nil } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -214,12 +213,12 @@ func RemoveRepository(t *organization.Team, repoID int64) error { return nil } - repo, err := repo_model.GetRepositoryByID(repoID) + repo, err := repo_model.GetRepositoryByID(db.DefaultContext, repoID) if err != nil { return err } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -263,7 +262,7 @@ func NewTeam(t *organization.Team) (err error) { return organization.ErrTeamAlreadyExist{OrgID: t.OrgID, Name: t.LowerName} } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -308,7 +307,7 @@ func UpdateTeam(t *organization.Team, authChanged, includeAllChanged bool) (err t.Description = t.Description[:255] } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -350,8 +349,8 @@ func UpdateTeam(t *organization.Team, authChanged, includeAllChanged bool) (err // Update access for team members if needed. if authChanged { - if err = t.GetRepositoriesCtx(ctx); err != nil { - return fmt.Errorf("getRepositories: %w", err) + if err = t.LoadRepositories(ctx); err != nil { + return fmt.Errorf("LoadRepositories: %w", err) } for _, repo := range t.Repos { @@ -375,18 +374,18 @@ func UpdateTeam(t *organization.Team, authChanged, includeAllChanged bool) (err // DeleteTeam deletes given team. // It's caller's responsibility to assign organization ID. func DeleteTeam(t *organization.Team) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } defer committer.Close() sess := db.GetEngine(ctx) - if err := t.GetRepositoriesCtx(ctx); err != nil { + if err := t.LoadRepositories(ctx); err != nil { return err } - if err := t.GetMembersCtx(ctx); err != nil { + if err := t.LoadMembers(ctx); err != nil { return err } @@ -460,7 +459,7 @@ func AddTeamMember(team *organization.Team, userID int64) error { return err } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -517,10 +516,16 @@ func AddTeamMember(team *organization.Team, userID int64) error { } } - // watch could be failed, so run it in a goroutine + if err := committer.Commit(); err != nil { + return err + } + committer.Close() + + // this behaviour may spend much time so run it in a goroutine + // FIXME: Update watch repos batchly if setting.Service.AutoWatchNewRepos { // Get team and its repositories. - if err := team.GetRepositoriesCtx(db.DefaultContext); err != nil { + if err := team.LoadRepositories(db.DefaultContext); err != nil { log.Error("getRepositories failed: %v", err) } go func(repos []*repo_model.Repository) { @@ -532,7 +537,7 @@ func AddTeamMember(team *organization.Team, userID int64) error { }(team.Repos) } - return committer.Commit() + return nil } func removeTeamMember(ctx context.Context, team *organization.Team, userID int64) error { @@ -549,7 +554,7 @@ func removeTeamMember(ctx context.Context, team *organization.Team, userID int64 team.NumMembers-- - if err := team.GetRepositoriesCtx(ctx); err != nil { + if err := team.LoadRepositories(ctx); err != nil { return err } @@ -598,7 +603,7 @@ func removeTeamMember(ctx context.Context, team *organization.Team, userID int64 // RemoveTeamMember removes member from given team of given organization. func RemoveTeamMember(team *organization.Team, userID int64) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/org_team_test.go b/models/org_team_test.go index a600d07c0c..446084c815 100644 --- a/models/org_team_test.go +++ b/models/org_team_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package models @@ -143,7 +142,7 @@ func TestDeleteTeam(t *testing.T) { // check that team members don't have "leftover" access to repos user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) - accessMode, err := access_model.AccessLevel(user, repo) + accessMode, err := access_model.AccessLevel(db.DefaultContext, user, repo) assert.NoError(t, err) assert.True(t, accessMode < perm.AccessModeWrite) } diff --git a/models/org_test.go b/models/org_test.go index 23b417119e..54e8f08465 100644 --- a/models/org_test.go +++ b/models/org_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package models diff --git a/models/organization/main_test.go b/models/organization/main_test.go index 376552cb22..7ccf8c8efd 100644 --- a/models/organization/main_test.go +++ b/models/organization/main_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package organization_test diff --git a/models/organization/mini_org.go b/models/organization/mini_org.go index 36cf948e65..b1627b5e6c 100644 --- a/models/organization/mini_org.go +++ b/models/organization/mini_org.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package organization diff --git a/models/organization/org.go b/models/organization/org.go index 993ca3f10d..b3d77b4ec6 100644 --- a/models/organization/org.go +++ b/models/organization/org.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package organization @@ -107,7 +106,7 @@ func (org *Organization) IsOrgMember(uid int64) (bool, error) { // CanCreateOrgRepo returns true if given user can create repo in organization func (org *Organization) CanCreateOrgRepo(uid int64) (bool, error) { - return CanCreateOrgRepo(org.ID, uid) + return CanCreateOrgRepo(db.DefaultContext, org.ID, uid) } func (org *Organization) getTeam(ctx context.Context, name string) (*Team, error) { @@ -277,7 +276,7 @@ func CreateOrganization(org *Organization, owner *user_model.User) (err error) { org.NumMembers = 1 org.Type = user_model.UserTypeOrganization - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -458,8 +457,9 @@ func CountOrgs(opts FindOrgOptions) (int64, error) { // HasOrgOrUserVisible tells if the given user can see the given org or user func HasOrgOrUserVisible(ctx context.Context, orgOrUser, user *user_model.User) bool { - // Not SignedUser - if user == nil { + // If user is nil, it's an anonymous user/request. + // The Ghost user is handled like an anonymous user. + if user == nil || user.IsGhost() { return orgOrUser.Visibility == structs.VisibleTypePublic } @@ -564,7 +564,7 @@ func AddOrgUser(orgID, uid int64) error { return err } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -701,7 +701,7 @@ func AccessibleReposEnv(ctx context.Context, org *Organization, userID int64) (A var user *user_model.User if userID > 0 { - u, err := user_model.GetUserByIDCtx(ctx, userID) + u, err := user_model.GetUserByID(ctx, userID) if err != nil { return nil, err } diff --git a/models/organization/org_repo.go b/models/organization/org_repo.go index 364374f71b..99638916b0 100644 --- a/models/organization/org_repo.go +++ b/models/organization/org_repo.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package organization diff --git a/models/organization/org_test.go b/models/organization/org_test.go index 0fba6e2592..2f821e3a4c 100644 --- a/models/organization/org_test.go +++ b/models/organization/org_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package organization_test diff --git a/models/organization/org_user.go b/models/organization/org_user.go index 7a5d17a75a..e5cbfe6c0f 100644 --- a/models/organization/org_user.go +++ b/models/organization/org_user.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package organization @@ -74,8 +73,8 @@ func IsPublicMembership(orgID, uid int64) (bool, error) { } // CanCreateOrgRepo returns true if user can create repo in organization -func CanCreateOrgRepo(orgID, uid int64) (bool, error) { - return db.GetEngine(db.DefaultContext). +func CanCreateOrgRepo(ctx context.Context, orgID, uid int64) (bool, error) { + return db.GetEngine(ctx). Where(builder.Eq{"team.can_create_org_repo": true}). Join("INNER", "team_user", "team_user.team_id = team.id"). And("team_user.uid = ?", uid). diff --git a/models/organization/org_user_test.go b/models/organization/org_user_test.go index aed3ea23cf..edd0aa3ea0 100644 --- a/models/organization/org_user_test.go +++ b/models/organization/org_user_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package organization_test @@ -38,7 +37,7 @@ func TestUserIsPublicMember(t *testing.T) { } func testUserIsPublicMember(t *testing.T, uid, orgID int64, expected bool) { - user, err := user_model.GetUserByID(uid) + user, err := user_model.GetUserByID(db.DefaultContext, uid) assert.NoError(t, err) is, err := organization.IsPublicMembership(orgID, user.ID) assert.NoError(t, err) @@ -66,7 +65,7 @@ func TestIsUserOrgOwner(t *testing.T) { } func testIsUserOrgOwner(t *testing.T, uid, orgID int64, expected bool) { - user, err := user_model.GetUserByID(uid) + user, err := user_model.GetUserByID(db.DefaultContext, uid) assert.NoError(t, err) is, err := organization.IsOrganizationOwner(db.DefaultContext, orgID, user.ID) assert.NoError(t, err) diff --git a/models/organization/team.go b/models/organization/team.go index aa9b24b57f..55d3f17276 100644 --- a/models/organization/team.go +++ b/models/organization/team.go @@ -1,7 +1,6 @@ // Copyright 2018 The Gitea Authors. All rights reserved. // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package organization @@ -223,8 +222,8 @@ func (t *Team) IsMember(userID int64) bool { return isMember } -// GetRepositoriesCtx returns paginated repositories in team of organization. -func (t *Team) GetRepositoriesCtx(ctx context.Context) (err error) { +// LoadRepositories returns paginated repositories in team of organization. +func (t *Team) LoadRepositories(ctx context.Context) (err error) { if t.Repos != nil { return nil } @@ -234,8 +233,8 @@ func (t *Team) GetRepositoriesCtx(ctx context.Context) (err error) { return err } -// GetMembersCtx returns paginated members in team of organization. -func (t *Team) GetMembersCtx(ctx context.Context) (err error) { +// LoadMembers returns paginated members in team of organization. +func (t *Team) LoadMembers(ctx context.Context) (err error) { t.Members, err = GetTeamMembers(ctx, &SearchMembersOptions{ TeamID: t.ID, }) @@ -243,18 +242,12 @@ func (t *Team) GetMembersCtx(ctx context.Context) (err error) { } // UnitEnabled returns if the team has the given unit type enabled -func (t *Team) UnitEnabled(tp unit.Type) bool { - return t.UnitAccessMode(tp) > perm.AccessModeNone +func (t *Team) UnitEnabled(ctx context.Context, tp unit.Type) bool { + return t.UnitAccessMode(ctx, tp) > perm.AccessModeNone } // UnitAccessMode returns if the team has the given unit type enabled -// it is called in templates, should not be replaced by `UnitAccessModeCtx(ctx ...)` -func (t *Team) UnitAccessMode(tp unit.Type) perm.AccessMode { - return t.UnitAccessModeCtx(db.DefaultContext, tp) -} - -// UnitAccessModeCtx returns if the team has the given unit type enabled -func (t *Team) UnitAccessModeCtx(ctx context.Context, tp unit.Type) perm.AccessMode { +func (t *Team) UnitAccessMode(ctx context.Context, tp unit.Type) perm.AccessMode { if err := t.getUnits(ctx); err != nil { log.Warn("Error loading team (ID: %d) units: %s", t.ID, err.Error()) } diff --git a/models/organization/team_invite.go b/models/organization/team_invite.go index 4504a2e9fe..17f6c59610 100644 --- a/models/organization/team_invite.go +++ b/models/organization/team_invite.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package organization diff --git a/models/organization/team_invite_test.go b/models/organization/team_invite_test.go index e0596ec28d..cd6e1fe2ef 100644 --- a/models/organization/team_invite_test.go +++ b/models/organization/team_invite_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package organization_test diff --git a/models/organization/team_repo.go b/models/organization/team_repo.go index 3ac4fa926b..e6b50ecff7 100644 --- a/models/organization/team_repo.go +++ b/models/organization/team_repo.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package organization diff --git a/models/organization/team_test.go b/models/organization/team_test.go index c8d58a0eb7..c63b83aab7 100644 --- a/models/organization/team_test.go +++ b/models/organization/team_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package organization_test @@ -43,7 +42,7 @@ func TestTeam_GetRepositories(t *testing.T) { test := func(teamID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, team.GetRepositoriesCtx(db.DefaultContext)) + assert.NoError(t, team.LoadRepositories(db.DefaultContext)) assert.Len(t, team.Repos, team.NumRepos) for _, repo := range team.Repos { unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repo.ID}) @@ -58,7 +57,7 @@ func TestTeam_GetMembers(t *testing.T) { test := func(teamID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, team.GetMembersCtx(db.DefaultContext)) + assert.NoError(t, team.LoadMembers(db.DefaultContext)) assert.Len(t, team.Members, team.NumMembers) for _, member := range team.Members { unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: member.ID, TeamID: teamID}) diff --git a/models/organization/team_unit.go b/models/organization/team_unit.go index a712ddb2eb..7668ca7483 100644 --- a/models/organization/team_unit.go +++ b/models/organization/team_unit.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package organization @@ -32,7 +31,7 @@ func getUnitsByTeamID(ctx context.Context, teamID int64) (units []*TeamUnit, err // UpdateTeamUnits updates a teams's units func UpdateTeamUnits(team *Team, units []TeamUnit) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/organization/team_user.go b/models/organization/team_user.go index 80f4d00e3d..7a024f1c6d 100644 --- a/models/organization/team_user.go +++ b/models/organization/team_user.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package organization diff --git a/models/packages/conan/references.go b/models/packages/conan/references.go index e47e689af7..06e828e8fa 100644 --- a/models/packages/conan/references.go +++ b/models/packages/conan/references.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package conan diff --git a/models/packages/conan/search.go b/models/packages/conan/search.go index 39a9000459..ab0bff5968 100644 --- a/models/packages/conan/search.go +++ b/models/packages/conan/search.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package conan diff --git a/models/packages/container/const.go b/models/packages/container/const.go index 9d3ed64a6e..0dfbda051d 100644 --- a/models/packages/container/const.go +++ b/models/packages/container/const.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package container diff --git a/models/packages/container/search.go b/models/packages/container/search.go index e4a5a53848..dfd5e244ba 100644 --- a/models/packages/container/search.go +++ b/models/packages/container/search.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package container diff --git a/models/packages/descriptor.go b/models/packages/descriptor.go index 357574a706..34f1cad87d 100644 --- a/models/packages/descriptor.go +++ b/models/packages/descriptor.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package packages @@ -86,15 +85,15 @@ func GetPackageDescriptor(ctx context.Context, pv *PackageVersion) (*PackageDesc if err != nil { return nil, err } - o, err := user_model.GetUserByIDCtx(ctx, p.OwnerID) + o, err := user_model.GetUserByID(ctx, p.OwnerID) if err != nil { return nil, err } - repository, err := repo_model.GetRepositoryByIDCtx(ctx, p.RepoID) + repository, err := repo_model.GetRepositoryByID(ctx, p.RepoID) if err != nil && !repo_model.IsErrRepoNotExist(err) { return nil, err } - creator, err := user_model.GetUserByIDCtx(ctx, pv.CreatorID) + creator, err := user_model.GetUserByID(ctx, pv.CreatorID) if err != nil { return nil, err } diff --git a/models/packages/package.go b/models/packages/package.go index e39a7c4e41..5c4837d98b 100644 --- a/models/packages/package.go +++ b/models/packages/package.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package packages @@ -45,6 +44,21 @@ const ( TypeVagrant Type = "vagrant" ) +var TypeList = []Type{ + TypeComposer, + TypeConan, + TypeContainer, + TypeGeneric, + TypeHelm, + TypeMaven, + TypeNpm, + TypeNuGet, + TypePub, + TypePyPI, + TypeRubyGems, + TypeVagrant, +} + // Name gets the name of the package type func (pt Type) Name() string { switch pt { diff --git a/models/packages/package_blob.go b/models/packages/package_blob.go index 8c701d4285..36ad745312 100644 --- a/models/packages/package_blob.go +++ b/models/packages/package_blob.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package packages @@ -62,6 +61,13 @@ func GetBlobByID(ctx context.Context, blobID int64) (*PackageBlob, error) { return pb, nil } +// ExistPackageBlobWithSHA returns if a package blob exists with the provided sha +func ExistPackageBlobWithSHA(ctx context.Context, blobSha256 string) (bool, error) { + return db.GetEngine(ctx).Exist(&PackageBlob{ + HashSHA256: blobSha256, + }) +} + // FindExpiredUnreferencedBlobs gets all blobs without associated files older than the specific duration func FindExpiredUnreferencedBlobs(ctx context.Context, olderThan time.Duration) ([]*PackageBlob, error) { pbs := make([]*PackageBlob, 0, 10) diff --git a/models/packages/package_blob_upload.go b/models/packages/package_blob_upload.go index 635068f1d8..64d1f9d473 100644 --- a/models/packages/package_blob_upload.go +++ b/models/packages/package_blob_upload.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package packages diff --git a/models/packages/package_cleanup_rule.go b/models/packages/package_cleanup_rule.go new file mode 100644 index 0000000000..9bd512755d --- /dev/null +++ b/models/packages/package_cleanup_rule.go @@ -0,0 +1,109 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package packages + +import ( + "context" + "errors" + "fmt" + "regexp" + + "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/modules/timeutil" + + "xorm.io/builder" +) + +var ErrPackageCleanupRuleNotExist = errors.New("Package blob does not exist") + +func init() { + db.RegisterModel(new(PackageCleanupRule)) +} + +// PackageCleanupRule represents a rule which describes when to clean up package versions +type PackageCleanupRule struct { + ID int64 `xorm:"pk autoincr"` + Enabled bool `xorm:"INDEX NOT NULL DEFAULT false"` + OwnerID int64 `xorm:"UNIQUE(s) INDEX NOT NULL DEFAULT 0"` + Type Type `xorm:"UNIQUE(s) INDEX NOT NULL"` + KeepCount int `xorm:"NOT NULL DEFAULT 0"` + KeepPattern string `xorm:"NOT NULL DEFAULT ''"` + KeepPatternMatcher *regexp.Regexp `xorm:"-"` + RemoveDays int `xorm:"NOT NULL DEFAULT 0"` + RemovePattern string `xorm:"NOT NULL DEFAULT ''"` + RemovePatternMatcher *regexp.Regexp `xorm:"-"` + MatchFullName bool `xorm:"NOT NULL DEFAULT false"` + CreatedUnix timeutil.TimeStamp `xorm:"created NOT NULL DEFAULT 0"` + UpdatedUnix timeutil.TimeStamp `xorm:"updated NOT NULL DEFAULT 0"` +} + +func (pcr *PackageCleanupRule) CompiledPattern() error { + if pcr.KeepPatternMatcher != nil || pcr.RemovePatternMatcher != nil { + return nil + } + + if pcr.KeepPattern != "" { + var err error + pcr.KeepPatternMatcher, err = regexp.Compile(fmt.Sprintf(`(?i)\A%s\z`, pcr.KeepPattern)) + if err != nil { + return err + } + } + + if pcr.RemovePattern != "" { + var err error + pcr.RemovePatternMatcher, err = regexp.Compile(fmt.Sprintf(`(?i)\A%s\z`, pcr.RemovePattern)) + if err != nil { + return err + } + } + + return nil +} + +func InsertCleanupRule(ctx context.Context, pcr *PackageCleanupRule) (*PackageCleanupRule, error) { + return pcr, db.Insert(ctx, pcr) +} + +func GetCleanupRuleByID(ctx context.Context, id int64) (*PackageCleanupRule, error) { + pcr := &PackageCleanupRule{} + + has, err := db.GetEngine(ctx).ID(id).Get(pcr) + if err != nil { + return nil, err + } + if !has { + return nil, ErrPackageCleanupRuleNotExist + } + return pcr, nil +} + +func UpdateCleanupRule(ctx context.Context, pcr *PackageCleanupRule) error { + _, err := db.GetEngine(ctx).ID(pcr.ID).AllCols().Update(pcr) + return err +} + +func GetCleanupRulesByOwner(ctx context.Context, ownerID int64) ([]*PackageCleanupRule, error) { + pcrs := make([]*PackageCleanupRule, 0, 10) + return pcrs, db.GetEngine(ctx).Where("owner_id = ?", ownerID).Find(&pcrs) +} + +func DeleteCleanupRuleByID(ctx context.Context, ruleID int64) error { + _, err := db.GetEngine(ctx).ID(ruleID).Delete(&PackageCleanupRule{}) + return err +} + +func HasOwnerCleanupRuleForPackageType(ctx context.Context, ownerID int64, packageType Type) (bool, error) { + return db.GetEngine(ctx). + Where("owner_id = ? AND type = ?", ownerID, packageType). + Exist(&PackageCleanupRule{}) +} + +func IterateEnabledCleanupRules(ctx context.Context, callback func(context.Context, *PackageCleanupRule) error) error { + return db.Iterate( + ctx, + builder.Eq{"enabled": true}, + callback, + ) +} diff --git a/models/packages/package_file.go b/models/packages/package_file.go index 8f304ce8ac..6d0fd185a0 100644 --- a/models/packages/package_file.go +++ b/models/packages/package_file.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package packages @@ -199,3 +198,13 @@ func SearchFiles(ctx context.Context, opts *PackageFileSearchOptions) ([]*Packag count, err := sess.FindAndCount(&pfs) return pfs, count, err } + +// CalculateBlobSize sums up all blob sizes matching the search options. +// It does NOT respect the deduplication of blobs. +func CalculateBlobSize(ctx context.Context, opts *PackageFileSearchOptions) (int64, error) { + return db.GetEngine(ctx). + Table("package_file"). + Where(opts.toConds()). + Join("INNER", "package_blob", "package_blob.id = package_file.blob_id"). + SumInt(new(PackageBlob), "size") +} diff --git a/models/packages/package_property.go b/models/packages/package_property.go index fc10713801..1b7f253d56 100644 --- a/models/packages/package_property.go +++ b/models/packages/package_property.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package packages diff --git a/models/packages/package_test.go b/models/packages/package_test.go index 915ef15f91..735688a731 100644 --- a/models/packages/package_test.go +++ b/models/packages/package_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package packages_test diff --git a/models/packages/package_version.go b/models/packages/package_version.go index 782261c575..928f9d47d6 100644 --- a/models/packages/package_version.go +++ b/models/packages/package_version.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package packages @@ -303,9 +302,14 @@ func SearchLatestVersions(ctx context.Context, opts *PackageSearchOptions) ([]*P cond := opts.toConds(). And(builder.Expr("pv2.id IS NULL")) + joinCond := builder.Expr("package_version.package_id = pv2.package_id AND (package_version.created_unix < pv2.created_unix OR (package_version.created_unix = pv2.created_unix AND package_version.id < pv2.id))") + if !opts.IsInternal.IsNone() { + joinCond = joinCond.And(builder.Eq{"pv2.is_internal": opts.IsInternal.IsTrue()}) + } + sess := db.GetEngine(ctx). Table("package_version"). - Join("LEFT", "package_version pv2", "package_version.package_id = pv2.package_id AND (package_version.created_unix < pv2.created_unix OR (package_version.created_unix = pv2.created_unix AND package_version.id < pv2.id))"). + Join("LEFT", "package_version pv2", joinCond). Join("INNER", "package", "package.id = package_version.package_id"). Where(cond) @@ -319,3 +323,21 @@ func SearchLatestVersions(ctx context.Context, opts *PackageSearchOptions) ([]*P count, err := sess.FindAndCount(&pvs) return pvs, count, err } + +// ExistVersion checks if a version matching the search options exist +func ExistVersion(ctx context.Context, opts *PackageSearchOptions) (bool, error) { + return db.GetEngine(ctx). + Where(opts.toConds()). + Table("package_version"). + Join("INNER", "package", "package.id = package_version.package_id"). + Exist(new(PackageVersion)) +} + +// CountVersions counts all versions of packages matching the search options +func CountVersions(ctx context.Context, opts *PackageSearchOptions) (int64, error) { + return db.GetEngine(ctx). + Where(opts.toConds()). + Table("package_version"). + Join("INNER", "package", "package.id = package_version.package_id"). + Count(new(PackageVersion)) +} diff --git a/models/perm/access/access.go b/models/perm/access/access.go index 7344e114a6..48ecf78a8c 100644 --- a/models/perm/access/access.go +++ b/models/perm/access/access.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package access @@ -172,7 +171,7 @@ func RecalculateTeamAccesses(ctx context.Context, repo *repo_model.Repository, i continue } - if err = t.GetMembersCtx(ctx); err != nil { + if err = t.LoadMembers(ctx); err != nil { return fmt.Errorf("getMembers '%d': %w", t.ID, err) } for _, m := range t.Members { diff --git a/models/perm/access/access_test.go b/models/perm/access/access_test.go index 7f58be4f39..bd828a1e9d 100644 --- a/models/perm/access/access_test.go +++ b/models/perm/access/access_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package access_test @@ -36,34 +35,34 @@ func TestAccessLevel(t *testing.T) { // org. owned private repo repo24 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 24}) - level, err := access_model.AccessLevel(user2, repo1) + level, err := access_model.AccessLevel(db.DefaultContext, user2, repo1) assert.NoError(t, err) assert.Equal(t, perm_model.AccessModeOwner, level) - level, err = access_model.AccessLevel(user2, repo3) + level, err = access_model.AccessLevel(db.DefaultContext, user2, repo3) assert.NoError(t, err) assert.Equal(t, perm_model.AccessModeOwner, level) - level, err = access_model.AccessLevel(user5, repo1) + level, err = access_model.AccessLevel(db.DefaultContext, user5, repo1) assert.NoError(t, err) assert.Equal(t, perm_model.AccessModeRead, level) - level, err = access_model.AccessLevel(user5, repo3) + level, err = access_model.AccessLevel(db.DefaultContext, user5, repo3) assert.NoError(t, err) assert.Equal(t, perm_model.AccessModeNone, level) // restricted user has no access to a public repo - level, err = access_model.AccessLevel(user29, repo1) + level, err = access_model.AccessLevel(db.DefaultContext, user29, repo1) assert.NoError(t, err) assert.Equal(t, perm_model.AccessModeNone, level) // ... unless he's a collaborator - level, err = access_model.AccessLevel(user29, repo4) + level, err = access_model.AccessLevel(db.DefaultContext, user29, repo4) assert.NoError(t, err) assert.Equal(t, perm_model.AccessModeWrite, level) // ... or a team member - level, err = access_model.AccessLevel(user29, repo24) + level, err = access_model.AccessLevel(db.DefaultContext, user29, repo24) assert.NoError(t, err) assert.Equal(t, perm_model.AccessModeRead, level) } diff --git a/models/perm/access/main_test.go b/models/perm/access/main_test.go index eb0abb74d1..837a9db437 100644 --- a/models/perm/access/main_test.go +++ b/models/perm/access/main_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package access_test diff --git a/models/perm/access/repo_permission.go b/models/perm/access/repo_permission.go index 93e3bdd6d8..a6bf9b6744 100644 --- a/models/perm/access/repo_permission.go +++ b/models/perm/access/repo_permission.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package access @@ -245,7 +244,7 @@ func GetUserRepoPermission(ctx context.Context, repo *repo_model.Repository, use for _, u := range repo.Units { var found bool for _, team := range teams { - teamMode := team.UnitAccessModeCtx(ctx, u.Type) + teamMode := team.UnitAccessMode(ctx, u.Type) if teamMode > perm_model.AccessModeNone { m := perm.UnitsMode[u.Type] if m < teamMode { @@ -326,17 +325,13 @@ func IsUserRepoAdmin(ctx context.Context, repo *repo_model.Repository, user *use // AccessLevel returns the Access a user has to a repository. Will return NoneAccess if the // user does not have access. -func AccessLevel(user *user_model.User, repo *repo_model.Repository) (perm_model.AccessMode, error) { //nolint - return AccessLevelUnit(user, repo, unit.TypeCode) +func AccessLevel(ctx context.Context, user *user_model.User, repo *repo_model.Repository) (perm_model.AccessMode, error) { //nolint + return AccessLevelUnit(ctx, user, repo, unit.TypeCode) } // AccessLevelUnit returns the Access a user has to a repository's. Will return NoneAccess if the // user does not have access. -func AccessLevelUnit(user *user_model.User, repo *repo_model.Repository, unitType unit.Type) (perm_model.AccessMode, error) { //nolint - return accessLevelUnit(db.DefaultContext, user, repo, unitType) -} - -func accessLevelUnit(ctx context.Context, user *user_model.User, repo *repo_model.Repository, unitType unit.Type) (perm_model.AccessMode, error) { +func AccessLevelUnit(ctx context.Context, user *user_model.User, repo *repo_model.Repository, unitType unit.Type) (perm_model.AccessMode, error) { //nolint perm, err := GetUserRepoPermission(ctx, repo, user) if err != nil { return perm_model.AccessModeNone, err @@ -346,7 +341,7 @@ func accessLevelUnit(ctx context.Context, user *user_model.User, repo *repo_mode // HasAccessUnit returns true if user has testMode to the unit of the repository func HasAccessUnit(ctx context.Context, user *user_model.User, repo *repo_model.Repository, unitType unit.Type, testMode perm_model.AccessMode) (bool, error) { - mode, err := accessLevelUnit(ctx, user, repo, unitType) + mode, err := AccessLevelUnit(ctx, user, repo, unitType) return testMode <= mode, err } @@ -369,7 +364,7 @@ func HasAccess(ctx context.Context, userID int64, repo *repo_model.Repository) ( var user *user_model.User var err error if userID > 0 { - user, err = user_model.GetUserByIDCtx(ctx, userID) + user, err = user_model.GetUserByID(ctx, userID) if err != nil { return false, err } diff --git a/models/perm/access_mode.go b/models/perm/access_mode.go index dfa7f7b752..c482e296bc 100644 --- a/models/perm/access_mode.go +++ b/models/perm/access_mode.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package perm diff --git a/models/project/board.go b/models/project/board.go index be7119ee4d..d8468f0cb5 100644 --- a/models/project/board.go +++ b/models/project/board.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package project @@ -133,7 +132,7 @@ func NewBoard(board *Board) error { // DeleteBoardByID removes all issues references to the project board. func DeleteBoardByID(boardID int64) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/project/issue.go b/models/project/issue.go index 59af7063a5..3269197d6c 100644 --- a/models/project/issue.go +++ b/models/project/issue.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package project @@ -78,7 +77,7 @@ func (p *Project) NumOpenIssues() int { // MoveIssuesOnProjectBoard moves or keeps issues in a column and sorts them inside that column func MoveIssuesOnProjectBoard(board *Board, sortedIssueIDs map[int64]int64) error { - return db.WithTx(func(ctx context.Context) error { + return db.WithTx(db.DefaultContext, func(ctx context.Context) error { sess := db.GetEngine(ctx) issueIDs := make([]int64, 0, len(sortedIssueIDs)) diff --git a/models/project/main_test.go b/models/project/main_test.go index 2e97b3a5ef..816cbeb94a 100644 --- a/models/project/main_test.go +++ b/models/project/main_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package project diff --git a/models/project/project.go b/models/project/project.go index ccdf5342d4..bcf1166408 100644 --- a/models/project/project.go +++ b/models/project/project.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package project @@ -180,7 +179,7 @@ func NewProject(p *Project) error { return errors.New("project type is not valid") } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -248,7 +247,7 @@ func updateRepositoryProjectCount(ctx context.Context, repoID int64) error { // ChangeProjectStatusByRepoIDAndID toggles a project between opened and closed func ChangeProjectStatusByRepoIDAndID(repoID, projectID int64, isClosed bool) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -272,7 +271,7 @@ func ChangeProjectStatusByRepoIDAndID(repoID, projectID int64, isClosed bool) er // ChangeProjectStatus toggle a project between opened and closed func ChangeProjectStatus(p *Project, isClosed bool) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -299,47 +298,35 @@ func changeProjectStatus(ctx context.Context, p *Project, isClosed bool) error { return updateRepositoryProjectCount(ctx, p.RepoID) } -// DeleteProjectByID deletes a project from a repository. -func DeleteProjectByID(id int64) error { - ctx, committer, err := db.TxContext() - if err != nil { - return err - } - defer committer.Close() - - if err := DeleteProjectByIDCtx(ctx, id); err != nil { - return err - } - - return committer.Commit() -} - -// DeleteProjectByIDCtx deletes a project from a repository. -func DeleteProjectByIDCtx(ctx context.Context, id int64) error { - p, err := GetProjectByID(ctx, id) - if err != nil { - if IsErrProjectNotExist(err) { - return nil +// DeleteProjectByID deletes a project from a repository. if it's not in a database +// transaction, it will start a new database transaction +func DeleteProjectByID(ctx context.Context, id int64) error { + return db.AutoTx(ctx, func(ctx context.Context) error { + p, err := GetProjectByID(ctx, id) + if err != nil { + if IsErrProjectNotExist(err) { + return nil + } + return err } - return err - } - if err := deleteProjectIssuesByProjectID(ctx, id); err != nil { - return err - } + if err := deleteProjectIssuesByProjectID(ctx, id); err != nil { + return err + } - if err := deleteBoardByProjectID(ctx, id); err != nil { - return err - } + if err := deleteBoardByProjectID(ctx, id); err != nil { + return err + } - if _, err = db.GetEngine(ctx).ID(p.ID).Delete(new(Project)); err != nil { - return err - } + if _, err = db.GetEngine(ctx).ID(p.ID).Delete(new(Project)); err != nil { + return err + } - return updateRepositoryProjectCount(ctx, p.RepoID) + return updateRepositoryProjectCount(ctx, p.RepoID) + }) } -func DeleteProjectByRepoIDCtx(ctx context.Context, repoID int64) error { +func DeleteProjectByRepoID(ctx context.Context, repoID int64) error { switch { case setting.Database.UseSQLite3: if _, err := db.GetEngine(ctx).Exec("DELETE FROM project_issue WHERE project_issue.id IN (SELECT project_issue.id FROM project_issue INNER JOIN project WHERE project.id = project_issue.project_id AND project.repo_id = ?)", repoID); err != nil { diff --git a/models/project/project_test.go b/models/project/project_test.go index f33fb3351a..4fde0fc7ce 100644 --- a/models/project/project_test.go +++ b/models/project/project_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package project diff --git a/models/pull/automerge.go b/models/pull/automerge.go index 16ab5af093..f68fb7c681 100644 --- a/models/pull/automerge.go +++ b/models/pull/automerge.go @@ -1,6 +1,5 @@ // Copyright 2022 Gitea. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package pull @@ -75,7 +74,7 @@ func GetScheduledMergeByPullID(ctx context.Context, pullID int64) (bool, *AutoMe return false, nil, err } - doer, err := user_model.GetUserByIDCtx(ctx, scheduledPRM.DoerID) + doer, err := user_model.GetUserByID(ctx, scheduledPRM.DoerID) if err != nil { return false, nil, err } diff --git a/models/pull/review_state.go b/models/pull/review_state.go index 1c465bf766..1a2b1e165f 100644 --- a/models/pull/review_state.go +++ b/models/pull/review_state.go @@ -1,6 +1,6 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT + package pull import ( diff --git a/models/repo.go b/models/repo.go index 569dafee5f..9af600c9ba 100644 --- a/models/repo.go +++ b/models/repo.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2017 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. +// SPDX-License-Identifier: MIT package models @@ -45,7 +44,7 @@ func Init() error { // DeleteRepository deletes a repository for a user or organization. // make sure if you call this func to close open sessions (sqlite will otherwise get a deadlock) func DeleteRepository(doer *user_model.User, uid, repoID int64) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -53,7 +52,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error { sess := db.GetEngine(ctx) // In case is a organization. - org, err := user_model.GetUserByIDCtx(ctx, uid) + org, err := user_model.GetUserByID(ctx, uid) if err != nil { return err } @@ -192,7 +191,7 @@ func DeleteRepository(doer *user_model.User, uid, repoID int64) error { } } - if err := project_model.DeleteProjectByRepoIDCtx(ctx, repoID); err != nil { + if err := project_model.DeleteProjectByRepoID(ctx, repoID); err != nil { return fmt.Errorf("unable to delete projects for repo[%d]: %w", repoID, err) } @@ -444,7 +443,7 @@ func CheckRepoStats(ctx context.Context) error { }, // Repository.NumIssues { - statsQuery("SELECT repo.id FROM `repository` repo WHERE repo.num_issues!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", false, false), + statsQuery("SELECT repo.id FROM `repository` repo WHERE repo.num_issues!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_pull=?)", false), repoStatsCorrectNumIssues, "repository count 'num_issues'", }, @@ -456,7 +455,7 @@ func CheckRepoStats(ctx context.Context) error { }, // Repository.NumPulls { - statsQuery("SELECT repo.id FROM `repository` repo WHERE repo.num_pulls!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_closed=? AND is_pull=?)", false, true), + statsQuery("SELECT repo.id FROM `repository` repo WHERE repo.num_pulls!=(SELECT COUNT(*) FROM `issue` WHERE repo_id=repo.id AND is_pull=?)", true), repoStatsCorrectNumPulls, "repository count 'num_pulls'", }, @@ -524,7 +523,7 @@ func CheckRepoStats(ctx context.Context) error { } log.Trace("Updating repository count 'num_forks': %d", id) - repo, err := repo_model.GetRepositoryByID(id) + repo, err := repo_model.GetRepositoryByID(ctx, id) if err != nil { log.Error("repo_model.GetRepositoryByID[%d]: %v", id, err) continue @@ -569,7 +568,7 @@ func UpdateRepoStats(ctx context.Context, id int64) error { } func updateUserStarNumbers(users []user_model.User) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -619,7 +618,7 @@ func DeleteDeployKey(ctx context.Context, doer *user_model.User, id int64) error // Check if user has access to delete this key. if !doer.IsAdmin { - repo, err := repo_model.GetRepositoryByIDCtx(ctx, key.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, key.RepoID) if err != nil { return fmt.Errorf("GetRepositoryByID: %w", err) } diff --git a/models/repo/archiver.go b/models/repo/archiver.go index 003911943f..11ecaff34c 100644 --- a/models/repo/archiver.go +++ b/models/repo/archiver.go @@ -1,17 +1,19 @@ // 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. +// SPDX-License-Identifier: MIT package repo import ( "context" "fmt" + "strconv" + "strings" "time" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/timeutil" + "code.gitea.io/gitea/modules/util" "xorm.io/builder" ) @@ -44,6 +46,28 @@ func (archiver *RepoArchiver) RelativePath() string { return fmt.Sprintf("%d/%s/%s.%s", archiver.RepoID, archiver.CommitID[:2], archiver.CommitID, archiver.Type.String()) } +// repoArchiverForRelativePath takes a relativePath created from (archiver *RepoArchiver) RelativePath() and creates a shell repoArchiver struct representing it +func repoArchiverForRelativePath(relativePath string) (*RepoArchiver, error) { + parts := strings.SplitN(relativePath, "/", 3) + if len(parts) != 3 { + return nil, util.SilentWrap{Message: fmt.Sprintf("invalid storage path: %s", relativePath), Err: util.ErrInvalidArgument} + } + repoID, err := strconv.ParseInt(parts[0], 10, 64) + if err != nil { + return nil, util.SilentWrap{Message: fmt.Sprintf("invalid storage path: %s", relativePath), Err: util.ErrInvalidArgument} + } + nameExts := strings.SplitN(parts[2], ".", 2) + if len(nameExts) != 2 { + return nil, util.SilentWrap{Message: fmt.Sprintf("invalid storage path: %s", relativePath), Err: util.ErrInvalidArgument} + } + + return &RepoArchiver{ + RepoID: repoID, + CommitID: parts[1] + nameExts[0], + Type: git.ToArchiveType(nameExts[1]), + }, nil +} + var delRepoArchiver = new(RepoArchiver) // DeleteRepoArchiver delete archiver @@ -65,6 +89,17 @@ func GetRepoArchiver(ctx context.Context, repoID int64, tp git.ArchiveType, comm return nil, nil } +// ExistsRepoArchiverWithStoragePath checks if there is a RepoArchiver for a given storage path +func ExistsRepoArchiverWithStoragePath(ctx context.Context, storagePath string) (bool, error) { + // We need to invert the path provided func (archiver *RepoArchiver) RelativePath() above + archiver, err := repoArchiverForRelativePath(storagePath) + if err != nil { + return false, err + } + + return db.GetEngine(ctx).Exist(archiver) +} + // AddRepoArchiver adds an archiver func AddRepoArchiver(ctx context.Context, archiver *RepoArchiver) error { _, err := db.GetEngine(ctx).Insert(archiver) diff --git a/models/repo/attachment.go b/models/repo/attachment.go index 180d7730ba..8fbf79a7a0 100644 --- a/models/repo/attachment.go +++ b/models/repo/attachment.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo @@ -122,9 +121,9 @@ func GetAttachmentsByUUIDs(ctx context.Context, uuids []string) ([]*Attachment, return attachments, db.GetEngine(ctx).In("uuid", uuids).Find(&attachments) } -// ExistAttachmentsByUUID returns true if attachment is exist by given UUID -func ExistAttachmentsByUUID(uuid string) (bool, error) { - return db.GetEngine(db.DefaultContext).Where("`uuid`=?", uuid).Exist(new(Attachment)) +// ExistAttachmentsByUUID returns true if attachment exists with the given UUID +func ExistAttachmentsByUUID(ctx context.Context, uuid string) (bool, error) { + return db.GetEngine(ctx).Where("`uuid`=?", uuid).Exist(new(Attachment)) } // GetAttachmentsByIssueID returns all attachments of an issue. @@ -226,20 +225,20 @@ func UpdateAttachment(ctx context.Context, atta *Attachment) error { } // DeleteAttachmentsByRelease deletes all attachments associated with the given release. -func DeleteAttachmentsByRelease(releaseID int64) error { - _, err := db.GetEngine(db.DefaultContext).Where("release_id = ?", releaseID).Delete(&Attachment{}) +func DeleteAttachmentsByRelease(ctx context.Context, releaseID int64) error { + _, err := db.GetEngine(ctx).Where("release_id = ?", releaseID).Delete(&Attachment{}) return err } // CountOrphanedAttachments returns the number of bad attachments -func CountOrphanedAttachments() (int64, error) { - return db.GetEngine(db.DefaultContext).Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))"). +func CountOrphanedAttachments(ctx context.Context) (int64, error) { + return db.GetEngine(ctx).Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))"). Count(new(Attachment)) } // DeleteOrphanedAttachments delete all bad attachments -func DeleteOrphanedAttachments() error { - _, err := db.GetEngine(db.DefaultContext).Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))"). +func DeleteOrphanedAttachments(ctx context.Context) error { + _, err := db.GetEngine(ctx).Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))"). Delete(new(Attachment)) return err } diff --git a/models/repo/attachment_test.go b/models/repo/attachment_test.go index d7c2f529db..21fba227a5 100644 --- a/models/repo/attachment_test.go +++ b/models/repo/attachment_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo_test diff --git a/models/repo/avatar.go b/models/repo/avatar.go index 1bc37598fe..9ec01bc04b 100644 --- a/models/repo/avatar.go +++ b/models/repo/avatar.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo @@ -24,6 +23,13 @@ func (repo *Repository) CustomAvatarRelativePath() string { return repo.Avatar } +// ExistsWithAvatarAtStoragePath returns true if there is a user with this Avatar +func ExistsWithAvatarAtStoragePath(ctx context.Context, storagePath string) (bool, error) { + // See func (repo *Repository) CustomAvatarRelativePath() + // repo.Avatar is used directly as the storage path - therefore we can check for existence directly using the path + return db.GetEngine(ctx).Where("`avatar`=?", storagePath).Exist(new(Repository)) +} + // RelAvatarLink returns a relative link to the repository's avatar. func (repo *Repository) RelAvatarLink() string { return repo.relAvatarLink(db.DefaultContext) diff --git a/models/repo/collaboration.go b/models/repo/collaboration.go index 0aaa749210..29bcab70f3 100644 --- a/models/repo/collaboration.go +++ b/models/repo/collaboration.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package repo @@ -45,7 +44,7 @@ func GetCollaborators(ctx context.Context, repoID int64, listOptions db.ListOpti collaborators := make([]*Collaborator, 0, len(collaborations)) for _, c := range collaborations { - user, err := user_model.GetUserByIDCtx(ctx, c.UserID) + user, err := user_model.GetUserByID(ctx, c.UserID) if err != nil { if user_model.IsErrUserNotExist(err) { log.Warn("Inconsistent DB: User: %d is listed as collaborator of %-v but does not exist", c.UserID, repoID) @@ -100,55 +99,42 @@ func getCollaborations(ctx context.Context, repoID int64, listOptions db.ListOpt } // ChangeCollaborationAccessMode sets new access mode for the collaboration. -func ChangeCollaborationAccessModeCtx(ctx context.Context, repo *Repository, uid int64, mode perm.AccessMode) error { +func ChangeCollaborationAccessMode(ctx context.Context, repo *Repository, uid int64, mode perm.AccessMode) error { // Discard invalid input if mode <= perm.AccessModeNone || mode > perm.AccessModeOwner { return nil } - e := db.GetEngine(ctx) + return db.AutoTx(ctx, func(ctx context.Context) error { + e := db.GetEngine(ctx) + + collaboration := &Collaboration{ + RepoID: repo.ID, + UserID: uid, + } + has, err := e.Get(collaboration) + if err != nil { + return fmt.Errorf("get collaboration: %w", err) + } else if !has { + return nil + } + + if collaboration.Mode == mode { + return nil + } + collaboration.Mode = mode + + if _, err = e. + ID(collaboration.ID). + Cols("mode"). + Update(collaboration); err != nil { + return fmt.Errorf("update collaboration: %w", err) + } else if _, err = e.Exec("UPDATE access SET mode = ? WHERE user_id = ? AND repo_id = ?", mode, uid, repo.ID); err != nil { + return fmt.Errorf("update access table: %w", err) + } - collaboration := &Collaboration{ - RepoID: repo.ID, - UserID: uid, - } - has, err := e.Get(collaboration) - if err != nil { - return fmt.Errorf("get collaboration: %w", err) - } else if !has { return nil - } - - if collaboration.Mode == mode { - return nil - } - collaboration.Mode = mode - - if _, err = e. - ID(collaboration.ID). - Cols("mode"). - Update(collaboration); err != nil { - return fmt.Errorf("update collaboration: %w", err) - } else if _, err = e.Exec("UPDATE access SET mode = ? WHERE user_id = ? AND repo_id = ?", mode, uid, repo.ID); err != nil { - return fmt.Errorf("update access table: %w", err) - } - - return nil -} - -// ChangeCollaborationAccessMode sets new access mode for the collaboration. -func ChangeCollaborationAccessMode(repo *Repository, uid int64, mode perm.AccessMode) error { - ctx, committer, err := db.TxContext() - if err != nil { - return err - } - defer committer.Close() - - if err := ChangeCollaborationAccessModeCtx(ctx, repo, uid, mode); err != nil { - return err - } - - return committer.Commit() + }) } // IsOwnerMemberCollaborator checks if a provided user is the owner, a collaborator or a member of a team in a repository diff --git a/models/repo/collaboration_test.go b/models/repo/collaboration_test.go index cbf46dd286..0a6444de85 100644 --- a/models/repo/collaboration_test.go +++ b/models/repo/collaboration_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package repo_test @@ -55,7 +54,7 @@ func TestRepository_ChangeCollaborationAccessMode(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) - assert.NoError(t, repo_model.ChangeCollaborationAccessMode(repo, 4, perm.AccessModeAdmin)) + assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, 4, perm.AccessModeAdmin)) collaboration := unittest.AssertExistsAndLoadBean(t, &repo_model.Collaboration{RepoID: repo.ID, UserID: 4}) assert.EqualValues(t, perm.AccessModeAdmin, collaboration.Mode) @@ -63,9 +62,9 @@ func TestRepository_ChangeCollaborationAccessMode(t *testing.T) { access := unittest.AssertExistsAndLoadBean(t, &access_model.Access{UserID: 4, RepoID: repo.ID}) assert.EqualValues(t, perm.AccessModeAdmin, access.Mode) - assert.NoError(t, repo_model.ChangeCollaborationAccessMode(repo, 4, perm.AccessModeAdmin)) + assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, 4, perm.AccessModeAdmin)) - assert.NoError(t, repo_model.ChangeCollaborationAccessMode(repo, unittest.NonexistentID, perm.AccessModeAdmin)) + assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, unittest.NonexistentID, perm.AccessModeAdmin)) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repo.ID}) } diff --git a/models/repo/fork.go b/models/repo/fork.go index b54c61c425..eafbab0fb1 100644 --- a/models/repo/fork.go +++ b/models/repo/fork.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo diff --git a/models/repo/fork_test.go b/models/repo/fork_test.go index 9e08d8136e..e8dca204cc 100644 --- a/models/repo/fork_test.go +++ b/models/repo/fork_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo_test @@ -18,14 +17,14 @@ func TestGetUserFork(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // User13 has repo 11 forked from repo10 - repo, err := repo_model.GetRepositoryByID(10) + repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 10) assert.NoError(t, err) assert.NotNil(t, repo) repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13) assert.NoError(t, err) assert.NotNil(t, repo) - repo, err = repo_model.GetRepositoryByID(9) + repo, err = repo_model.GetRepositoryByID(db.DefaultContext, 9) assert.NoError(t, err) assert.NotNil(t, repo) repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13) diff --git a/models/repo/git.go b/models/repo/git.go index 509020565a..7ae88058dc 100644 --- a/models/repo/git.go +++ b/models/repo/git.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo diff --git a/models/repo/issue.go b/models/repo/issue.go index 9f0fa3bad9..6f6b565a00 100644 --- a/models/repo/issue.go +++ b/models/repo/issue.go @@ -1,13 +1,11 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo import ( "context" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" @@ -27,44 +25,34 @@ func (repo *Repository) CanEnableTimetracker() bool { } // IsTimetrackerEnabled returns whether or not the timetracker is enabled. It returns the default value from config if an error occurs. -func (repo *Repository) IsTimetrackerEnabled() bool { - return repo.IsTimetrackerEnabledCtx(db.DefaultContext) -} - -// IsTimetrackerEnabledCtx returns whether or not the timetracker is enabled. It returns the default value from config if an error occurs. -func (repo *Repository) IsTimetrackerEnabledCtx(ctx context.Context) bool { +func (repo *Repository) IsTimetrackerEnabled(ctx context.Context) bool { if !setting.Service.EnableTimetracking { return false } var u *RepoUnit var err error - if u, err = repo.GetUnitCtx(ctx, unit.TypeIssues); err != nil { + if u, err = repo.GetUnit(ctx, unit.TypeIssues); err != nil { return setting.Service.DefaultEnableTimetracking } return u.IssuesConfig().EnableTimetracker } // AllowOnlyContributorsToTrackTime returns value of IssuesConfig or the default value -func (repo *Repository) AllowOnlyContributorsToTrackTime() bool { +func (repo *Repository) AllowOnlyContributorsToTrackTime(ctx context.Context) bool { var u *RepoUnit var err error - if u, err = repo.GetUnit(unit.TypeIssues); err != nil { + if u, err = repo.GetUnit(ctx, unit.TypeIssues); err != nil { return setting.Service.DefaultAllowOnlyContributorsToTrackTime } return u.IssuesConfig().AllowOnlyContributorsToTrackTime } // IsDependenciesEnabled returns if dependencies are enabled and returns the default setting if not set. -func (repo *Repository) IsDependenciesEnabled() bool { - return repo.IsDependenciesEnabledCtx(db.DefaultContext) -} - -// IsDependenciesEnabledCtx returns if dependencies are enabled and returns the default setting if not set. -func (repo *Repository) IsDependenciesEnabledCtx(ctx context.Context) bool { +func (repo *Repository) IsDependenciesEnabled(ctx context.Context) bool { var u *RepoUnit var err error - if u, err = repo.GetUnitCtx(ctx, unit.TypeIssues); err != nil { + if u, err = repo.GetUnit(ctx, unit.TypeIssues); err != nil { log.Trace("%s", err) return setting.Service.DefaultEnableDependencies } diff --git a/models/repo/language_stats.go b/models/repo/language_stats.go index b047046aeb..2da16814bd 100644 --- a/models/repo/language_stats.go +++ b/models/repo/language_stats.go @@ -1,12 +1,12 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo import ( "context" "math" + "sort" "strings" "code.gitea.io/gitea/models/db" @@ -44,7 +44,7 @@ func (stats LanguageStatList) LoadAttributes() { func (stats LanguageStatList) getLanguagePercentages() map[string]float32 { langPerc := make(map[string]float32) - var otherPerc float32 = 100 + var otherPerc float32 var total int64 for _, stat := range stats { @@ -52,21 +52,52 @@ func (stats LanguageStatList) getLanguagePercentages() map[string]float32 { } if total > 0 { for _, stat := range stats { - perc := float32(math.Round(float64(stat.Size)/float64(total)*1000) / 10) + perc := float32(float64(stat.Size) / float64(total) * 100) if perc <= 0.1 { + otherPerc += perc continue } - otherPerc -= perc langPerc[stat.Language] = perc } - otherPerc = float32(math.Round(float64(otherPerc)*10) / 10) } if otherPerc > 0 { langPerc["other"] = otherPerc } + roundByLargestRemainder(langPerc, 100) return langPerc } +// Rounds to 1 decimal point, target should be the expected sum of percs +func roundByLargestRemainder(percs map[string]float32, target float32) { + leftToDistribute := int(target * 10) + + keys := make([]string, 0, len(percs)) + + for k, v := range percs { + percs[k] = v * 10 + floored := math.Floor(float64(percs[k])) + leftToDistribute -= int(floored) + keys = append(keys, k) + } + + // Sort the keys by the largest remainder + sort.SliceStable(keys, func(i, j int) bool { + _, remainderI := math.Modf(float64(percs[keys[i]])) + _, remainderJ := math.Modf(float64(percs[keys[j]])) + return remainderI > remainderJ + }) + + // Increment the values in order of largest remainder + for _, k := range keys { + percs[k] = float32(math.Floor(float64(percs[k]))) + if leftToDistribute > 0 { + percs[k]++ + leftToDistribute-- + } + percs[k] /= 10 + } +} + // GetLanguageStats returns the language statistics for a repository func GetLanguageStats(ctx context.Context, repo *Repository) (LanguageStatList, error) { stats := make(LanguageStatList, 0, 6) @@ -110,7 +141,7 @@ func GetTopLanguageStats(repo *Repository, limit int) (LanguageStatList, error) // UpdateLanguageStats updates the language statistics for repository func UpdateLanguageStats(repo *Repository, commitID string, stats map[string]int64) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -182,7 +213,7 @@ func UpdateLanguageStats(repo *Repository, commitID string, stats map[string]int // CopyLanguageStat Copy originalRepo language stat information to destRepo (use for forked repo) func CopyLanguageStat(originalRepo, destRepo *Repository) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/repo/main_test.go b/models/repo/main_test.go index f6d704ca65..bb9be54b9c 100644 --- a/models/repo/main_test.go +++ b/models/repo/main_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo_test diff --git a/models/repo/mirror.go b/models/repo/mirror.go index 297ffd594a..2f59b85331 100644 --- a/models/repo/mirror.go +++ b/models/repo/mirror.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo @@ -53,7 +52,7 @@ func (m *Mirror) GetRepository() *Repository { return m.Repo } var err error - m.Repo, err = GetRepositoryByIDCtx(db.DefaultContext, m.RepoID) + m.Repo, err = GetRepositoryByID(db.DefaultContext, m.RepoID) if err != nil { log.Error("getRepositoryByID[%d]: %v", m.ID, err) } diff --git a/models/repo/pushmirror.go b/models/repo/pushmirror.go index 38d6e72019..f79ce59ee2 100644 --- a/models/repo/pushmirror.go +++ b/models/repo/pushmirror.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo @@ -62,7 +61,7 @@ func (m *PushMirror) GetRepository() *Repository { return m.Repo } var err error - m.Repo, err = GetRepositoryByIDCtx(db.DefaultContext, m.RepoID) + m.Repo, err = GetRepositoryByID(db.DefaultContext, m.RepoID) if err != nil { log.Error("getRepositoryByID[%d]: %v", m.ID, err) } @@ -120,9 +119,9 @@ func GetPushMirrorsByRepoID(ctx context.Context, repoID int64, listOptions db.Li } // GetPushMirrorsSyncedOnCommit returns push-mirrors for this repo that should be updated by new commits -func GetPushMirrorsSyncedOnCommit(repoID int64) ([]*PushMirror, error) { +func GetPushMirrorsSyncedOnCommit(ctx context.Context, repoID int64) ([]*PushMirror, error) { mirrors := make([]*PushMirror, 0, 10) - return mirrors, db.GetEngine(db.DefaultContext). + return mirrors, db.GetEngine(ctx). Where("repo_id=? AND sync_on_commit=?", repoID, true). Find(&mirrors) } diff --git a/models/repo/pushmirror_test.go b/models/repo/pushmirror_test.go index 5087e30095..2b3c5be292 100644 --- a/models/repo/pushmirror_test.go +++ b/models/repo/pushmirror_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo_test diff --git a/models/repo/redirect.go b/models/repo/redirect.go index f28220c2af..92a011a453 100644 --- a/models/repo/redirect.go +++ b/models/repo/redirect.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/models/repo/redirect_test.go b/models/repo/redirect_test.go index 90114667e5..8255704d59 100644 --- a/models/repo/redirect_test.go +++ b/models/repo/redirect_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo_test diff --git a/models/repo/release.go b/models/repo/release.go index 14428f15f7..25eba10e05 100644 --- a/models/repo/release.go +++ b/models/repo/release.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo @@ -90,16 +89,17 @@ func init() { db.RegisterModel(new(Release)) } -func (r *Release) loadAttributes(ctx context.Context) error { +// LoadAttributes load repo and publisher attributes for a release +func (r *Release) LoadAttributes(ctx context.Context) error { var err error if r.Repo == nil { - r.Repo, err = GetRepositoryByIDCtx(ctx, r.RepoID) + r.Repo, err = GetRepositoryByID(ctx, r.RepoID) if err != nil { return err } } if r.Publisher == nil { - r.Publisher, err = user_model.GetUserByIDCtx(ctx, r.PublisherID) + r.Publisher, err = user_model.GetUserByID(ctx, r.PublisherID) if err != nil { if user_model.IsErrUserNotExist(err) { r.Publisher = user_model.NewGhostUser() @@ -111,11 +111,6 @@ func (r *Release) loadAttributes(ctx context.Context) error { return GetReleaseAttachments(ctx, r) } -// LoadAttributes load repo and publisher attributes for a release -func (r *Release) LoadAttributes() error { - return r.loadAttributes(db.DefaultContext) -} - // APIURL the api url for a release. release must have attributes loaded func (r *Release) APIURL() string { return r.Repo.APIURL() + "/releases/" + strconv.FormatInt(r.ID, 10) @@ -241,8 +236,8 @@ func (opts *FindReleasesOptions) toConds(repoID int64) builder.Cond { } // GetReleasesByRepoID returns a list of releases of repository. -func GetReleasesByRepoID(repoID int64, opts FindReleasesOptions) ([]*Release, error) { - sess := db.GetEngine(db.DefaultContext). +func GetReleasesByRepoID(ctx context.Context, repoID int64, opts FindReleasesOptions) ([]*Release, error) { + sess := db.GetEngine(ctx). Desc("created_unix", "id"). Where(opts.toConds(repoID)) @@ -291,8 +286,8 @@ func GetReleasesByRepoIDAndNames(ctx context.Context, repoID int64, tagNames []s } // GetReleaseCountByRepoID returns the count of releases of repository -func GetReleaseCountByRepoID(repoID int64, opts FindReleasesOptions) (int64, error) { - return db.GetEngine(db.DefaultContext).Where(opts.toConds(repoID)).Count(&Release{}) +func GetReleaseCountByRepoID(ctx context.Context, repoID int64, opts FindReleasesOptions) (int64, error) { + return db.GetEngine(ctx).Where(opts.toConds(repoID)).Count(&Release{}) } type releaseMetaSearch struct { @@ -381,8 +376,8 @@ func SortReleases(rels []*Release) { } // DeleteReleaseByID deletes a release from database by given ID. -func DeleteReleaseByID(id int64) error { - _, err := db.GetEngine(db.DefaultContext).ID(id).Delete(new(Release)) +func DeleteReleaseByID(ctx context.Context, id int64) error { + _, err := db.GetEngine(ctx).ID(id).Delete(new(Release)) return err } diff --git a/models/repo/repo.go b/models/repo/repo.go index 2bb9d0cc44..10c4b90bf0 100644 --- a/models/repo/repo.go +++ b/models/repo/repo.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo @@ -236,14 +235,6 @@ func (repo *Repository) AfterLoad() { repo.NumOpenProjects = repo.NumProjects - repo.NumClosedProjects } -// MustOwner always returns a valid *user_model.User object to avoid -// conceptually impossible error handling. -// It creates a fake object that contains error details -// when error occurs. -func (repo *Repository) MustOwner() *user_model.User { - return repo.mustOwner(db.DefaultContext) -} - // LoadAttributes loads attributes of the repository. func (repo *Repository) LoadAttributes(ctx context.Context) error { // Load owner @@ -324,12 +315,7 @@ func (repo *Repository) LoadUnits(ctx context.Context) (err error) { } // UnitEnabled if this repository has the given unit enabled -func (repo *Repository) UnitEnabled(tp unit.Type) (result bool) { - return repo.UnitEnabledCtx(db.DefaultContext, tp) -} - -// UnitEnabled if this repository has the given unit enabled -func (repo *Repository) UnitEnabledCtx(ctx context.Context, tp unit.Type) bool { +func (repo *Repository) UnitEnabled(ctx context.Context, tp unit.Type) bool { if err := repo.LoadUnits(ctx); err != nil { log.Warn("Error loading repository (ID: %d) units: %s", repo.ID, err.Error()) } @@ -342,8 +328,8 @@ func (repo *Repository) UnitEnabledCtx(ctx context.Context, tp unit.Type) bool { } // MustGetUnit always returns a RepoUnit object -func (repo *Repository) MustGetUnit(tp unit.Type) *RepoUnit { - ru, err := repo.GetUnit(tp) +func (repo *Repository) MustGetUnit(ctx context.Context, tp unit.Type) *RepoUnit { + ru, err := repo.GetUnit(ctx, tp) if err == nil { return ru } @@ -376,12 +362,7 @@ func (repo *Repository) MustGetUnit(tp unit.Type) *RepoUnit { } // GetUnit returns a RepoUnit object -func (repo *Repository) GetUnit(tp unit.Type) (*RepoUnit, error) { - return repo.GetUnitCtx(db.DefaultContext, tp) -} - -// GetUnitCtx returns a RepoUnit object -func (repo *Repository) GetUnitCtx(ctx context.Context, tp unit.Type) (*RepoUnit, error) { +func (repo *Repository) GetUnit(ctx context.Context, tp unit.Type) (*RepoUnit, error) { if err := repo.LoadUnits(ctx); err != nil { return nil, err } @@ -399,11 +380,15 @@ func (repo *Repository) GetOwner(ctx context.Context) (err error) { return nil } - repo.Owner, err = user_model.GetUserByIDCtx(ctx, repo.OwnerID) + repo.Owner, err = user_model.GetUserByID(ctx, repo.OwnerID) return err } -func (repo *Repository) mustOwner(ctx context.Context) *user_model.User { +// MustOwner always returns a valid *user_model.User object to avoid +// conceptually impossible error handling. +// It creates a fake object that contains error details +// when error occurs. +func (repo *Repository) MustOwner(ctx context.Context) *user_model.User { if err := repo.GetOwner(ctx); err != nil { return &user_model.User{ Name: "error", @@ -424,7 +409,7 @@ func (repo *Repository) ComposeMetas() map[string]string { "mode": "comment", } - unit, err := repo.GetUnit(unit.TypeExternalTracker) + unit, err := repo.GetUnit(db.DefaultContext, unit.TypeExternalTracker) if err == nil { metas["format"] = unit.ExternalTrackerConfig().ExternalTrackerFormat switch unit.ExternalTrackerConfig().ExternalTrackerStyle { @@ -438,7 +423,7 @@ func (repo *Repository) ComposeMetas() map[string]string { } } - repo.MustOwner() + repo.MustOwner(db.DefaultContext) if repo.Owner.IsOrganization() { teams := make([]string, 0, 5) _ = db.GetEngine(db.DefaultContext).Table("team_repo"). @@ -472,16 +457,12 @@ func (repo *Repository) ComposeDocumentMetas() map[string]string { // GetBaseRepo populates repo.BaseRepo for a fork repository and // returns an error on failure (NOTE: no error is returned for // non-fork repositories, and BaseRepo will be left untouched) -func (repo *Repository) GetBaseRepo() (err error) { - return repo.getBaseRepo(db.DefaultContext) -} - -func (repo *Repository) getBaseRepo(ctx context.Context) (err error) { +func (repo *Repository) GetBaseRepo(ctx context.Context) (err error) { if !repo.IsFork { return nil } - repo.BaseRepo, err = GetRepositoryByIDCtx(ctx, repo.ForkID) + repo.BaseRepo, err = GetRepositoryByID(ctx, repo.ForkID) return err } @@ -527,7 +508,7 @@ func (repo *Repository) CanEnablePulls() bool { // AllowsPulls returns true if repository meets the requirements of accepting pulls and has them enabled. func (repo *Repository) AllowsPulls() bool { - return repo.CanEnablePulls() && repo.UnitEnabled(unit.TypePullRequests) + return repo.CanEnablePulls() && repo.UnitEnabled(db.DefaultContext, unit.TypePullRequests) } // CanEnableEditor returns true if repository meets the requirements of web editor. @@ -616,11 +597,6 @@ func (repo *Repository) GetTrustModel() TrustModelType { return trustModel } -// GetRepositoryByOwnerAndName returns the repository by given ownername and reponame. -func GetRepositoryByOwnerAndName(ownerName, repoName string) (*Repository, error) { - return GetRepositoryByOwnerAndNameCtx(db.DefaultContext, ownerName, repoName) -} - // __________ .__ __ // \______ \ ____ ______ ____ _____|__|/ |_ ___________ ___.__. // | _// __ \\____ \ / _ \/ ___/ \ __\/ _ \_ __ < | | @@ -652,8 +628,8 @@ func (err ErrRepoNotExist) Unwrap() error { return util.ErrNotExist } -// GetRepositoryByOwnerAndNameCtx returns the repository by given owner name and repo name -func GetRepositoryByOwnerAndNameCtx(ctx context.Context, ownerName, repoName string) (*Repository, error) { +// GetRepositoryByOwnerAndName returns the repository by given owner name and repo name +func GetRepositoryByOwnerAndName(ctx context.Context, ownerName, repoName string) (*Repository, error) { var repo Repository has, err := db.GetEngine(ctx).Table("repository").Select("repository.*"). Join("INNER", "`user`", "`user`.id = repository.owner_id"). @@ -683,8 +659,8 @@ func GetRepositoryByName(ownerID int64, name string) (*Repository, error) { return repo, err } -// GetRepositoryByIDCtx returns the repository by given id if exists. -func GetRepositoryByIDCtx(ctx context.Context, id int64) (*Repository, error) { +// GetRepositoryByID returns the repository by given id if exists. +func GetRepositoryByID(ctx context.Context, id int64) (*Repository, error) { repo := new(Repository) has, err := db.GetEngine(ctx).ID(id).Get(repo) if err != nil { @@ -695,11 +671,6 @@ func GetRepositoryByIDCtx(ctx context.Context, id int64) (*Repository, error) { return repo, nil } -// GetRepositoryByID returns the repository by given id if exists. -func GetRepositoryByID(id int64) (*Repository, error) { - return GetRepositoryByIDCtx(db.DefaultContext, id) -} - // GetRepositoriesMapByIDs returns the repositories by given id slice. func GetRepositoriesMapByIDs(ids []int64) (map[int64]*Repository, error) { repos := make(map[int64]*Repository, len(ids)) @@ -727,7 +698,7 @@ func GetTemplateRepo(ctx context.Context, repo *Repository) (*Repository, error) return nil, nil } - return GetRepositoryByIDCtx(ctx, repo.TemplateID) + return GetRepositoryByID(ctx, repo.TemplateID) } // TemplateRepo returns the repository, which is template of this repository @@ -792,13 +763,13 @@ func UpdateRepoIssueNumbers(ctx context.Context, repoID int64, isPull, isClosed } // CountNullArchivedRepository counts the number of repositories with is_archived is null -func CountNullArchivedRepository() (int64, error) { - return db.GetEngine(db.DefaultContext).Where(builder.IsNull{"is_archived"}).Count(new(Repository)) +func CountNullArchivedRepository(ctx context.Context) (int64, error) { + return db.GetEngine(ctx).Where(builder.IsNull{"is_archived"}).Count(new(Repository)) } // FixNullArchivedRepository sets is_archived to false where it is null -func FixNullArchivedRepository() (int64, error) { - return db.GetEngine(db.DefaultContext).Where(builder.IsNull{"is_archived"}).Cols("is_archived").NoAutoTime().Update(&Repository{ +func FixNullArchivedRepository(ctx context.Context) (int64, error) { + return db.GetEngine(ctx).Where(builder.IsNull{"is_archived"}).Cols("is_archived").NoAutoTime().Update(&Repository{ IsArchived: false, }) } diff --git a/models/repo/repo_indexer.go b/models/repo/repo_indexer.go index 67ba3382dc..9667c56244 100644 --- a/models/repo/repo_indexer.go +++ b/models/repo/repo_indexer.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/models/repo/repo_list.go b/models/repo/repo_list.go index 191970d275..6d9dd9ec65 100644 --- a/models/repo/repo_list.go +++ b/models/repo/repo_list.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo @@ -518,14 +517,13 @@ func SearchRepositoryCondition(opts *SearchRepoOptions) builder.Cond { // SearchRepository returns repositories based on search options, // it returns results in given range and number of total results. -func SearchRepository(opts *SearchRepoOptions) (RepositoryList, int64, error) { +func SearchRepository(ctx context.Context, opts *SearchRepoOptions) (RepositoryList, int64, error) { cond := SearchRepositoryCondition(opts) - return SearchRepositoryByCondition(opts, cond, true) + return SearchRepositoryByCondition(ctx, opts, cond, true) } // SearchRepositoryByCondition search repositories by condition -func SearchRepositoryByCondition(opts *SearchRepoOptions, cond builder.Cond, loadAttributes bool) (RepositoryList, int64, error) { - ctx := db.DefaultContext +func SearchRepositoryByCondition(ctx context.Context, opts *SearchRepoOptions, cond builder.Cond, loadAttributes bool) (RepositoryList, int64, error) { sess, count, err := searchRepositoryByCondition(ctx, opts, cond) if err != nil { return nil, 0, err @@ -652,9 +650,9 @@ func AccessibleRepositoryCondition(user *user_model.User, unitType unit.Type) bu // SearchRepositoryByName takes keyword and part of repository name to search, // it returns results in given range and number of total results. -func SearchRepositoryByName(opts *SearchRepoOptions) (RepositoryList, int64, error) { +func SearchRepositoryByName(ctx context.Context, opts *SearchRepoOptions) (RepositoryList, int64, error) { opts.IncludeDescription = false - return SearchRepository(opts) + return SearchRepository(ctx, opts) } // SearchRepositoryIDs takes keyword and part of repository name to search, diff --git a/models/repo/repo_list_test.go b/models/repo/repo_list_test.go index f9c84a0f3f..d87d70c189 100644 --- a/models/repo/repo_list_test.go +++ b/models/repo/repo_list_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo_test @@ -20,7 +19,7 @@ func TestSearchRepository(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // test search public repository on explore page - repos, count, err := repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{ + repos, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{ Page: 1, PageSize: 10, @@ -35,7 +34,7 @@ func TestSearchRepository(t *testing.T) { } assert.Equal(t, int64(1), count) - repos, count, err = repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{ + repos, count, err = repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{ Page: 1, PageSize: 10, @@ -49,7 +48,7 @@ func TestSearchRepository(t *testing.T) { assert.Len(t, repos, 2) // test search private repository on explore page - repos, count, err = repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{ + repos, count, err = repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{ Page: 1, PageSize: 10, @@ -65,7 +64,7 @@ func TestSearchRepository(t *testing.T) { } assert.Equal(t, int64(1), count) - repos, count, err = repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{ + repos, count, err = repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{ Page: 1, PageSize: 10, @@ -80,14 +79,14 @@ func TestSearchRepository(t *testing.T) { assert.Len(t, repos, 3) // Test non existing owner - repos, count, err = repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{OwnerID: unittest.NonexistentID}) + repos, count, err = repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{OwnerID: unittest.NonexistentID}) assert.NoError(t, err) assert.Empty(t, repos) assert.Equal(t, int64(0), count) // Test search within description - repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{ + repos, count, err = repo_model.SearchRepository(db.DefaultContext, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{ Page: 1, PageSize: 10, @@ -104,7 +103,7 @@ func TestSearchRepository(t *testing.T) { assert.Equal(t, int64(1), count) // Test NOT search within description - repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{ + repos, count, err = repo_model.SearchRepository(db.DefaultContext, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{ Page: 1, PageSize: 10, @@ -236,12 +235,12 @@ func TestSearchRepository(t *testing.T) { { name: "AllPublic/PublicRepositoriesOfUserIncludingCollaborative", opts: &repo_model.SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 15, AllPublic: true, Template: util.OptionalBoolFalse}, - count: 28, + count: 29, }, { name: "AllPublic/PublicAndPrivateRepositoriesOfUserIncludingCollaborative", opts: &repo_model.SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 15, Private: true, AllPublic: true, AllLimited: true, Template: util.OptionalBoolFalse}, - count: 33, + count: 34, }, { name: "AllPublic/PublicAndPrivateRepositoriesOfUserIncludingCollaborativeByName", @@ -256,7 +255,7 @@ func TestSearchRepository(t *testing.T) { { name: "AllPublic/PublicRepositoriesOfOrganization", opts: &repo_model.SearchRepoOptions{ListOptions: db.ListOptions{Page: 1, PageSize: 10}, OwnerID: 17, AllPublic: true, Collaborate: util.OptionalBoolFalse, Template: util.OptionalBoolFalse}, - count: 28, + count: 29, }, { name: "AllTemplates", @@ -277,7 +276,7 @@ func TestSearchRepository(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { - repos, count, err := repo_model.SearchRepositoryByName(testCase.opts) + repos, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, testCase.opts) assert.NoError(t, err) assert.Equal(t, int64(testCase.count), count) @@ -377,7 +376,7 @@ func TestSearchRepositoryByTopicName(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { - _, count, err := repo_model.SearchRepositoryByName(testCase.opts) + _, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, testCase.opts) assert.NoError(t, err) assert.Equal(t, int64(testCase.count), count) }) diff --git a/models/repo/repo_test.go b/models/repo/repo_test.go index 617ec12798..fb473151eb 100644 --- a/models/repo/repo_test.go +++ b/models/repo/repo_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo_test @@ -116,7 +115,7 @@ func TestMetas(t *testing.T) { externalTracker.ExternalTrackerConfig().ExternalTrackerStyle = markup.IssueNameStyleRegexp testSuccess(markup.IssueNameStyleRegexp) - repo, err := repo_model.GetRepositoryByID(3) + repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 3) assert.NoError(t, err) metas = repo.ComposeMetas() diff --git a/models/repo/repo_unit.go b/models/repo/repo_unit.go index dd85ca9186..e20d03e2c5 100644 --- a/models/repo/repo_unit.go +++ b/models/repo/repo_unit.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo @@ -241,7 +240,7 @@ func UpdateRepoUnit(unit *RepoUnit) error { // UpdateRepositoryUnits updates a repository's units func UpdateRepositoryUnits(repo *Repository, units []RepoUnit, deleteUnitTypes []unit.Type) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/repo/star.go b/models/repo/star.go index 113b56f595..b3d3d795f8 100644 --- a/models/repo/star.go +++ b/models/repo/star.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package repo @@ -26,7 +25,7 @@ func init() { // StarRepo or unstar repository. func StarRepo(userID, repoID int64, star bool) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/repo/star_test.go b/models/repo/star_test.go index 1b53e17d27..7221a6c8eb 100644 --- a/models/repo/star_test.go +++ b/models/repo/star_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo_test diff --git a/models/repo/topic.go b/models/repo/topic.go index 33bbb05af9..05f50cfe46 100644 --- a/models/repo/topic.go +++ b/models/repo/topic.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo @@ -231,7 +230,7 @@ func GetRepoTopicByName(ctx context.Context, repoID int64, topicName string) (*T // AddTopic adds a topic name to a repository (if it does not already have it) func AddTopic(repoID int64, topicName string) (*Topic, error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } @@ -293,7 +292,7 @@ func SaveTopics(repoID int64, topicNames ...string) error { return err } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/repo/topic_test.go b/models/repo/topic_test.go index 8187addb81..8a8728168d 100644 --- a/models/repo/topic_test.go +++ b/models/repo/topic_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo_test diff --git a/models/repo/update.go b/models/repo/update.go index cc21deb0bc..3aef280ff8 100644 --- a/models/repo/update.go +++ b/models/repo/update.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo @@ -21,7 +20,7 @@ func UpdateRepositoryOwnerNames(ownerID int64, ownerName string) error { if ownerID == 0 { return nil } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -172,7 +171,7 @@ func ChangeRepositoryName(doer *user_model.User, repo *Repository, newRepoName s } } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/repo/upload.go b/models/repo/upload.go index e115c8e50e..3b1b97c6d6 100644 --- a/models/repo/upload.go +++ b/models/repo/upload.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo @@ -121,7 +120,7 @@ func DeleteUploads(uploads ...*Upload) (err error) { return nil } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/repo/user_repo.go b/models/repo/user_repo.go index e7125f70f8..0d5b8579e0 100644 --- a/models/repo/user_repo.go +++ b/models/repo/user_repo.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package repo @@ -17,8 +16,9 @@ import ( ) // GetStarredRepos returns the repos starred by a particular user -func GetStarredRepos(userID int64, private bool, listOptions db.ListOptions) ([]*Repository, error) { - sess := db.GetEngine(db.DefaultContext).Where("star.uid=?", userID). +func GetStarredRepos(ctx context.Context, userID int64, private bool, listOptions db.ListOptions) ([]*Repository, error) { + sess := db.GetEngine(ctx). + Where("star.uid=?", userID). Join("LEFT", "star", "`repository`.id=`star`.repo_id") if !private { sess = sess.And("is_private=?", false) @@ -36,8 +36,9 @@ func GetStarredRepos(userID int64, private bool, listOptions db.ListOptions) ([] } // GetWatchedRepos returns the repos watched by a particular user -func GetWatchedRepos(userID int64, private bool, listOptions db.ListOptions) ([]*Repository, int64, error) { - sess := db.GetEngine(db.DefaultContext).Where("watch.user_id=?", userID). +func GetWatchedRepos(ctx context.Context, userID int64, private bool, listOptions db.ListOptions) ([]*Repository, int64, error) { + sess := db.GetEngine(ctx). + Where("watch.user_id=?", userID). And("`watch`.mode<>?", WatchModeDont). Join("LEFT", "watch", "`repository`.id=`watch`.repo_id") if !private { diff --git a/models/repo/user_repo_test.go b/models/repo/user_repo_test.go index 6409145920..7816b0262a 100644 --- a/models/repo/user_repo_test.go +++ b/models/repo/user_repo_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo_test diff --git a/models/repo/watch.go b/models/repo/watch.go index ecc25ee32b..00f313ca7c 100644 --- a/models/repo/watch.go +++ b/models/repo/watch.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/models/repo/watch_test.go b/models/repo/watch_test.go index 18a2d5d5fd..8b8c6d6250 100644 --- a/models/repo/watch_test.go +++ b/models/repo/watch_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo_test diff --git a/models/repo/wiki.go b/models/repo/wiki.go index c8886eaa34..b378666a20 100644 --- a/models/repo/wiki.go +++ b/models/repo/wiki.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo diff --git a/models/repo/wiki_test.go b/models/repo/wiki_test.go index 8631736276..629986f741 100644 --- a/models/repo/wiki_test.go +++ b/models/repo/wiki_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo_test diff --git a/models/repo_collaboration.go b/models/repo_collaboration.go index 58d6b0f488..b85880eab9 100644 --- a/models/repo_collaboration.go +++ b/models/repo_collaboration.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package models @@ -25,7 +24,7 @@ func DeleteCollaboration(repo *repo_model.Repository, uid int64) (err error) { UserID: uid, } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -54,7 +53,7 @@ func DeleteCollaboration(repo *repo_model.Repository, uid int64) (err error) { } func reconsiderRepoIssuesAssignee(ctx context.Context, repo *repo_model.Repository, uid int64) error { - user, err := user_model.GetUserByIDCtx(ctx, uid) + user, err := user_model.GetUserByID(ctx, uid) if err != nil { return err } diff --git a/models/repo_collaboration_test.go b/models/repo_collaboration_test.go index 77034b65d2..94c5ab5291 100644 --- a/models/repo_collaboration_test.go +++ b/models/repo_collaboration_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package models diff --git a/models/repo_test.go b/models/repo_test.go index a8358e307d..da66b16136 100644 --- a/models/repo_test.go +++ b/models/repo_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package models diff --git a/models/repo_transfer.go b/models/repo_transfer.go index d6a3985fe5..19e6c06627 100644 --- a/models/repo_transfer.go +++ b/models/repo_transfer.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package models @@ -40,9 +39,9 @@ func init() { } // LoadAttributes fetches the transfer recipient from the database -func (r *RepoTransfer) LoadAttributes() error { +func (r *RepoTransfer) LoadAttributes(ctx context.Context) error { if r.Recipient == nil { - u, err := user_model.GetUserByID(r.RecipientID) + u, err := user_model.GetUserByID(ctx, r.RecipientID) if err != nil { return err } @@ -52,7 +51,7 @@ func (r *RepoTransfer) LoadAttributes() error { if r.Recipient.IsOrganization() && len(r.TeamIDs) != len(r.Teams) { for _, v := range r.TeamIDs { - team, err := organization.GetTeamByID(db.DefaultContext, v) + team, err := organization.GetTeamByID(ctx, v) if err != nil { return err } @@ -66,7 +65,7 @@ func (r *RepoTransfer) LoadAttributes() error { } if r.Doer == nil { - u, err := user_model.GetUserByID(r.DoerID) + u, err := user_model.GetUserByID(ctx, r.DoerID) if err != nil { return err } @@ -81,7 +80,7 @@ func (r *RepoTransfer) LoadAttributes() error { // For user, it checks if it's himself // For organizations, it checks if the user is able to create repos func (r *RepoTransfer) CanUserAcceptTransfer(u *user_model.User) bool { - if err := r.LoadAttributes(); err != nil { + if err := r.LoadAttributes(db.DefaultContext); err != nil { log.Error("LoadAttributes: %v", err) return false } @@ -90,7 +89,7 @@ func (r *RepoTransfer) CanUserAcceptTransfer(u *user_model.User) bool { return r.RecipientID == u.ID } - allowed, err := organization.CanCreateOrgRepo(r.RecipientID, u.ID) + allowed, err := organization.CanCreateOrgRepo(db.DefaultContext, r.RecipientID, u.ID) if err != nil { log.Error("CanCreateOrgRepo: %v", err) return false @@ -101,10 +100,10 @@ func (r *RepoTransfer) CanUserAcceptTransfer(u *user_model.User) bool { // GetPendingRepositoryTransfer fetches the most recent and ongoing transfer // process for the repository -func GetPendingRepositoryTransfer(repo *repo_model.Repository) (*RepoTransfer, error) { +func GetPendingRepositoryTransfer(ctx context.Context, repo *repo_model.Repository) (*RepoTransfer, error) { transfer := new(RepoTransfer) - has, err := db.GetEngine(db.DefaultContext).Where("repo_id = ? ", repo.ID).Get(transfer) + has, err := db.GetEngine(ctx).Where("repo_id = ? ", repo.ID).Get(transfer) if err != nil { return nil, err } @@ -124,7 +123,7 @@ func deleteRepositoryTransfer(ctx context.Context, repoID int64) error { // CancelRepositoryTransfer marks the repository as ready and remove pending transfer entry, // thus cancel the transfer process. func CancelRepositoryTransfer(repo *repo_model.Repository) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -155,56 +154,48 @@ func TestRepositoryReadyForTransfer(status repo_model.RepositoryStatus) error { // CreatePendingRepositoryTransfer transfer a repo from one owner to a new one. // it marks the repository transfer as "pending" -func CreatePendingRepositoryTransfer(doer, newOwner *user_model.User, repoID int64, teams []*organization.Team) error { - ctx, committer, err := db.TxContext() - if err != nil { - return err - } - defer committer.Close() - - repo, err := repo_model.GetRepositoryByIDCtx(ctx, repoID) - if err != nil { - return err - } - - // Make sure repo is ready to transfer - if err := TestRepositoryReadyForTransfer(repo.Status); err != nil { - return err - } - - repo.Status = repo_model.RepositoryPendingTransfer - if err := repo_model.UpdateRepositoryCols(ctx, repo, "status"); err != nil { - return err - } - - // Check if new owner has repository with same name. - if has, err := repo_model.IsRepositoryExist(ctx, newOwner, repo.Name); err != nil { - return fmt.Errorf("IsRepositoryExist: %w", err) - } else if has { - return repo_model.ErrRepoAlreadyExist{ - Uname: newOwner.LowerName, - Name: repo.Name, +func CreatePendingRepositoryTransfer(ctx context.Context, doer, newOwner *user_model.User, repoID int64, teams []*organization.Team) error { + return db.AutoTx(ctx, func(ctx context.Context) error { + repo, err := repo_model.GetRepositoryByID(ctx, repoID) + if err != nil { + return err } - } - transfer := &RepoTransfer{ - RepoID: repo.ID, - RecipientID: newOwner.ID, - CreatedUnix: timeutil.TimeStampNow(), - UpdatedUnix: timeutil.TimeStampNow(), - DoerID: doer.ID, - TeamIDs: make([]int64, 0, len(teams)), - } + // Make sure repo is ready to transfer + if err := TestRepositoryReadyForTransfer(repo.Status); err != nil { + return err + } - for k := range teams { - transfer.TeamIDs = append(transfer.TeamIDs, teams[k].ID) - } + repo.Status = repo_model.RepositoryPendingTransfer + if err := repo_model.UpdateRepositoryCols(ctx, repo, "status"); err != nil { + return err + } - if err := db.Insert(ctx, transfer); err != nil { - return err - } + // Check if new owner has repository with same name. + if has, err := repo_model.IsRepositoryExist(ctx, newOwner, repo.Name); err != nil { + return fmt.Errorf("IsRepositoryExist: %w", err) + } else if has { + return repo_model.ErrRepoAlreadyExist{ + Uname: newOwner.LowerName, + Name: repo.Name, + } + } - return committer.Commit() + transfer := &RepoTransfer{ + RepoID: repo.ID, + RecipientID: newOwner.ID, + CreatedUnix: timeutil.TimeStampNow(), + UpdatedUnix: timeutil.TimeStampNow(), + DoerID: doer.ID, + TeamIDs: make([]int64, 0, len(teams)), + } + + for k := range teams { + transfer.TeamIDs = append(transfer.TeamIDs, teams[k].ID) + } + + return db.Insert(ctx, transfer) + }) } // TransferOwnership transfers all corresponding repository items from old user to new one. @@ -243,7 +234,7 @@ func TransferOwnership(doer *user_model.User, newOwnerName string, repo *repo_mo } }() - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/repo_transfer_test.go b/models/repo_transfer_test.go index 7904b04e98..8352adc948 100644 --- a/models/repo_transfer_test.go +++ b/models/repo_transfer_test.go @@ -1,12 +1,12 @@ // 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. +// SPDX-License-Identifier: MIT package models import ( "testing" + "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -20,36 +20,36 @@ func TestRepositoryTransfer(t *testing.T) { doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) - transfer, err := GetPendingRepositoryTransfer(repo) + transfer, err := GetPendingRepositoryTransfer(db.DefaultContext, repo) assert.NoError(t, err) assert.NotNil(t, transfer) // Cancel transfer assert.NoError(t, CancelRepositoryTransfer(repo)) - transfer, err = GetPendingRepositoryTransfer(repo) + transfer, err = GetPendingRepositoryTransfer(db.DefaultContext, repo) assert.Error(t, err) assert.Nil(t, transfer) assert.True(t, IsErrNoPendingTransfer(err)) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - assert.NoError(t, CreatePendingRepositoryTransfer(doer, user2, repo.ID, nil)) + assert.NoError(t, CreatePendingRepositoryTransfer(db.DefaultContext, doer, user2, repo.ID, nil)) - transfer, err = GetPendingRepositoryTransfer(repo) + transfer, err = GetPendingRepositoryTransfer(db.DefaultContext, repo) assert.Nil(t, err) - assert.NoError(t, transfer.LoadAttributes()) + assert.NoError(t, transfer.LoadAttributes(db.DefaultContext)) assert.Equal(t, "user2", transfer.Recipient.Name) user6 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Only transfer can be started at any given time - err = CreatePendingRepositoryTransfer(doer, user6, repo.ID, nil) + err = CreatePendingRepositoryTransfer(db.DefaultContext, doer, user6, repo.ID, nil) assert.Error(t, err) assert.True(t, IsErrRepoTransferInProgress(err)) // Unknown user - err = CreatePendingRepositoryTransfer(doer, &user_model.User{ID: 1000, LowerName: "user1000"}, repo.ID, nil) + err = CreatePendingRepositoryTransfer(db.DefaultContext, doer, &user_model.User{ID: 1000, LowerName: "user1000"}, repo.ID, nil) assert.Error(t, err) // Cancel transfer diff --git a/models/system/appstate.go b/models/system/appstate.go index c11a2512ab..7378537678 100644 --- a/models/system/appstate.go +++ b/models/system/appstate.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package system @@ -25,7 +24,7 @@ func init() { // SaveAppStateContent saves the app state item to database func SaveAppStateContent(key, content string) error { - return db.WithTx(func(ctx context.Context) error { + return db.WithTx(db.DefaultContext, func(ctx context.Context) error { eng := db.GetEngine(ctx) // try to update existing row res, err := eng.Exec("UPDATE app_state SET revision=revision+1, content=? WHERE id=?", content, key) diff --git a/models/system/main_test.go b/models/system/main_test.go index a56c76aedc..94e2906447 100644 --- a/models/system/main_test.go +++ b/models/system/main_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package system_test diff --git a/models/system/notice.go b/models/system/notice.go index 3276fa3ffb..e598abe222 100644 --- a/models/system/notice.go +++ b/models/system/notice.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package system diff --git a/models/system/notice_test.go b/models/system/notice_test.go index 768bcca66c..01eb9b57a5 100644 --- a/models/system/notice_test.go +++ b/models/system/notice_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package system_test diff --git a/models/system/setting.go b/models/system/setting.go index 9711d38f3b..dc6145b417 100644 --- a/models/system/setting.go +++ b/models/system/setting.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package system @@ -12,6 +11,7 @@ import ( "strings" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/modules/cache" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/timeutil" @@ -35,6 +35,10 @@ func (s *Setting) TableName() string { } func (s *Setting) GetValueBool() bool { + if s == nil { + return false + } + b, _ := strconv.ParseBool(s.SettingValue) return b } @@ -75,8 +79,8 @@ func IsErrDataExpired(err error) bool { return ok } -// GetSetting returns specific setting -func GetSetting(key string) (*Setting, error) { +// GetSettingNoCache returns specific setting without using the cache +func GetSettingNoCache(key string) (*Setting, error) { v, err := GetSettings([]string{key}) if err != nil { return nil, err @@ -87,6 +91,24 @@ func GetSetting(key string) (*Setting, error) { return v[key], nil } +// GetSetting returns the setting value via the key +func GetSetting(key string) (*Setting, error) { + return cache.Get(genSettingCacheKey(key), func() (*Setting, error) { + res, err := GetSettingNoCache(key) + if err != nil { + return nil, err + } + return res, nil + }) +} + +// GetSettingBool return bool value of setting, +// none existing keys and errors are ignored and result in false +func GetSettingBool(key string) bool { + s, _ := GetSetting(key) + return s.GetValueBool() +} + // GetSettings returns specific settings func GetSettings(keys []string) (map[string]*Setting, error) { for i := 0; i < len(keys); i++ { @@ -139,12 +161,13 @@ func GetAllSettings() (AllSettings, error) { // DeleteSetting deletes a specific setting for a user func DeleteSetting(setting *Setting) error { + cache.Remove(genSettingCacheKey(setting.SettingKey)) _, err := db.GetEngine(db.DefaultContext).Delete(setting) return err } func SetSettingNoVersion(key, value string) error { - s, err := GetSetting(key) + s, err := GetSettingNoCache(key) if IsErrSettingIsNotExist(err) { return SetSetting(&Setting{ SettingKey: key, @@ -160,15 +183,19 @@ func SetSettingNoVersion(key, value string) error { // SetSetting updates a users' setting for a specific key func SetSetting(setting *Setting) error { - if err := upsertSettingValue(strings.ToLower(setting.SettingKey), setting.SettingValue, setting.Version); err != nil { + _, err := cache.Set(genSettingCacheKey(setting.SettingKey), func() (*Setting, error) { + return setting, upsertSettingValue(strings.ToLower(setting.SettingKey), setting.SettingValue, setting.Version) + }) + if err != nil { return err } + setting.Version++ return nil } func upsertSettingValue(key, value string, version int) error { - return db.WithTx(func(ctx context.Context) error { + return db.WithTx(db.DefaultContext, func(ctx context.Context) error { e := db.GetEngine(ctx) // here we use a general method to do a safe upsert for different databases (and most transaction levels) @@ -213,7 +240,7 @@ var ( func Init() error { var disableGravatar bool - disableGravatarSetting, err := GetSetting(KeyPictureDisableGravatar) + disableGravatarSetting, err := GetSettingNoCache(KeyPictureDisableGravatar) if IsErrSettingIsNotExist(err) { disableGravatar = setting.GetDefaultDisableGravatar() disableGravatarSetting = &Setting{SettingValue: strconv.FormatBool(disableGravatar)} @@ -224,7 +251,7 @@ func Init() error { } var enableFederatedAvatar bool - enableFederatedAvatarSetting, err := GetSetting(KeyPictureEnableFederatedAvatar) + enableFederatedAvatarSetting, err := GetSettingNoCache(KeyPictureEnableFederatedAvatar) if IsErrSettingIsNotExist(err) { enableFederatedAvatar = setting.GetDefaultEnableFederatedAvatar(disableGravatar) enableFederatedAvatarSetting = &Setting{SettingValue: strconv.FormatBool(enableFederatedAvatar)} diff --git a/models/system/setting_key.go b/models/system/setting_key.go index 5a6ea6ed72..ad083ed1ea 100644 --- a/models/system/setting_key.go +++ b/models/system/setting_key.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package system @@ -9,3 +8,8 @@ const ( KeyPictureDisableGravatar = "picture.disable_gravatar" KeyPictureEnableFederatedAvatar = "picture.enable_federated_avatar" ) + +// genSettingCacheKey returns the cache key for some configuration +func genSettingCacheKey(key string) string { + return "system.setting." + key +} diff --git a/models/system/setting_test.go b/models/system/setting_test.go index d25fc05f31..3ff5ba2520 100644 --- a/models/system/setting_test.go +++ b/models/system/setting_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package system_test diff --git a/models/unit/unit.go b/models/unit/unit.go index b83bd61831..c4743dbdb4 100644 --- a/models/unit/unit.go +++ b/models/unit/unit.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package unit diff --git a/models/unittest/consistency.go b/models/unittest/consistency.go index 46f889746a..17ff75c089 100644 --- a/models/unittest/consistency.go +++ b/models/unittest/consistency.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package unittest diff --git a/models/unittest/fixtures.go b/models/unittest/fixtures.go index e39acd766f..9fba053825 100644 --- a/models/unittest/fixtures.go +++ b/models/unittest/fixtures.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package unittest diff --git a/models/unittest/fscopy.go b/models/unittest/fscopy.go index ff815e729d..631da49f2d 100644 --- a/models/unittest/fscopy.go +++ b/models/unittest/fscopy.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package unittest diff --git a/models/unittest/reflection.go b/models/unittest/reflection.go index 68c312ac9e..1b149b19fe 100644 --- a/models/unittest/reflection.go +++ b/models/unittest/reflection.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package unittest diff --git a/models/unittest/testdb.go b/models/unittest/testdb.go index 2e6c25ae48..87d9304618 100644 --- a/models/unittest/testdb.go +++ b/models/unittest/testdb.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package unittest diff --git a/models/unittest/unit_tests.go b/models/unittest/unit_tests.go index c8673debed..b2f19196c7 100644 --- a/models/unittest/unit_tests.go +++ b/models/unittest/unit_tests.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package unittest diff --git a/models/user.go b/models/user.go index 85f465127a..715d0e3866 100644 --- a/models/user.go +++ b/models/user.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package models @@ -89,6 +88,7 @@ func DeleteUser(ctx context.Context, u *user_model.User, purge bool) (err error) &user_model.UserBadge{UserID: u.ID}, &pull_model.AutoMerge{DoerID: u.ID}, &pull_model.ReviewState{UserID: u.ID}, + &user_model.Redirect{RedirectUserID: u.ID}, ); err != nil { return fmt.Errorf("deleteBeans: %w", err) } diff --git a/models/user/avatar.go b/models/user/avatar.go index 89285a040b..5b8b5f77e7 100644 --- a/models/user/avatar.go +++ b/models/user/avatar.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package user @@ -68,11 +67,9 @@ func (u *User) AvatarLinkWithSize(size int) string { useLocalAvatar := false autoGenerateAvatar := false - var disableGravatar bool disableGravatarSetting, _ := system_model.GetSetting(system_model.KeyPictureDisableGravatar) - if disableGravatarSetting != nil { - disableGravatar = disableGravatarSetting.GetValueBool() - } + + disableGravatar := disableGravatarSetting.GetValueBool() switch { case u.UseCustomAvatar: @@ -122,3 +119,10 @@ func (u *User) IsUploadAvatarChanged(data []byte) bool { avatarID := fmt.Sprintf("%x", md5.Sum([]byte(fmt.Sprintf("%d-%x", u.ID, md5.Sum(data))))) return u.Avatar != avatarID } + +// ExistsWithAvatarAtStoragePath returns true if there is a user with this Avatar +func ExistsWithAvatarAtStoragePath(ctx context.Context, storagePath string) (bool, error) { + // See func (u *User) CustomAvatarRelativePath() + // u.Avatar is used directly as the storage path - therefore we can check for existence directly using the path + return db.GetEngine(ctx).Where("`avatar`=?", storagePath).Exist(new(User)) +} diff --git a/models/user/badge.go b/models/user/badge.go index 5ff840cb8c..948b0b1065 100644 --- a/models/user/badge.go +++ b/models/user/badge.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package user diff --git a/models/user/email_address.go b/models/user/email_address.go index d6279b6639..69e94f8bb6 100644 --- a/models/user/email_address.go +++ b/models/user/email_address.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2020 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. +// SPDX-License-Identifier: MIT package user @@ -321,7 +320,7 @@ func DeleteInactiveEmailAddresses(ctx context.Context) error { // ActivateEmail activates the email address to given user. func ActivateEmail(email *EmailAddress) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -333,7 +332,7 @@ func ActivateEmail(email *EmailAddress) error { } func updateActivation(ctx context.Context, email *EmailAddress, activate bool) error { - user, err := GetUserByIDCtx(ctx, email.UID) + user, err := GetUserByID(ctx, email.UID) if err != nil { return err } @@ -372,7 +371,7 @@ func MakeEmailPrimary(email *EmailAddress) error { } } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -510,7 +509,7 @@ func SearchEmails(opts *SearchEmailOptions) ([]*SearchEmailResult, int64, error) // ActivateUserEmail will change the activated state of an email address, // either primary or secondary (all in the email_address table) func ActivateUserEmail(userID int64, email string, activate bool) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/user/email_address_test.go b/models/user/email_address_test.go index b9acaa1113..53fd18c303 100644 --- a/models/user/email_address_test.go +++ b/models/user/email_address_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package user_test @@ -163,7 +162,7 @@ func TestMakeEmailPrimary(t *testing.T) { err = user_model.MakeEmailPrimary(email) assert.NoError(t, err) - user, _ := user_model.GetUserByID(int64(10)) + user, _ := user_model.GetUserByID(db.DefaultContext, int64(10)) assert.Equal(t, "user101@example.com", user.Email) } diff --git a/models/user/error.go b/models/user/error.go index 3fe4ee6657..306b9ee9d9 100644 --- a/models/user/error.go +++ b/models/user/error.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package user diff --git a/models/user/external_login_user.go b/models/user/external_login_user.go index 496717c57b..f70f3effcc 100644 --- a/models/user/external_login_user.go +++ b/models/user/external_login_user.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package user diff --git a/models/user/follow.go b/models/user/follow.go index 5f24f706d1..7efecc26a7 100644 --- a/models/user/follow.go +++ b/models/user/follow.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package user @@ -33,7 +32,7 @@ func FollowUser(userID, followID int64) (err error) { return nil } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -59,7 +58,7 @@ func UnfollowUser(userID, followID int64) (err error) { return nil } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/user/follow_test.go b/models/user/follow_test.go index ad2f7cf742..fc408d5257 100644 --- a/models/user/follow_test.go +++ b/models/user/follow_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package user_test diff --git a/models/user/list.go b/models/user/list.go index 6c43c961c8..6b3b7bea9a 100644 --- a/models/user/list.go +++ b/models/user/list.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package user diff --git a/models/user/main_test.go b/models/user/main_test.go index b2416a3e0a..0d76aacd5f 100644 --- a/models/user/main_test.go +++ b/models/user/main_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package user_test diff --git a/models/user/openid.go b/models/user/openid.go index f8e8a787e6..1946705048 100644 --- a/models/user/openid.go +++ b/models/user/openid.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package user diff --git a/models/user/openid_test.go b/models/user/openid_test.go index d20b72d19a..6f0eae55e7 100644 --- a/models/user/openid_test.go +++ b/models/user/openid_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package user_test diff --git a/models/user/redirect.go b/models/user/redirect.go index af8d6439ad..9d8903c059 100644 --- a/models/user/redirect.go +++ b/models/user/redirect.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package user diff --git a/models/user/redirect_test.go b/models/user/redirect_test.go index a5b19d4f04..3d2ea3aeec 100644 --- a/models/user/redirect_test.go +++ b/models/user/redirect_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package user_test diff --git a/models/user/search.go b/models/user/search.go index fa4a021a47..622e47ccff 100644 --- a/models/user/search.go +++ b/models/user/search.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package user diff --git a/models/user/setting.go b/models/user/setting.go index 5fe7c2ec23..a17483f9af 100644 --- a/models/user/setting.go +++ b/models/user/setting.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package user @@ -10,6 +9,7 @@ import ( "strings" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/modules/cache" "xorm.io/builder" ) @@ -47,9 +47,25 @@ func IsErrUserSettingIsNotExist(err error) bool { return ok } -// GetSetting returns specific setting +// genSettingCacheKey returns the cache key for some configuration +func genSettingCacheKey(userID int64, key string) string { + return fmt.Sprintf("user_%d.setting.%s", userID, key) +} + +// GetSetting returns the setting value via the key func GetSetting(uid int64, key string) (*Setting, error) { - v, err := GetUserSettings(uid, []string{key}) + return cache.Get(genSettingCacheKey(uid, key), func() (*Setting, error) { + res, err := GetSettingNoCache(uid, key) + if err != nil { + return nil, err + } + return res, nil + }) +} + +// GetSettingNoCache returns specific setting without using the cache +func GetSettingNoCache(uid int64, key string) (*Setting, error) { + v, err := GetSettings(uid, []string{key}) if err != nil { return nil, err } @@ -59,8 +75,8 @@ func GetSetting(uid int64, key string) (*Setting, error) { return v[key], nil } -// GetUserSettings returns specific settings from user -func GetUserSettings(uid int64, keys []string) (map[string]*Setting, error) { +// GetSettings returns specific settings from user +func GetSettings(uid int64, keys []string) (map[string]*Setting, error) { settings := make([]*Setting, 0, len(keys)) if err := db.GetEngine(db.DefaultContext). Where("user_id=?", uid). @@ -105,6 +121,7 @@ func GetUserSetting(userID int64, key string, def ...string) (string, error) { if err := validateUserSettingKey(key); err != nil { return "", err } + setting := &Setting{UserID: userID, SettingKey: key} has, err := db.GetEngine(db.DefaultContext).Get(setting) if err != nil { @@ -124,7 +141,10 @@ func DeleteUserSetting(userID int64, key string) error { if err := validateUserSettingKey(key); err != nil { return err } + + cache.Remove(genSettingCacheKey(userID, key)) _, err := db.GetEngine(db.DefaultContext).Delete(&Setting{UserID: userID, SettingKey: key}) + return err } @@ -133,11 +153,16 @@ func SetUserSetting(userID int64, key, value string) error { if err := validateUserSettingKey(key); err != nil { return err } - return upsertUserSettingValue(userID, key, value) + + _, err := cache.Set(genSettingCacheKey(userID, key), func() (string, error) { + return value, upsertUserSettingValue(userID, key, value) + }) + + return err } func upsertUserSettingValue(userID int64, key, value string) error { - return db.WithTx(func(ctx context.Context) error { + return db.WithTx(db.DefaultContext, func(ctx context.Context) error { e := db.GetEngine(ctx) // here we use a general method to do a safe upsert for different databases (and most transaction levels) diff --git a/models/user/setting_keys.go b/models/user/setting_keys.go index d48ac93052..10255735b3 100644 --- a/models/user/setting_keys.go +++ b/models/user/setting_keys.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package user diff --git a/models/user/setting_test.go b/models/user/setting_test.go index f0083038df..d0d612d25d 100644 --- a/models/user/setting_test.go +++ b/models/user/setting_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package user_test @@ -27,7 +26,7 @@ func TestSettings(t *testing.T) { assert.NoError(t, err) // get specific setting - settings, err := user_model.GetUserSettings(99, []string{keyName}) + settings, err := user_model.GetSettings(99, []string{keyName}) assert.NoError(t, err) assert.Len(t, settings, 1) assert.EqualValues(t, newSetting.SettingValue, settings[keyName].SettingValue) diff --git a/models/user/user.go b/models/user/user.go index 0949fe3424..af92027e25 100644 --- a/models/user/user.go +++ b/models/user/user.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package user @@ -402,7 +401,7 @@ func hashPassword(passwd, salt, algo string) (string, error) { tempPasswd = pbkdf2.Key([]byte(passwd), saltBytes, 10000, 50, sha256.New) } - return fmt.Sprintf("%x", tempPasswd), nil + return hex.EncodeToString(tempPasswd), nil } // SetPassword hashes a password using the algorithm defined in the config value of PASSWORD_HASH_ALGO @@ -695,7 +694,7 @@ func CreateUser(u *User, overwriteDefault ...*CreateUserOverwriteOptions) (err e return err } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -814,7 +813,7 @@ func ChangeUserName(u *User, newUserName string) (err error) { return err } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -957,7 +956,7 @@ func UpdateUserCols(ctx context.Context, u *User, cols ...string) error { // UpdateUserSetting updates user's settings. func UpdateUserSetting(u *User) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -994,12 +993,7 @@ func UserPath(userName string) string { //revive:disable-line:exported } // GetUserByID returns the user object by given ID if exists. -func GetUserByID(id int64) (*User, error) { - return GetUserByIDCtx(db.DefaultContext, id) -} - -// GetUserByIDCtx returns the user object by given ID if exists. -func GetUserByIDCtx(ctx context.Context, id int64) (*User, error) { +func GetUserByID(ctx context.Context, id int64) (*User, error) { u := new(User) has, err := db.GetEngine(ctx).ID(id).Get(u) if err != nil { @@ -1042,14 +1036,15 @@ func GetUserEmailsByNames(ctx context.Context, names []string) []string { } // GetMaileableUsersByIDs gets users from ids, but only if they can receive mails -func GetMaileableUsersByIDs(ids []int64, isMention bool) ([]*User, error) { +func GetMaileableUsersByIDs(ctx context.Context, ids []int64, isMention bool) ([]*User, error) { if len(ids) == 0 { return nil, nil } ous := make([]*User, 0, len(ids)) if isMention { - return ous, db.GetEngine(db.DefaultContext).In("id", ids). + return ous, db.GetEngine(ctx). + In("id", ids). Where("`type` = ?", UserTypeIndividual). And("`prohibit_login` = ?", false). And("`is_active` = ?", true). @@ -1057,7 +1052,8 @@ func GetMaileableUsersByIDs(ids []int64, isMention bool) ([]*User, error) { Find(&ous) } - return ous, db.GetEngine(db.DefaultContext).In("id", ids). + return ous, db.GetEngine(ctx). + In("id", ids). Where("`type` = ?", UserTypeIndividual). And("`prohibit_login` = ?", false). And("`is_active` = ?", true). @@ -1090,10 +1086,10 @@ func GetUserNameByID(ctx context.Context, id int64) (string, error) { } // GetUserIDsByNames returns a slice of ids corresponds to names. -func GetUserIDsByNames(names []string, ignoreNonExistent bool) ([]int64, error) { +func GetUserIDsByNames(ctx context.Context, names []string, ignoreNonExistent bool) ([]int64, error) { ids := make([]int64, 0, len(names)) for _, name := range names { - u, err := GetUserByName(db.DefaultContext, name) + u, err := GetUserByName(ctx, name) if err != nil { if ignoreNonExistent { continue @@ -1175,7 +1171,7 @@ func GetUserByEmailContext(ctx context.Context, email string) (*User, error) { return nil, err } if has { - return GetUserByIDCtx(ctx, emailAddress.UID) + return GetUserByID(ctx, emailAddress.UID) } // Finally, if email address is the protected email address: @@ -1219,7 +1215,7 @@ func GetUserByOpenID(uri string) (*User, error) { return nil, err } if has { - return GetUserByID(oid.UID) + return GetUserByID(db.DefaultContext, oid.UID) } return nil, ErrUserNotExist{0, uri, 0} diff --git a/models/user/user_test.go b/models/user/user_test.go index 5f2ac0a60c..525da531f2 100644 --- a/models/user/user_test.go +++ b/models/user/user_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package user_test @@ -23,7 +22,7 @@ import ( func TestOAuth2Application_LoadUser(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) app := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ID: 1}) - user, err := user_model.GetUserByID(app.UID) + user, err := user_model.GetUserByID(db.DefaultContext, app.UID) assert.NoError(t, err) assert.NotNil(t, user) } @@ -257,12 +256,12 @@ func TestGetUserIDsByNames(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // ignore non existing - IDs, err := user_model.GetUserIDsByNames([]string{"user1", "user2", "none_existing_user"}, true) + IDs, err := user_model.GetUserIDsByNames(db.DefaultContext, []string{"user1", "user2", "none_existing_user"}, true) assert.NoError(t, err) assert.Equal(t, []int64{1, 2}, IDs) // ignore non existing - IDs, err = user_model.GetUserIDsByNames([]string{"user1", "do_not_exist"}, false) + IDs, err = user_model.GetUserIDsByNames(db.DefaultContext, []string{"user1", "do_not_exist"}, false) assert.Error(t, err) assert.Equal(t, []int64(nil), IDs) } @@ -270,14 +269,14 @@ func TestGetUserIDsByNames(t *testing.T) { func TestGetMaileableUsersByIDs(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - results, err := user_model.GetMaileableUsersByIDs([]int64{1, 4}, false) + results, err := user_model.GetMaileableUsersByIDs(db.DefaultContext, []int64{1, 4}, false) assert.NoError(t, err) assert.Len(t, results, 1) if len(results) > 1 { assert.Equal(t, results[0].ID, 1) } - results, err = user_model.GetMaileableUsersByIDs([]int64{1, 4}, true) + results, err = user_model.GetMaileableUsersByIDs(db.DefaultContext, []int64{1, 4}, true) assert.NoError(t, err) assert.Len(t, results, 2) if len(results) > 2 { diff --git a/models/user/user_update.go b/models/user/user_update.go index 9c9dc09bb2..66702e2a14 100644 --- a/models/user/user_update.go +++ b/models/user/user_update.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package user diff --git a/models/webhook/hooktask.go b/models/webhook/hooktask.go index 246484aea9..2a37ff31d8 100644 --- a/models/webhook/hooktask.go +++ b/models/webhook/hooktask.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package webhook @@ -233,14 +232,30 @@ func ReplayHookTask(ctx context.Context, hookID int64, uuid string) (*HookTask, return newTask, db.Insert(ctx, newTask) } -// FindUndeliveredHookTasks represents find the undelivered hook tasks -func FindUndeliveredHookTasks(ctx context.Context) ([]*HookTask, error) { - tasks := make([]*HookTask, 0, 10) +// FindUndeliveredHookTaskIDs will find the next 100 undelivered hook tasks with ID greater than the provided lowerID +func FindUndeliveredHookTaskIDs(ctx context.Context, lowerID int64) ([]int64, error) { + const batchSize = 100 + + tasks := make([]int64, 0, batchSize) return tasks, db.GetEngine(ctx). + Select("id"). + Table(new(HookTask)). Where("is_delivered=?", false). + And("id > ?", lowerID). + Asc("id"). + Limit(batchSize). Find(&tasks) } +func MarkTaskDelivered(ctx context.Context, task *HookTask) (bool, error) { + count, err := db.GetEngine(ctx).ID(task.ID).Where("is_delivered = ?", false).Cols("is_delivered").Update(&HookTask{ + ID: task.ID, + IsDelivered: true, + }) + + return count != 0, err +} + // CleanupHookTaskTable deletes rows from hook_task as needed. func CleanupHookTaskTable(ctx context.Context, cleanupType HookTaskCleanupType, olderThan time.Duration, numberToKeep int) error { log.Trace("Doing: CleanupHookTaskTable") diff --git a/models/webhook/main_test.go b/models/webhook/main_test.go index 39ef2da6a2..8df569a3cc 100644 --- a/models/webhook/main_test.go +++ b/models/webhook/main_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/models/webhook/webhook.go b/models/webhook/webhook.go index 6426b95202..5defc67fd7 100644 --- a/models/webhook/webhook.go +++ b/models/webhook/webhook.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2017 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. +// SPDX-License-Identifier: MIT package webhook @@ -575,7 +574,7 @@ func UpdateWebhookLastStatus(w *Webhook) error { // deleteWebhook uses argument bean as query condition, // ID must be specified and do not assign unnecessary fields. func deleteWebhook(bean *Webhook) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -610,7 +609,7 @@ func DeleteWebhookByOrgID(orgID, id int64) error { // DeleteDefaultSystemWebhook deletes an admin-configured default or system webhook (where Org and Repo ID both 0) func DeleteDefaultSystemWebhook(id int64) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/models/webhook/webhook_test.go b/models/webhook/webhook_test.go index 8c4838ebdc..2bdafb61b6 100644 --- a/models/webhook/webhook_test.go +++ b/models/webhook/webhook_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/modules/analyze/code_langauge.go b/modules/analyze/code_langauge.go index baec2cebc5..74e7a06d06 100644 --- a/modules/analyze/code_langauge.go +++ b/modules/analyze/code_langauge.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package analyze diff --git a/modules/analyze/generated.go b/modules/analyze/generated.go index 0f14d28545..f608387bfe 100644 --- a/modules/analyze/generated.go +++ b/modules/analyze/generated.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package analyze diff --git a/modules/analyze/vendor.go b/modules/analyze/vendor.go index 976a6ddc7b..adcca923dd 100644 --- a/modules/analyze/vendor.go +++ b/modules/analyze/vendor.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package analyze diff --git a/modules/analyze/vendor_test.go b/modules/analyze/vendor_test.go index 2784e49d34..aafd3c431b 100644 --- a/modules/analyze/vendor_test.go +++ b/modules/analyze/vendor_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package analyze diff --git a/modules/auth/openid/discovery_cache.go b/modules/auth/openid/discovery_cache.go index 68cd7a8756..3a8d119bdd 100644 --- a/modules/auth/openid/discovery_cache.go +++ b/modules/auth/openid/discovery_cache.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package openid diff --git a/modules/auth/openid/discovery_cache_test.go b/modules/auth/openid/discovery_cache_test.go index 28546f6031..5a7f450937 100644 --- a/modules/auth/openid/discovery_cache_test.go +++ b/modules/auth/openid/discovery_cache_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package openid diff --git a/modules/auth/openid/openid.go b/modules/auth/openid/openid.go index 8926fc6d7a..249ce02335 100644 --- a/modules/auth/openid/openid.go +++ b/modules/auth/openid/openid.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package openid diff --git a/modules/auth/pam/pam.go b/modules/auth/pam/pam.go index 39e93d7162..cca1482b1d 100644 --- a/modules/auth/pam/pam.go +++ b/modules/auth/pam/pam.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT //go:build pam diff --git a/modules/auth/pam/pam_stub.go b/modules/auth/pam/pam_stub.go index 414d7631b5..a48e89860e 100644 --- a/modules/auth/pam/pam_stub.go +++ b/modules/auth/pam/pam_stub.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT //go:build !pam diff --git a/modules/auth/pam/pam_test.go b/modules/auth/pam/pam_test.go index 08565d2f31..c277d59c41 100644 --- a/modules/auth/pam/pam_test.go +++ b/modules/auth/pam/pam_test.go @@ -1,8 +1,7 @@ //go:build pam // 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. +// SPDX-License-Identifier: MIT package pam diff --git a/modules/auth/webauthn/webauthn.go b/modules/auth/webauthn/webauthn.go index e39b6f46d6..ec60a86100 100644 --- a/modules/auth/webauthn/webauthn.go +++ b/modules/auth/webauthn/webauthn.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package webauthn diff --git a/modules/auth/webauthn/webauthn_test.go b/modules/auth/webauthn/webauthn_test.go index 71fb9d2757..1beeb64cd6 100644 --- a/modules/auth/webauthn/webauthn_test.go +++ b/modules/auth/webauthn/webauthn_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package webauthn diff --git a/modules/avatar/avatar.go b/modules/avatar/avatar.go index 2de77de009..9ee926b059 100644 --- a/modules/avatar/avatar.go +++ b/modules/avatar/avatar.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package avatar diff --git a/modules/avatar/avatar_test.go b/modules/avatar/avatar_test.go index a2acc54438..5ef4ed379b 100644 --- a/modules/avatar/avatar_test.go +++ b/modules/avatar/avatar_test.go @@ -1,6 +1,5 @@ // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package avatar diff --git a/modules/avatar/identicon/block.go b/modules/avatar/identicon/block.go index 270f05e1b0..cb1803a231 100644 --- a/modules/avatar/identicon/block.go +++ b/modules/avatar/identicon/block.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT // Copied and modified from https://github.com/issue9/identicon/ (MIT License) diff --git a/modules/avatar/identicon/colors.go b/modules/avatar/identicon/colors.go index a8d7090369..09a98bd0e9 100644 --- a/modules/avatar/identicon/colors.go +++ b/modules/avatar/identicon/colors.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package identicon diff --git a/modules/avatar/identicon/identicon.go b/modules/avatar/identicon/identicon.go index cc7e2a791d..63926d5f19 100644 --- a/modules/avatar/identicon/identicon.go +++ b/modules/avatar/identicon/identicon.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT // Copied and modified from https://github.com/issue9/identicon/ (MIT License) // Generate pseudo-random avatars by IP, E-mail, etc. diff --git a/modules/avatar/identicon/identicon_test.go b/modules/avatar/identicon/identicon_test.go index 44635fbb3b..23bcc73e2e 100644 --- a/modules/avatar/identicon/identicon_test.go +++ b/modules/avatar/identicon/identicon_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT //go:build test_avatar_identicon diff --git a/modules/avatar/identicon/polygon.go b/modules/avatar/identicon/polygon.go index 88440633c2..ecfc179a5c 100644 --- a/modules/avatar/identicon/polygon.go +++ b/modules/avatar/identicon/polygon.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT // Copied and modified from https://github.com/issue9/identicon/ (MIT License) diff --git a/modules/base/base.go b/modules/base/base.go index 026f68f646..dddce202da 100644 --- a/modules/base/base.go +++ b/modules/base/base.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package base diff --git a/modules/base/natural_sort.go b/modules/base/natural_sort.go index 46cdd52932..e920177f89 100644 --- a/modules/base/natural_sort.go +++ b/modules/base/natural_sort.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package base diff --git a/modules/base/natural_sort_test.go b/modules/base/natural_sort_test.go index 2faa5acf38..91e864ad2a 100644 --- a/modules/base/natural_sort_test.go +++ b/modules/base/natural_sort_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package base diff --git a/modules/base/tool.go b/modules/base/tool.go index f1e4a3bf97..994e58ac3c 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package base @@ -43,7 +42,7 @@ func EncodeSha1(str string) string { return hex.EncodeToString(h.Sum(nil)) } -// EncodeSha256 string to sha1 hex value. +// EncodeSha256 string to sha256 hex value. func EncodeSha256(str string) string { h := sha256.New() _, _ = h.Write([]byte(str)) diff --git a/modules/base/tool_test.go b/modules/base/tool_test.go index 87de898e0b..81f4b464e6 100644 --- a/modules/base/tool_test.go +++ b/modules/base/tool_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package base diff --git a/modules/cache/cache.go b/modules/cache/cache.go index 21d0cd0a04..2e7d5bb603 100644 --- a/modules/cache/cache.go +++ b/modules/cache/cache.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package cache @@ -46,32 +45,64 @@ func GetCache() mc.Cache { return conn } +// Get returns the key value from cache with callback when no key exists in cache +func Get[V interface{}](key string, getFunc func() (V, error)) (V, error) { + if conn == nil || setting.CacheService.TTL == 0 { + return getFunc() + } + + cached := conn.Get(key) + if value, ok := cached.(V); ok { + return value, nil + } + + value, err := getFunc() + if err != nil { + return value, err + } + + return value, conn.Put(key, value, setting.CacheService.TTLSeconds()) +} + +// Set updates and returns the key value in the cache with callback. The old value is only removed if the updateFunc() is successful +func Set[V interface{}](key string, valueFunc func() (V, error)) (V, error) { + if conn == nil || setting.CacheService.TTL == 0 { + return valueFunc() + } + + value, err := valueFunc() + if err != nil { + return value, err + } + + return value, conn.Put(key, value, setting.CacheService.TTLSeconds()) +} + // GetString returns the key value from cache with callback when no key exists in cache func GetString(key string, getFunc func() (string, error)) (string, error) { if conn == nil || setting.CacheService.TTL == 0 { return getFunc() } - if !conn.IsExist(key) { - var ( - value string - err error - ) - if value, err = getFunc(); err != nil { + + cached := conn.Get(key) + + if cached == nil { + value, err := getFunc() + if err != nil { return value, err } - err = conn.Put(key, value, setting.CacheService.TTLSeconds()) - if err != nil { - return "", err - } + return value, conn.Put(key, value, setting.CacheService.TTLSeconds()) } - value := conn.Get(key) - if v, ok := value.(string); ok { - return v, nil + + if value, ok := cached.(string); ok { + return value, nil } - if v, ok := value.(fmt.Stringer); ok { - return v.String(), nil + + if stringer, ok := cached.(fmt.Stringer); ok { + return stringer.String(), nil } - return fmt.Sprintf("%s", conn.Get(key)), nil + + return fmt.Sprintf("%s", cached), nil } // GetInt returns key value from cache with callback when no key exists in cache @@ -79,30 +110,33 @@ func GetInt(key string, getFunc func() (int, error)) (int, error) { if conn == nil || setting.CacheService.TTL == 0 { return getFunc() } - if !conn.IsExist(key) { - var ( - value int - err error - ) - if value, err = getFunc(); err != nil { + + cached := conn.Get(key) + + if cached == nil { + value, err := getFunc() + if err != nil { return value, err } - err = conn.Put(key, value, setting.CacheService.TTLSeconds()) - if err != nil { - return 0, err - } + + return value, conn.Put(key, value, setting.CacheService.TTLSeconds()) } - switch value := conn.Get(key).(type) { + + switch v := cached.(type) { case int: - return value, nil + return v, nil case string: - v, err := strconv.Atoi(value) + value, err := strconv.Atoi(v) if err != nil { return 0, err } - return v, nil + return value, nil default: - return 0, fmt.Errorf("Unsupported cached value type: %v", value) + value, err := getFunc() + if err != nil { + return value, err + } + return value, conn.Put(key, value, setting.CacheService.TTLSeconds()) } } @@ -111,30 +145,34 @@ func GetInt64(key string, getFunc func() (int64, error)) (int64, error) { if conn == nil || setting.CacheService.TTL == 0 { return getFunc() } - if !conn.IsExist(key) { - var ( - value int64 - err error - ) - if value, err = getFunc(); err != nil { + + cached := conn.Get(key) + + if cached == nil { + value, err := getFunc() + if err != nil { return value, err } - err = conn.Put(key, value, setting.CacheService.TTLSeconds()) - if err != nil { - return 0, err - } + + return value, conn.Put(key, value, setting.CacheService.TTLSeconds()) } - switch value := conn.Get(key).(type) { + + switch v := conn.Get(key).(type) { case int64: - return value, nil + return v, nil case string: - v, err := strconv.ParseInt(value, 10, 64) + value, err := strconv.ParseInt(v, 10, 64) if err != nil { return 0, err } - return v, nil + return value, nil default: - return 0, fmt.Errorf("Unsupported cached value type: %v", value) + value, err := getFunc() + if err != nil { + return value, err + } + + return value, conn.Put(key, value, setting.CacheService.TTLSeconds()) } } diff --git a/modules/cache/cache_redis.go b/modules/cache/cache_redis.go index 7bb71f08ce..8e056ff2ec 100644 --- a/modules/cache/cache_redis.go +++ b/modules/cache/cache_redis.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package cache diff --git a/modules/cache/cache_test.go b/modules/cache/cache_test.go index f418f77e46..1c8f7d55ba 100644 --- a/modules/cache/cache_test.go +++ b/modules/cache/cache_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package cache diff --git a/modules/cache/cache_twoqueue.go b/modules/cache/cache_twoqueue.go index 9c26b011b6..2e2efd00f2 100644 --- a/modules/cache/cache_twoqueue.go +++ b/modules/cache/cache_twoqueue.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package cache diff --git a/modules/charset/ambiguous.go b/modules/charset/ambiguous.go index 9dab3b0951..96e0561e15 100644 --- a/modules/charset/ambiguous.go +++ b/modules/charset/ambiguous.go @@ -1,7 +1,6 @@ // This file is generated by modules/charset/ambiguous/generate.go DO NOT EDIT // Copyright 2022 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. +// SPDX-License-Identifier: MIT package charset @@ -29,6 +28,12 @@ func AmbiguousTablesForLocale(locale translation.Locale) []*AmbiguousTable { key = key[:idx] } } + if table == nil && (locale.Language() == "zh-CN" || locale.Language() == "zh_CN") { + table = AmbiguousCharacters["zh-hans"] + } + if table == nil && strings.HasPrefix(locale.Language(), "zh") { + table = AmbiguousCharacters["zh-hant"] + } if table == nil { table = AmbiguousCharacters["_default"] } diff --git a/modules/charset/ambiguous/generate.go b/modules/charset/ambiguous/generate.go index 7dd2821aae..b0c2531008 100644 --- a/modules/charset/ambiguous/generate.go +++ b/modules/charset/ambiguous/generate.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package main @@ -135,8 +134,8 @@ func runTemplate(t *template.Template, filename string, data interface{}) error var generatorTemplate = template.Must(template.New("ambiguousTemplate").Parse(`// This file is generated by modules/charset/ambiguous/generate.go DO NOT EDIT // Copyright 2022 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. +// SPDX-License-Identifier: MIT + package charset diff --git a/modules/charset/ambiguous_gen.go b/modules/charset/ambiguous_gen.go index cc270affac..c88ffd5aa5 100644 --- a/modules/charset/ambiguous_gen.go +++ b/modules/charset/ambiguous_gen.go @@ -1,7 +1,6 @@ // This file is generated by modules/charset/ambiguous/generate.go DO NOT EDIT // Copyright 2022 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. +// SPDX-License-Identifier: MIT package charset diff --git a/modules/charset/ambiguous_gen_test.go b/modules/charset/ambiguous_gen_test.go index bd64e1c5b1..221c27d0e1 100644 --- a/modules/charset/ambiguous_gen_test.go +++ b/modules/charset/ambiguous_gen_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package charset diff --git a/modules/charset/breakwriter.go b/modules/charset/breakwriter.go index 619826ff21..a87e846466 100644 --- a/modules/charset/breakwriter.go +++ b/modules/charset/breakwriter.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package charset diff --git a/modules/charset/breakwriter_test.go b/modules/charset/breakwriter_test.go index 6bbed42ea5..5eeeedc4e2 100644 --- a/modules/charset/breakwriter_test.go +++ b/modules/charset/breakwriter_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package charset diff --git a/modules/charset/charset.go b/modules/charset/charset.go index a1210d2f05..51152142a5 100644 --- a/modules/charset/charset.go +++ b/modules/charset/charset.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package charset diff --git a/modules/charset/charset_test.go b/modules/charset/charset_test.go index 6dd13c039d..fc56799b47 100644 --- a/modules/charset/charset_test.go +++ b/modules/charset/charset_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package charset diff --git a/modules/charset/escape.go b/modules/charset/escape.go index b264a569ff..ce2eb1446d 100644 --- a/modules/charset/escape.go +++ b/modules/charset/escape.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT //go:generate go run invisible/generate.go -v -o ./invisible_gen.go diff --git a/modules/charset/escape_status.go b/modules/charset/escape_status.go index 7ff0ef112b..37b6ad86d4 100644 --- a/modules/charset/escape_status.go +++ b/modules/charset/escape_status.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package charset diff --git a/modules/charset/escape_stream.go b/modules/charset/escape_stream.go index e5f303d26f..823b635137 100644 --- a/modules/charset/escape_stream.go +++ b/modules/charset/escape_stream.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package charset @@ -240,7 +239,7 @@ func (counts runeCountType) needsEscape() bool { type runeType int const ( - basicASCIIRuneType runeType = iota //nolint // <- This is technically deadcode but its self-documenting so it should stay + basicASCIIRuneType runeType = iota // <- This is technically deadcode but its self-documenting so it should stay brokenRuneType nonBasicASCIIRuneType ambiguousRuneType diff --git a/modules/charset/escape_test.go b/modules/charset/escape_test.go index a7232a4658..abe767f4a5 100644 --- a/modules/charset/escape_test.go +++ b/modules/charset/escape_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package charset diff --git a/modules/charset/htmlstream.go b/modules/charset/htmlstream.go index b354ce6a48..61f29120a6 100644 --- a/modules/charset/htmlstream.go +++ b/modules/charset/htmlstream.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package charset diff --git a/modules/charset/invisible/generate.go b/modules/charset/invisible/generate.go index 39eddd58dd..9dfc253333 100644 --- a/modules/charset/invisible/generate.go +++ b/modules/charset/invisible/generate.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package main @@ -88,8 +87,8 @@ func runTemplate(t *template.Template, filename string, data interface{}) error var generatorTemplate = template.Must(template.New("invisibleTemplate").Parse(`// This file is generated by modules/charset/invisible/generate.go DO NOT EDIT // Copyright 2022 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. +// SPDX-License-Identifier: MIT + package charset diff --git a/modules/charset/invisible_gen.go b/modules/charset/invisible_gen.go index b3bfebe0c0..812f0e34b3 100644 --- a/modules/charset/invisible_gen.go +++ b/modules/charset/invisible_gen.go @@ -1,7 +1,6 @@ // This file is generated by modules/charset/invisible/generate.go DO NOT EDIT // Copyright 2022 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. +// SPDX-License-Identifier: MIT package charset diff --git a/modules/container/set.go b/modules/container/set.go index 4b4c74525d..15779983fd 100644 --- a/modules/container/set.go +++ b/modules/container/set.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package container diff --git a/modules/container/set_test.go b/modules/container/set_test.go index 6654763e56..1502236034 100644 --- a/modules/container/set_test.go +++ b/modules/container/set_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package container diff --git a/modules/context/access_log.go b/modules/context/access_log.go index 1a10c4763a..05c0f86218 100644 --- a/modules/context/access_log.go +++ b/modules/context/access_log.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package context diff --git a/modules/context/api.go b/modules/context/api.go index b9d130e2a8..f49997a787 100644 --- a/modules/context/api.go +++ b/modules/context/api.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package context diff --git a/modules/context/api_org.go b/modules/context/api_org.go index 2231677d42..dad02b1719 100644 --- a/modules/context/api_org.go +++ b/modules/context/api_org.go @@ -1,6 +1,5 @@ // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package context diff --git a/modules/context/api_test.go b/modules/context/api_test.go index 323fdbd2cc..911a49949e 100644 --- a/modules/context/api_test.go +++ b/modules/context/api_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package context diff --git a/modules/context/auth.go b/modules/context/auth.go index e6d882eb5b..7cc29debbd 100644 --- a/modules/context/auth.go +++ b/modules/context/auth.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package context diff --git a/modules/context/captcha.go b/modules/context/captcha.go index 6117d30713..735613504c 100644 --- a/modules/context/captcha.go +++ b/modules/context/captcha.go @@ -1,13 +1,18 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package context import ( + "fmt" "sync" + "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/cache" + "code.gitea.io/gitea/modules/hcaptcha" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/mcaptcha" + "code.gitea.io/gitea/modules/recaptcha" "code.gitea.io/gitea/modules/setting" "gitea.com/go-chi/captcha" @@ -28,3 +33,56 @@ func GetImageCaptcha() *captcha.Captcha { }) return cpt } + +// SetCaptchaData sets common captcha data +func SetCaptchaData(ctx *Context) { + if !setting.Service.EnableCaptcha { + return + } + ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha + ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL + ctx.Data["Captcha"] = GetImageCaptcha() + ctx.Data["CaptchaType"] = setting.Service.CaptchaType + ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey + ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey + ctx.Data["McaptchaSitekey"] = setting.Service.McaptchaSitekey + ctx.Data["McaptchaURL"] = setting.Service.McaptchaURL +} + +const ( + gRecaptchaResponseField = "g-recaptcha-response" + hCaptchaResponseField = "h-captcha-response" + mCaptchaResponseField = "m-captcha-response" +) + +// VerifyCaptcha verifies Captcha data +// No-op if captchas are not enabled +func VerifyCaptcha(ctx *Context, tpl base.TplName, form interface{}) { + if !setting.Service.EnableCaptcha { + return + } + + var valid bool + var err error + switch setting.Service.CaptchaType { + case setting.ImageCaptcha: + valid = GetImageCaptcha().VerifyReq(ctx.Req) + case setting.ReCaptcha: + valid, err = recaptcha.Verify(ctx, ctx.Req.Form.Get(gRecaptchaResponseField)) + case setting.HCaptcha: + valid, err = hcaptcha.Verify(ctx, ctx.Req.Form.Get(hCaptchaResponseField)) + case setting.MCaptcha: + valid, err = mcaptcha.Verify(ctx, ctx.Req.Form.Get(mCaptchaResponseField)) + default: + ctx.ServerError("Unknown Captcha Type", fmt.Errorf("Unknown Captcha Type: %s", setting.Service.CaptchaType)) + return + } + if err != nil { + log.Debug("%v", err) + } + + if !valid { + ctx.Data["Err_Captcha"] = true + ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tpl, form) + } +} diff --git a/modules/context/context.go b/modules/context/context.go index 4b6a21b217..0fe00bf787 100644 --- a/modules/context/context.go +++ b/modules/context/context.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2020 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. +// SPDX-License-Identifier: MIT package context @@ -34,6 +33,7 @@ import ( "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/templates" "code.gitea.io/gitea/modules/translation" + "code.gitea.io/gitea/modules/typesniffer" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/web/middleware" "code.gitea.io/gitea/services/auth" @@ -139,7 +139,7 @@ func (ctx *Context) IsUserRepoReaderAny() bool { // RedirectToUser redirect to a differently-named user func RedirectToUser(ctx *Context, userName string, redirectUserID int64) { - user, err := user_model.GetUserByID(redirectUserID) + user, err := user_model.GetUserByID(ctx, redirectUserID) if err != nil { ctx.ServerError("GetUserByID", err) return @@ -322,9 +322,9 @@ func (ctx *Context) plainTextInternal(skip, status int, bs []byte) { if statusPrefix == 4 || statusPrefix == 5 { log.Log(skip, log.TRACE, "plainTextInternal (status=%d): %s", status, string(bs)) } - ctx.Resp.WriteHeader(status) ctx.Resp.Header().Set("Content-Type", "text/plain;charset=utf-8") ctx.Resp.Header().Set("X-Content-Type-Options", "nosniff") + ctx.Resp.WriteHeader(status) if _, err := ctx.Resp.Write(bs); err != nil { log.ErrorWithSkip(skip, "plainTextInternal (status=%d): write bytes failed: %v", status, err) } @@ -345,34 +345,61 @@ func (ctx *Context) RespHeader() http.Header { return ctx.Resp.Header() } +type ServeHeaderOptions struct { + ContentType string // defaults to "application/octet-stream" + ContentTypeCharset string + ContentLength *int64 + Disposition string // defaults to "attachment" + Filename string + CacheDuration time.Duration // defaults to 5 minutes + LastModified time.Time +} + // SetServeHeaders sets necessary content serve headers -func (ctx *Context) SetServeHeaders(filename string) { - ctx.Resp.Header().Set("Content-Description", "File Transfer") - ctx.Resp.Header().Set("Content-Type", "application/octet-stream") - ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+filename) - ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary") - ctx.Resp.Header().Set("Expires", "0") - ctx.Resp.Header().Set("Cache-Control", "must-revalidate") - ctx.Resp.Header().Set("Pragma", "public") - ctx.Resp.Header().Set("Access-Control-Expose-Headers", "Content-Disposition") +func (ctx *Context) SetServeHeaders(opts *ServeHeaderOptions) { + header := ctx.Resp.Header() + + contentType := typesniffer.ApplicationOctetStream + if opts.ContentType != "" { + if opts.ContentTypeCharset != "" { + contentType = opts.ContentType + "; charset=" + strings.ToLower(opts.ContentTypeCharset) + } else { + contentType = opts.ContentType + } + } + header.Set("Content-Type", contentType) + header.Set("X-Content-Type-Options", "nosniff") + + if opts.ContentLength != nil { + header.Set("Content-Length", strconv.FormatInt(*opts.ContentLength, 10)) + } + + if opts.Filename != "" { + disposition := opts.Disposition + if disposition == "" { + disposition = "attachment" + } + + backslashEscapedName := strings.ReplaceAll(strings.ReplaceAll(opts.Filename, `\`, `\\`), `"`, `\"`) // \ -> \\, " -> \" + header.Set("Content-Disposition", fmt.Sprintf(`%s; filename="%s"; filename*=UTF-8''%s`, disposition, backslashEscapedName, url.PathEscape(opts.Filename))) + header.Set("Access-Control-Expose-Headers", "Content-Disposition") + } + + duration := opts.CacheDuration + if duration == 0 { + duration = 5 * time.Minute + } + httpcache.AddCacheControlToHeader(header, duration) + + if !opts.LastModified.IsZero() { + header.Set("Last-Modified", opts.LastModified.UTC().Format(http.TimeFormat)) + } } // ServeContent serves content to http request -func (ctx *Context) ServeContent(name string, r io.ReadSeeker, modTime time.Time) { - ctx.SetServeHeaders(name) - http.ServeContent(ctx.Resp, ctx.Req, name, modTime, r) -} - -// ServeFile serves given file to response. -func (ctx *Context) ServeFile(file string, names ...string) { - var name string - if len(names) > 0 { - name = names[0] - } else { - name = path.Base(file) - } - ctx.SetServeHeaders(name) - http.ServeFile(ctx.Resp, ctx.Req, file) +func (ctx *Context) ServeContent(r io.ReadSeeker, opts *ServeHeaderOptions) { + ctx.SetServeHeaders(opts) + http.ServeContent(ctx.Resp, ctx.Req, opts.Filename, opts.LastModified, r) } // UploadStream returns the request body or the first form file diff --git a/modules/context/csrf.go b/modules/context/csrf.go index df775048cb..6639a8b008 100644 --- a/modules/context/csrf.go +++ b/modules/context/csrf.go @@ -13,6 +13,7 @@ // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. +// SPDX-License-Identifier: Apache-2.0 // a middleware that generates and validates CSRF tokens. diff --git a/modules/context/form.go b/modules/context/form.go index 4f48d746b9..f9c4ab6a98 100644 --- a/modules/context/form.go +++ b/modules/context/form.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package context diff --git a/modules/context/org.go b/modules/context/org.go index 89260b8654..39df29a860 100644 --- a/modules/context/org.go +++ b/modules/context/org.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package context diff --git a/modules/context/package.go b/modules/context/package.go index ce0f9a511b..2a55db3a77 100644 --- a/modules/context/package.go +++ b/modules/context/package.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package context @@ -111,7 +110,7 @@ func determineAccessMode(ctx *Context) (perm.AccessMode, error) { return accessMode, err } for _, t := range teams { - perm := t.UnitAccessModeCtx(ctx, unit.TypePackages) + perm := t.UnitAccessMode(ctx, unit.TypePackages) if accessMode < perm { accessMode = perm } diff --git a/modules/context/pagination.go b/modules/context/pagination.go index 617b472f0d..3effd88f10 100644 --- a/modules/context/pagination.go +++ b/modules/context/pagination.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package context diff --git a/modules/context/permission.go b/modules/context/permission.go index fd2263c75f..8cb5d09eb9 100644 --- a/modules/context/permission.go +++ b/modules/context/permission.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package context diff --git a/modules/context/private.go b/modules/context/private.go index 9e7977b5d5..24f50fa471 100644 --- a/modules/context/private.go +++ b/modules/context/private.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package context diff --git a/modules/context/repo.go b/modules/context/repo.go index 1a0263a330..71a2b3c0c6 100644 --- a/modules/context/repo.go +++ b/modules/context/repo.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2017 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. +// SPDX-License-Identifier: MIT package context @@ -164,13 +163,13 @@ func (r *Repository) CanUseTimetracker(issue *issues_model.Issue, user *user_mod // 1. Is timetracker enabled // 2. Is the user a contributor, admin, poster or assignee and do the repository policies require this? isAssigned, _ := issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, user) - return r.Repository.IsTimetrackerEnabled() && (!r.Repository.AllowOnlyContributorsToTrackTime() || + return r.Repository.IsTimetrackerEnabled(db.DefaultContext) && (!r.Repository.AllowOnlyContributorsToTrackTime(db.DefaultContext) || r.Permission.CanWriteIssuesOrPulls(issue.IsPull) || issue.IsPoster(user.ID) || isAssigned) } // CanCreateIssueDependencies returns whether or not a user can create dependencies. func (r *Repository) CanCreateIssueDependencies(user *user_model.User, isPull bool) bool { - return r.Repository.IsDependenciesEnabled() && r.Permission.CanWriteIssuesOrPulls(isPull) + return r.Repository.IsDependenciesEnabled(db.DefaultContext) && r.Permission.CanWriteIssuesOrPulls(isPull) } // GetCommitsCount returns cached commit count for current view @@ -265,7 +264,7 @@ func (r *Repository) GetEditorconfig(optCommit ...*git.Commit) (*editorconfig.Ed // RetrieveBaseRepo retrieves base repository func RetrieveBaseRepo(ctx *Context, repo *repo_model.Repository) { // Non-fork repository will not return error in this method. - if err := repo.GetBaseRepo(); err != nil { + if err := repo.GetBaseRepo(ctx); err != nil { if repo_model.IsErrRepoNotExist(err) { repo.IsFork = false repo.ForkID = 0 @@ -336,7 +335,7 @@ func RedirectToRepo(ctx *Context, redirectRepoID int64) { ownerName := ctx.Params(":username") previousRepoName := ctx.Params(":reponame") - repo, err := repo_model.GetRepositoryByID(redirectRepoID) + repo, err := repo_model.GetRepositoryByID(ctx, redirectRepoID) if err != nil { ctx.ServerError("GetRepositoryByID", err) return @@ -411,7 +410,7 @@ func RepoIDAssignment() func(ctx *Context) { repoID := ctx.ParamsInt64(":repoid") // Get repository. - repo, err := repo_model.GetRepositoryByID(repoID) + repo, err := repo_model.GetRepositoryByID(ctx, repoID) if err != nil { if repo_model.IsErrRepoNotExist(err) { ctx.NotFound("GetRepositoryByID", nil) @@ -441,8 +440,10 @@ func RepoAssignment(ctx *Context) (cancel context.CancelFunc) { userName := ctx.Params(":username") repoName := ctx.Params(":reponame") repoName = strings.TrimSuffix(repoName, ".git") - repoName = strings.TrimSuffix(repoName, ".rss") - repoName = strings.TrimSuffix(repoName, ".atom") + if setting.EnableFeed { + repoName = strings.TrimSuffix(repoName, ".rss") + repoName = strings.TrimSuffix(repoName, ".atom") + } // Check if the user is the same as the repository owner if ctx.IsSigned && ctx.Doer.LowerName == strings.ToLower(userName) { @@ -527,12 +528,12 @@ func RepoAssignment(ctx *Context) (cancel context.CancelFunc) { ctx.Data["RepoLink"] = ctx.Repo.RepoLink ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name - unit, err := ctx.Repo.Repository.GetUnit(unit_model.TypeExternalTracker) + unit, err := ctx.Repo.Repository.GetUnit(ctx, unit_model.TypeExternalTracker) if err == nil { ctx.Data["RepoExternalIssuesLink"] = unit.ExternalTrackerConfig().ExternalTrackerURL } - ctx.Data["NumTags"], err = repo_model.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, repo_model.FindReleasesOptions{ + ctx.Data["NumTags"], err = repo_model.GetReleaseCountByRepoID(ctx, ctx.Repo.Repository.ID, repo_model.FindReleasesOptions{ IncludeDrafts: true, IncludeTags: true, HasSha1: util.OptionalBoolTrue, // only draft releases which are created with existing tags @@ -541,7 +542,7 @@ func RepoAssignment(ctx *Context) (cancel context.CancelFunc) { ctx.ServerError("GetReleaseCountByRepoID", err) return } - ctx.Data["NumReleases"], err = repo_model.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, repo_model.FindReleasesOptions{}) + ctx.Data["NumReleases"], err = repo_model.GetReleaseCountByRepoID(ctx, ctx.Repo.Repository.ID, repo_model.FindReleasesOptions{}) if err != nil { ctx.ServerError("GetReleaseCountByRepoID", err) return @@ -722,13 +723,13 @@ func RepoAssignment(ctx *Context) (cancel context.CancelFunc) { ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest if ctx.Repo.Repository.Status == repo_model.RepositoryPendingTransfer { - repoTransfer, err := models.GetPendingRepositoryTransfer(ctx.Repo.Repository) + repoTransfer, err := models.GetPendingRepositoryTransfer(ctx, ctx.Repo.Repository) if err != nil { ctx.ServerError("GetPendingRepositoryTransfer", err) return } - if err := repoTransfer.LoadAttributes(); err != nil { + if err := repoTransfer.LoadAttributes(ctx); err != nil { ctx.ServerError("LoadRecipient", err) return } @@ -1087,6 +1088,9 @@ func (ctx *Context) IssueTemplatesErrorsFromDefaultBranch() ([]*api.IssueTemplat if it, err := template.UnmarshalFromEntry(entry, dirName); err != nil { invalidFiles[fullName] = err } else { + if !strings.HasPrefix(it.Ref, "refs/") { // Assume that the ref intended is always a branch - for tags users should use refs/tags/ + it.Ref = git.BranchPrefix + it.Ref + } issueTemplates = append(issueTemplates, it) } } diff --git a/modules/context/response.go b/modules/context/response.go index 112964dbe1..40eb5c0d35 100644 --- a/modules/context/response.go +++ b/modules/context/response.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package context diff --git a/modules/context/utils.go b/modules/context/utils.go index a72c8b47e6..1fa99953a2 100644 --- a/modules/context/utils.go +++ b/modules/context/utils.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package context diff --git a/modules/context/xsrf.go b/modules/context/xsrf.go index e3ecc82f6d..15e36d1859 100644 --- a/modules/context/xsrf.go +++ b/modules/context/xsrf.go @@ -13,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. +// SPDX-License-Identifier: Apache-2.0 package context diff --git a/modules/context/xsrf_test.go b/modules/context/xsrf_test.go index ef42d61d5a..21cda5d5d4 100644 --- a/modules/context/xsrf_test.go +++ b/modules/context/xsrf_test.go @@ -13,6 +13,7 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. +// SPDX-License-Identifier: Apache-2.0 package context diff --git a/modules/convert/attachment.go b/modules/convert/attachment.go new file mode 100644 index 0000000000..ddba181a12 --- /dev/null +++ b/modules/convert/attachment.go @@ -0,0 +1,30 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package convert + +import ( + repo_model "code.gitea.io/gitea/models/repo" + api "code.gitea.io/gitea/modules/structs" +) + +// ToAttachment converts models.Attachment to api.Attachment +func ToAttachment(a *repo_model.Attachment) *api.Attachment { + return &api.Attachment{ + ID: a.ID, + Name: a.Name, + Created: a.CreatedUnix.AsTime(), + DownloadCount: a.DownloadCount, + Size: a.Size, + UUID: a.UUID, + DownloadURL: a.DownloadURL(), + } +} + +func ToAttachments(attachments []*repo_model.Attachment) []*api.Attachment { + converted := make([]*api.Attachment, 0, len(attachments)) + for _, attachment := range attachments { + converted = append(converted, ToAttachment(attachment)) + } + return converted +} diff --git a/modules/convert/convert.go b/modules/convert/convert.go index 78eb62d42d..756a1f95d9 100644 --- a/modules/convert/convert.go +++ b/modules/convert/convert.go @@ -1,11 +1,11 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package convert import ( + "context" "fmt" "strconv" "strings" @@ -409,8 +409,8 @@ func ToOAuth2Application(app *auth.OAuth2Application) *api.OAuth2Application { } // ToLFSLock convert a LFSLock to api.LFSLock -func ToLFSLock(l *git_model.LFSLock) *api.LFSLock { - u, err := user_model.GetUserByID(l.OwnerID) +func ToLFSLock(ctx context.Context, l *git_model.LFSLock) *api.LFSLock { + u, err := user_model.GetUserByID(ctx, l.OwnerID) if err != nil { return nil } diff --git a/modules/convert/git_commit.go b/modules/convert/git_commit.go index 6015a73712..59842e4020 100644 --- a/modules/convert/git_commit.go +++ b/modules/convert/git_commit.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert diff --git a/modules/convert/git_commit_test.go b/modules/convert/git_commit_test.go index 0bba0e502e..8c4ef88ebe 100644 --- a/modules/convert/git_commit_test.go +++ b/modules/convert/git_commit_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert diff --git a/modules/convert/issue.go b/modules/convert/issue.go index 5364367a80..f3af03ed94 100644 --- a/modules/convert/issue.go +++ b/modules/convert/issue.go @@ -1,10 +1,10 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert import ( + "context" "fmt" "net/url" "strings" @@ -22,35 +22,36 @@ import ( // it assumes some fields assigned with values: // Required - Poster, Labels, // Optional - Milestone, Assignee, PullRequest -func ToAPIIssue(issue *issues_model.Issue) *api.Issue { - if err := issue.LoadLabels(db.DefaultContext); err != nil { +func ToAPIIssue(ctx context.Context, issue *issues_model.Issue) *api.Issue { + if err := issue.LoadLabels(ctx); err != nil { return &api.Issue{} } - if err := issue.LoadPoster(); err != nil { + if err := issue.LoadPoster(ctx); err != nil { return &api.Issue{} } - if err := issue.LoadRepo(db.DefaultContext); err != nil { + if err := issue.LoadRepo(ctx); err != nil { return &api.Issue{} } - if err := issue.Repo.GetOwner(db.DefaultContext); err != nil { + if err := issue.Repo.GetOwner(ctx); err != nil { return &api.Issue{} } apiIssue := &api.Issue{ - ID: issue.ID, - URL: issue.APIURL(), - HTMLURL: issue.HTMLURL(), - Index: issue.Index, - Poster: ToUser(issue.Poster, nil), - Title: issue.Title, - Body: issue.Content, - Ref: issue.Ref, - Labels: ToLabelList(issue.Labels, issue.Repo, issue.Repo.Owner), - State: issue.State(), - IsLocked: issue.IsLocked, - Comments: issue.NumComments, - Created: issue.CreatedUnix.AsTime(), - Updated: issue.UpdatedUnix.AsTime(), + ID: issue.ID, + URL: issue.APIURL(), + HTMLURL: issue.HTMLURL(), + Index: issue.Index, + Poster: ToUser(issue.Poster, nil), + Title: issue.Title, + Body: issue.Content, + Attachments: ToAttachments(issue.Attachments), + Ref: issue.Ref, + Labels: ToLabelList(issue.Labels, issue.Repo, issue.Repo.Owner), + State: issue.State(), + IsLocked: issue.IsLocked, + Comments: issue.NumComments, + Created: issue.CreatedUnix.AsTime(), + Updated: issue.UpdatedUnix.AsTime(), } apiIssue.Repo = &api.RepositoryMeta{ @@ -64,14 +65,14 @@ func ToAPIIssue(issue *issues_model.Issue) *api.Issue { apiIssue.Closed = issue.ClosedUnix.AsTimePtr() } - if err := issue.LoadMilestone(); err != nil { + if err := issue.LoadMilestone(ctx); err != nil { return &api.Issue{} } if issue.Milestone != nil { apiIssue.Milestone = ToAPIMilestone(issue.Milestone) } - if err := issue.LoadAssignees(db.DefaultContext); err != nil { + if err := issue.LoadAssignees(ctx); err != nil { return &api.Issue{} } if len(issue.Assignees) > 0 { @@ -81,7 +82,7 @@ func ToAPIIssue(issue *issues_model.Issue) *api.Issue { apiIssue.Assignee = ToUser(issue.Assignees[0], nil) // For compatibility, we're keeping the first assignee as `apiIssue.Assignee` } if issue.IsPull { - if err := issue.LoadPullRequest(); err != nil { + if err := issue.LoadPullRequest(ctx); err != nil { return &api.Issue{} } apiIssue.PullRequest = &api.PullRequestMeta{ @@ -99,26 +100,25 @@ func ToAPIIssue(issue *issues_model.Issue) *api.Issue { } // ToAPIIssueList converts an IssueList to API format -func ToAPIIssueList(il issues_model.IssueList) []*api.Issue { +func ToAPIIssueList(ctx context.Context, il issues_model.IssueList) []*api.Issue { result := make([]*api.Issue, len(il)) for i := range il { - result[i] = ToAPIIssue(il[i]) + result[i] = ToAPIIssue(ctx, il[i]) } return result } // ToTrackedTime converts TrackedTime to API format -func ToTrackedTime(t *issues_model.TrackedTime) (apiT *api.TrackedTime) { +func ToTrackedTime(ctx context.Context, t *issues_model.TrackedTime) (apiT *api.TrackedTime) { apiT = &api.TrackedTime{ - ID: t.ID, - IssueID: t.IssueID, - UserID: t.UserID, - UserName: t.User.Name, - Time: t.Time, - Created: t.Created, + ID: t.ID, + IssueID: t.IssueID, + UserID: t.UserID, + Time: t.Time, + Created: t.Created, } if t.Issue != nil { - apiT.Issue = ToAPIIssue(t.Issue) + apiT.Issue = ToAPIIssue(ctx, t.Issue) } if t.User != nil { apiT.UserName = t.User.Name @@ -149,7 +149,7 @@ func ToStopWatches(sws []*issues_model.Stopwatch) (api.StopWatches, error) { } repo, ok = repoCache[issue.RepoID] if !ok { - repo, err = repo_model.GetRepositoryByID(issue.RepoID) + repo, err = repo_model.GetRepositoryByID(db.DefaultContext, issue.RepoID) if err != nil { return nil, err } @@ -169,10 +169,10 @@ func ToStopWatches(sws []*issues_model.Stopwatch) (api.StopWatches, error) { } // ToTrackedTimeList converts TrackedTimeList to API format -func ToTrackedTimeList(tl issues_model.TrackedTimeList) api.TrackedTimeList { +func ToTrackedTimeList(ctx context.Context, tl issues_model.TrackedTimeList) api.TrackedTimeList { result := make([]*api.TrackedTime, 0, len(tl)) for _, t := range tl { - result = append(result, ToTrackedTime(t)) + result = append(result, ToTrackedTime(ctx, t)) } return result } diff --git a/modules/convert/issue_comment.go b/modules/convert/issue_comment.go index 73ad345fa4..6044cbcf61 100644 --- a/modules/convert/issue_comment.go +++ b/modules/convert/issue_comment.go @@ -1,11 +1,11 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert import ( - "code.gitea.io/gitea/models/db" + "context" + issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" @@ -16,20 +16,21 @@ import ( // ToComment converts a issues_model.Comment to the api.Comment format func ToComment(c *issues_model.Comment) *api.Comment { return &api.Comment{ - ID: c.ID, - Poster: ToUser(c.Poster, nil), - HTMLURL: c.HTMLURL(), - IssueURL: c.IssueURL(), - PRURL: c.PRURL(), - Body: c.Content, - Created: c.CreatedUnix.AsTime(), - Updated: c.UpdatedUnix.AsTime(), + ID: c.ID, + Poster: ToUser(c.Poster, nil), + HTMLURL: c.HTMLURL(), + IssueURL: c.IssueURL(), + PRURL: c.PRURL(), + Body: c.Content, + Attachments: ToAttachments(c.Attachments), + Created: c.CreatedUnix.AsTime(), + Updated: c.UpdatedUnix.AsTime(), } } // ToTimelineComment converts a issues_model.Comment to the api.TimelineComment format -func ToTimelineComment(c *issues_model.Comment, doer *user_model.User) *api.TimelineComment { - err := c.LoadMilestone() +func ToTimelineComment(ctx context.Context, c *issues_model.Comment, doer *user_model.User) *api.TimelineComment { + err := c.LoadMilestone(ctx) if err != nil { log.Error("LoadMilestone: %v", err) return nil @@ -107,25 +108,25 @@ func ToTimelineComment(c *issues_model.Comment, doer *user_model.User) *api.Time return nil } - comment.TrackedTime = ToTrackedTime(c.Time) + comment.TrackedTime = ToTrackedTime(ctx, c.Time) } if c.RefIssueID != 0 { - issue, err := issues_model.GetIssueByID(db.DefaultContext, c.RefIssueID) + issue, err := issues_model.GetIssueByID(ctx, c.RefIssueID) if err != nil { log.Error("GetIssueByID(%d): %v", c.RefIssueID, err) return nil } - comment.RefIssue = ToAPIIssue(issue) + comment.RefIssue = ToAPIIssue(ctx, issue) } if c.RefCommentID != 0 { - com, err := issues_model.GetCommentByID(db.DefaultContext, c.RefCommentID) + com, err := issues_model.GetCommentByID(ctx, c.RefCommentID) if err != nil { log.Error("GetCommentByID(%d): %v", c.RefCommentID, err) return nil } - err = com.LoadPoster() + err = com.LoadPoster(ctx) if err != nil { log.Error("LoadPoster: %v", err) return nil @@ -138,7 +139,7 @@ func ToTimelineComment(c *issues_model.Comment, doer *user_model.User) *api.Time var repo *repo_model.Repository if c.Label.BelongsToOrg() { var err error - org, err = user_model.GetUserByID(c.Label.OrgID) + org, err = user_model.GetUserByID(ctx, c.Label.OrgID) if err != nil { log.Error("GetUserByID(%d): %v", c.Label.OrgID, err) return nil @@ -146,7 +147,7 @@ func ToTimelineComment(c *issues_model.Comment, doer *user_model.User) *api.Time } if c.Label.BelongsToRepo() { var err error - repo, err = repo_model.GetRepositoryByID(c.Label.RepoID) + repo, err = repo_model.GetRepositoryByID(ctx, c.Label.RepoID) if err != nil { log.Error("GetRepositoryByID(%d): %v", c.Label.RepoID, err) return nil @@ -167,7 +168,7 @@ func ToTimelineComment(c *issues_model.Comment, doer *user_model.User) *api.Time } if c.DependentIssue != nil { - comment.DependentIssue = ToAPIIssue(c.DependentIssue) + comment.DependentIssue = ToAPIIssue(ctx, c.DependentIssue) } return comment diff --git a/modules/convert/issue_test.go b/modules/convert/issue_test.go index ec672abad2..4d780f3f00 100644 --- a/modules/convert/issue_test.go +++ b/modules/convert/issue_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert diff --git a/modules/convert/main_test.go b/modules/convert/main_test.go index 84f16b9af3..4c8e57bf79 100644 --- a/modules/convert/main_test.go +++ b/modules/convert/main_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert diff --git a/modules/convert/mirror.go b/modules/convert/mirror.go index b2414f4677..1dcfc9b64d 100644 --- a/modules/convert/mirror.go +++ b/modules/convert/mirror.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package convert diff --git a/modules/convert/notification.go b/modules/convert/notification.go index 55f782f8f6..5d3b078a25 100644 --- a/modules/convert/notification.go +++ b/modules/convert/notification.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert @@ -8,6 +7,7 @@ import ( "net/url" activities_model "code.gitea.io/gitea/models/activities" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/perm" api "code.gitea.io/gitea/modules/structs" ) @@ -24,7 +24,7 @@ func ToNotificationThread(n *activities_model.Notification) *api.NotificationThr // 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) + result.Repository = ToRepo(db.DefaultContext, n.Repository, perm.AccessModeRead) // This permission is not correct and we should not be reporting it for repository := result.Repository; repository != nil; repository = repository.Parent { diff --git a/modules/convert/package.go b/modules/convert/package.go index 9713cda48b..68ae6f4e62 100644 --- a/modules/convert/package.go +++ b/modules/convert/package.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package convert @@ -23,7 +22,7 @@ func ToPackage(ctx context.Context, pd *packages.PackageDescriptor, doer *user_m } if permission.HasAccess() { - repo = ToRepo(pd.Repository, permission.AccessMode) + repo = ToRepo(ctx, pd.Repository, permission.AccessMode) } } diff --git a/modules/convert/pull.go b/modules/convert/pull.go index 9c31f9bd2c..db0add6cde 100644 --- a/modules/convert/pull.go +++ b/modules/convert/pull.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert @@ -33,13 +32,13 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u return nil } - apiIssue := ToAPIIssue(pr.Issue) - if err := pr.LoadBaseRepoCtx(ctx); err != nil { + apiIssue := ToAPIIssue(ctx, pr.Issue) + if err := pr.LoadBaseRepo(ctx); err != nil { log.Error("GetRepositoryById[%d]: %v", pr.ID, err) return nil } - if err := pr.LoadHeadRepoCtx(ctx); err != nil { + if err := pr.LoadHeadRepo(ctx); err != nil { log.Error("GetRepositoryById[%d]: %v", pr.ID, err) return nil } @@ -80,7 +79,7 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u Name: pr.BaseBranch, Ref: pr.BaseBranch, RepoID: pr.BaseRepoID, - Repository: ToRepo(pr.BaseRepo, p.AccessMode), + Repository: ToRepo(ctx, pr.BaseRepo, p.AccessMode), }, Head: &api.PRBranchInfo{ Name: pr.HeadBranch, @@ -140,7 +139,7 @@ func ToAPIPullRequest(ctx context.Context, pr *issues_model.PullRequest, doer *u } apiPullRequest.Head.RepoID = pr.HeadRepo.ID - apiPullRequest.Head.Repository = ToRepo(pr.HeadRepo, p.AccessMode) + apiPullRequest.Head.Repository = ToRepo(ctx, pr.HeadRepo, p.AccessMode) headGitRepo, err := git.OpenRepository(ctx, pr.HeadRepo.RepoPath()) if err != nil { diff --git a/modules/convert/pull_review.go b/modules/convert/pull_review.go index 93ce208224..66c5018ee2 100644 --- a/modules/convert/pull_review.go +++ b/modules/convert/pull_review.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert @@ -39,6 +38,7 @@ func ToPullReview(ctx context.Context, r *issues_model.Review, doer *user_model. Dismissed: r.Dismissed, CodeCommentsCount: r.GetCodeCommentsCount(), Submitted: r.CreatedUnix.AsTime(), + Updated: r.UpdatedUnix.AsTime(), HTMLURL: r.HTMLURL(), HTMLPullURL: r.Issue.HTMLURL(), } diff --git a/modules/convert/pull_test.go b/modules/convert/pull_test.go index a6ccbaca58..0915d096e6 100644 --- a/modules/convert/pull_test.go +++ b/modules/convert/pull_test.go @@ -1,12 +1,12 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert import ( "testing" + "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/perm" repo_model "code.gitea.io/gitea/models/repo" @@ -22,8 +22,8 @@ func TestPullRequest_APIFormat(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) headRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) - assert.NoError(t, pr.LoadAttributes()) - assert.NoError(t, pr.LoadIssue()) + assert.NoError(t, pr.LoadAttributes(db.DefaultContext)) + assert.NoError(t, pr.LoadIssue(db.DefaultContext)) apiPullRequest := ToAPIPullRequest(git.DefaultContext, pr, nil) assert.NotNil(t, apiPullRequest) assert.EqualValues(t, &structs.PRBranchInfo{ @@ -31,13 +31,13 @@ func TestPullRequest_APIFormat(t *testing.T) { Ref: "refs/pull/2/head", Sha: "4a357436d925b5c974181ff12a994538ddc5a269", RepoID: 1, - Repository: ToRepo(headRepo, perm.AccessModeRead), + Repository: ToRepo(db.DefaultContext, headRepo, perm.AccessModeRead), }, apiPullRequest.Head) // withOut HeadRepo pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) - assert.NoError(t, pr.LoadIssue()) - assert.NoError(t, pr.LoadAttributes()) + assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + assert.NoError(t, pr.LoadAttributes(db.DefaultContext)) // simulate fork deletion pr.HeadRepo = nil pr.HeadRepoID = 100000 diff --git a/modules/convert/release.go b/modules/convert/release.go index 5fc95dab72..3afa53c03f 100644 --- a/modules/convert/release.go +++ b/modules/convert/release.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert @@ -11,10 +10,6 @@ import ( // ToRelease convert a repo_model.Release to api.Release func ToRelease(r *repo_model.Release) *api.Release { - assets := make([]*api.Attachment, 0) - for _, att := range r.Attachments { - assets = append(assets, ToReleaseAttachment(att)) - } return &api.Release{ ID: r.ID, TagName: r.TagName, @@ -30,19 +25,6 @@ func ToRelease(r *repo_model.Release) *api.Release { CreatedAt: r.CreatedUnix.AsTime(), PublishedAt: r.CreatedUnix.AsTime(), Publisher: ToUser(r.Publisher, nil), - Attachments: assets, - } -} - -// ToReleaseAttachment converts models.Attachment to api.Attachment -func ToReleaseAttachment(a *repo_model.Attachment) *api.Attachment { - return &api.Attachment{ - ID: a.ID, - Name: a.Name, - Created: a.CreatedUnix.AsTime(), - DownloadCount: a.DownloadCount, - Size: a.Size, - UUID: a.UUID, - DownloadURL: a.DownloadURL(), + Attachments: ToAttachments(r.Attachments), } } diff --git a/modules/convert/repository.go b/modules/convert/repository.go index 09b84afa6c..ce53a66692 100644 --- a/modules/convert/repository.go +++ b/modules/convert/repository.go @@ -1,14 +1,13 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert import ( + "context" "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/perm" repo_model "code.gitea.io/gitea/models/repo" unit_model "code.gitea.io/gitea/models/unit" @@ -17,11 +16,11 @@ import ( ) // ToRepo converts a Repository to api.Repository -func ToRepo(repo *repo_model.Repository, mode perm.AccessMode) *api.Repository { - return innerToRepo(repo, mode, false) +func ToRepo(ctx context.Context, repo *repo_model.Repository, mode perm.AccessMode) *api.Repository { + return innerToRepo(ctx, repo, mode, false) } -func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent bool) *api.Repository { +func innerToRepo(ctx context.Context, repo *repo_model.Repository, mode perm.AccessMode, isParent bool) *api.Repository { var parent *api.Repository cloneLink := repo.CloneLink() @@ -31,12 +30,12 @@ func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent boo Pull: mode >= perm.AccessModeRead, } if !isParent { - err := repo.GetBaseRepo() + err := repo.GetBaseRepo(ctx) if err != nil { return nil } if repo.BaseRepo != nil { - parent = innerToRepo(repo.BaseRepo, mode, true) + parent = innerToRepo(ctx, repo.BaseRepo, mode, true) } } @@ -44,7 +43,7 @@ func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent boo hasIssues := false var externalTracker *api.ExternalTracker var internalTracker *api.InternalTracker - if unit, err := repo.GetUnit(unit_model.TypeIssues); err == nil { + if unit, err := repo.GetUnit(ctx, unit_model.TypeIssues); err == nil { config := unit.IssuesConfig() hasIssues = true internalTracker = &api.InternalTracker{ @@ -52,7 +51,7 @@ func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent boo AllowOnlyContributorsToTrackTime: config.AllowOnlyContributorsToTrackTime, EnableIssueDependencies: config.EnableDependencies, } - } else if unit, err := repo.GetUnit(unit_model.TypeExternalTracker); err == nil { + } else if unit, err := repo.GetUnit(ctx, unit_model.TypeExternalTracker); err == nil { config := unit.ExternalTrackerConfig() hasIssues = true externalTracker = &api.ExternalTracker{ @@ -64,9 +63,9 @@ func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent boo } hasWiki := false var externalWiki *api.ExternalWiki - if _, err := repo.GetUnit(unit_model.TypeWiki); err == nil { + if _, err := repo.GetUnit(ctx, unit_model.TypeWiki); err == nil { hasWiki = true - } else if unit, err := repo.GetUnit(unit_model.TypeExternalWiki); err == nil { + } else if unit, err := repo.GetUnit(ctx, unit_model.TypeExternalWiki); err == nil { hasWiki = true config := unit.ExternalWikiConfig() externalWiki = &api.ExternalWiki{ @@ -82,7 +81,7 @@ func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent boo allowRebaseUpdate := false defaultDeleteBranchAfterMerge := false defaultMergeStyle := repo_model.MergeStyleMerge - if unit, err := repo.GetUnit(unit_model.TypePullRequests); err == nil { + if unit, err := repo.GetUnit(ctx, unit_model.TypePullRequests); err == nil { config := unit.PullRequestsConfig() hasPullRequests = true ignoreWhitespaceConflicts = config.IgnoreWhitespaceConflicts @@ -95,21 +94,21 @@ func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent boo defaultMergeStyle = config.GetDefaultMergeStyle() } hasProjects := false - if _, err := repo.GetUnit(unit_model.TypeProjects); err == nil { + if _, err := repo.GetUnit(ctx, unit_model.TypeProjects); err == nil { hasProjects = true } - if err := repo.GetOwner(db.DefaultContext); err != nil { + if err := repo.GetOwner(ctx); err != nil { return nil } - numReleases, _ := repo_model.GetReleaseCountByRepoID(repo.ID, repo_model.FindReleasesOptions{IncludeDrafts: false, IncludeTags: false}) + numReleases, _ := repo_model.GetReleaseCountByRepoID(ctx, repo.ID, repo_model.FindReleasesOptions{IncludeDrafts: false, IncludeTags: false}) mirrorInterval := "" var mirrorUpdated time.Time if repo.IsMirror { var err error - repo.Mirror, err = repo_model.GetMirrorByRepoID(db.DefaultContext, repo.ID) + repo.Mirror, err = repo_model.GetMirrorByRepoID(ctx, repo.ID) if err == nil { mirrorInterval = repo.Mirror.Interval.String() mirrorUpdated = repo.Mirror.UpdatedUnix.AsTime() @@ -118,11 +117,11 @@ func innerToRepo(repo *repo_model.Repository, mode perm.AccessMode, isParent boo var transfer *api.RepoTransfer if repo.Status == repo_model.RepositoryPendingTransfer { - t, err := models.GetPendingRepositoryTransfer(repo) + t, err := models.GetPendingRepositoryTransfer(ctx, repo) if err != nil && !models.IsErrNoPendingTransfer(err) { log.Warn("GetPendingRepositoryTransfer: %v", err) } else { - if err := t.LoadAttributes(); err != nil { + if err := t.LoadAttributes(ctx); err != nil { log.Warn("LoadAttributes of RepoTransfer: %v", err) } else { transfer = ToRepoTransfer(t) diff --git a/modules/convert/status.go b/modules/convert/status.go index 7ed28a9c10..5fcf04074f 100644 --- a/modules/convert/status.go +++ b/modules/convert/status.go @@ -1,17 +1,18 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert import ( + "context" + git_model "code.gitea.io/gitea/models/git" user_model "code.gitea.io/gitea/models/user" api "code.gitea.io/gitea/modules/structs" ) // ToCommitStatus converts git_model.CommitStatus to api.CommitStatus -func ToCommitStatus(status *git_model.CommitStatus) *api.CommitStatus { +func ToCommitStatus(ctx context.Context, status *git_model.CommitStatus) *api.CommitStatus { apiStatus := &api.CommitStatus{ Created: status.CreatedUnix.AsTime(), Updated: status.CreatedUnix.AsTime(), @@ -24,7 +25,7 @@ func ToCommitStatus(status *git_model.CommitStatus) *api.CommitStatus { } if status.CreatorID != 0 { - creator, _ := user_model.GetUserByID(status.CreatorID) + creator, _ := user_model.GetUserByID(ctx, status.CreatorID) apiStatus.Creator = ToUser(creator, nil) } @@ -32,7 +33,7 @@ func ToCommitStatus(status *git_model.CommitStatus) *api.CommitStatus { } // ToCombinedStatus converts List of CommitStatus to a CombinedStatus -func ToCombinedStatus(statuses []*git_model.CommitStatus, repo *api.Repository) *api.CombinedStatus { +func ToCombinedStatus(ctx context.Context, statuses []*git_model.CommitStatus, repo *api.Repository) *api.CombinedStatus { if len(statuses) == 0 { return nil } @@ -46,7 +47,7 @@ func ToCombinedStatus(statuses []*git_model.CommitStatus, repo *api.Repository) retStatus.Statuses = make([]*api.CommitStatus, 0, len(statuses)) for _, status := range statuses { - retStatus.Statuses = append(retStatus.Statuses, ToCommitStatus(status)) + retStatus.Statuses = append(retStatus.Statuses, ToCommitStatus(ctx, status)) if status.State.NoBetterThan(retStatus.State) { retStatus.State = status.State } diff --git a/modules/convert/user.go b/modules/convert/user.go index 093994856c..6b90539fd9 100644 --- a/modules/convert/user.go +++ b/modules/convert/user.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert diff --git a/modules/convert/user_test.go b/modules/convert/user_test.go index 89d912e460..c3ab4187b7 100644 --- a/modules/convert/user_test.go +++ b/modules/convert/user_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package convert diff --git a/modules/convert/utils.go b/modules/convert/utils.go index 52fbcf547f..cdce60831c 100644 --- a/modules/convert/utils.go +++ b/modules/convert/utils.go @@ -1,7 +1,6 @@ // Copyright 2020 The Gitea Authors. All rights reserved. // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package convert diff --git a/modules/convert/utils_test.go b/modules/convert/utils_test.go index e0ab15dfd8..d1ec5980ce 100644 --- a/modules/convert/utils_test.go +++ b/modules/convert/utils_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package convert diff --git a/modules/convert/wiki.go b/modules/convert/wiki.go index 1112da43f8..20d76162c7 100644 --- a/modules/convert/wiki.go +++ b/modules/convert/wiki.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package convert diff --git a/modules/csv/csv.go b/modules/csv/csv.go index fe0c350960..c5497befe7 100644 --- a/modules/csv/csv.go +++ b/modules/csv/csv.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package csv diff --git a/modules/csv/csv_test.go b/modules/csv/csv_test.go index 5a8e13c811..c627597fa3 100644 --- a/modules/csv/csv_test.go +++ b/modules/csv/csv_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package csv diff --git a/modules/doctor/authorizedkeys.go b/modules/doctor/authorizedkeys.go index b3e9699a02..e4d85c4a18 100644 --- a/modules/doctor/authorizedkeys.go +++ b/modules/doctor/authorizedkeys.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package doctor diff --git a/modules/doctor/breaking.go b/modules/doctor/breaking.go index 474997acd8..77e3d4e8ef 100644 --- a/modules/doctor/breaking.go +++ b/modules/doctor/breaking.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package doctor diff --git a/modules/doctor/checkOldArchives.go b/modules/doctor/checkOldArchives.go index cefb3817bf..390dfb43aa 100644 --- a/modules/doctor/checkOldArchives.go +++ b/modules/doctor/checkOldArchives.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package doctor diff --git a/modules/doctor/dbconsistency.go b/modules/doctor/dbconsistency.go index 7ae349908e..bb560ac6a3 100644 --- a/modules/doctor/dbconsistency.go +++ b/modules/doctor/dbconsistency.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package doctor @@ -18,13 +17,13 @@ import ( type consistencyCheck struct { Name string - Counter func() (int64, error) - Fixer func() (int64, error) + Counter func(context.Context) (int64, error) + Fixer func(context.Context) (int64, error) FixedMessage string } func (c *consistencyCheck) Run(ctx context.Context, logger log.Logger, autofix bool) error { - count, err := c.Counter() + count, err := c.Counter(ctx) if err != nil { logger.Critical("Error: %v whilst counting %s", err, c.Name) return err @@ -32,7 +31,7 @@ func (c *consistencyCheck) Run(ctx context.Context, logger log.Logger, autofix b if count > 0 { if autofix { var fixed int64 - if fixed, err = c.Fixer(); err != nil { + if fixed, err = c.Fixer(ctx); err != nil { logger.Critical("Error: %v whilst fixing %s", err, c.Name) return err } @@ -54,9 +53,9 @@ func (c *consistencyCheck) Run(ctx context.Context, logger log.Logger, autofix b return nil } -func asFixer(fn func() error) func() (int64, error) { - return func() (int64, error) { - err := fn() +func asFixer(fn func(ctx context.Context) error) func(ctx context.Context) (int64, error) { + return func(ctx context.Context) (int64, error) { + err := fn(ctx) return -1, err } } @@ -64,11 +63,11 @@ func asFixer(fn func() error) func() (int64, error) { func genericOrphanCheck(name, subject, refobject, joincond string) consistencyCheck { return consistencyCheck{ Name: name, - Counter: func() (int64, error) { - return db.CountOrphanedObjects(subject, refobject, joincond) + Counter: func(ctx context.Context) (int64, error) { + return db.CountOrphanedObjects(ctx, subject, refobject, joincond) }, - Fixer: func() (int64, error) { - err := db.DeleteOrphanedObjects(subject, refobject, joincond) + Fixer: func(ctx context.Context) (int64, error) { + err := db.DeleteOrphanedObjects(ctx, subject, refobject, joincond) return -1, err }, } @@ -205,6 +204,9 @@ func checkDBConsistency(ctx context.Context, logger log.Logger, autofix bool) er // find stopwatches without existing issue genericOrphanCheck("Orphaned Stopwatches without existing Issue", "stopwatch", "issue", "stopwatch.issue_id=`issue`.id"), + // find redirects without existing user. + genericOrphanCheck("Orphaned Redirects without existing redirect user", + "user_redirect", "user", "user_redirect.redirect_user_id=`user`.id"), ) for _, c := range consistencyChecks { diff --git a/modules/doctor/dbversion.go b/modules/doctor/dbversion.go index 8afd9f44fd..2b20cb2340 100644 --- a/modules/doctor/dbversion.go +++ b/modules/doctor/dbversion.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package doctor @@ -13,6 +12,7 @@ import ( ) func checkDBVersion(ctx context.Context, logger log.Logger, autofix bool) error { + logger.Info("Expected database version: %d", migrations.ExpectedVersion()) if err := db.InitEngineWithMigration(ctx, migrations.EnsureUpToDate); err != nil { if !autofix { logger.Critical("Error: %v during ensure up to date", err) diff --git a/modules/doctor/doctor.go b/modules/doctor/doctor.go index 5d14cef55c..2025edc58d 100644 --- a/modules/doctor/doctor.go +++ b/modules/doctor/doctor.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package doctor diff --git a/modules/doctor/fix16961.go b/modules/doctor/fix16961.go index d9f895739f..ea14a9b2c4 100644 --- a/modules/doctor/fix16961.go +++ b/modules/doctor/fix16961.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package doctor diff --git a/modules/doctor/fix16961_test.go b/modules/doctor/fix16961_test.go index f5e5667c09..498ed9c8d5 100644 --- a/modules/doctor/fix16961_test.go +++ b/modules/doctor/fix16961_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package doctor diff --git a/modules/doctor/heads.go b/modules/doctor/heads.go index 33efc27a22..41fca01d57 100644 --- a/modules/doctor/heads.go +++ b/modules/doctor/heads.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package doctor @@ -19,11 +18,9 @@ func synchronizeRepoHeads(ctx context.Context, logger log.Logger, autofix bool) numReposUpdated := 0 err := iterateRepositories(ctx, func(repo *repo_model.Repository) error { numRepos++ - runOpts := &git.RunOpts{Dir: repo.RepoPath()} + _, _, defaultBranchErr := git.NewCommand(ctx, "rev-parse").AddDashesAndList(repo.DefaultBranch).RunStdString(&git.RunOpts{Dir: repo.RepoPath()}) - _, _, defaultBranchErr := git.NewCommand(ctx, "rev-parse").AddDashesAndList(repo.DefaultBranch).RunStdString(runOpts) - - head, _, headErr := git.NewCommand(ctx, "symbolic-ref", "--short", "HEAD").RunStdString(runOpts) + head, _, headErr := git.NewCommand(ctx, "symbolic-ref", "--short", "HEAD").RunStdString(&git.RunOpts{Dir: repo.RepoPath()}) // what we expect: default branch is valid, and HEAD points to it if headErr == nil && defaultBranchErr == nil && head == repo.DefaultBranch { @@ -49,7 +46,7 @@ func synchronizeRepoHeads(ctx context.Context, logger log.Logger, autofix bool) } // otherwise, let's try fixing HEAD - err := git.NewCommand(ctx, "symbolic-ref").AddDashesAndList("HEAD", git.BranchPrefix+repo.DefaultBranch).Run(runOpts) + err := git.NewCommand(ctx, "symbolic-ref").AddDashesAndList("HEAD", git.BranchPrefix+repo.DefaultBranch).Run(&git.RunOpts{Dir: repo.RepoPath()}) if err != nil { logger.Warn("Failed to fix HEAD for %s/%s: %v", repo.OwnerName, repo.Name, err) return nil @@ -65,7 +62,7 @@ func synchronizeRepoHeads(ctx context.Context, logger log.Logger, autofix bool) logger.Info("Out of %d repos, HEADs for %d are now fixed and HEADS for %d are still broken", numRepos, numReposUpdated, numDefaultBranchesBroken+numHeadsBroken-numReposUpdated) } else { if numHeadsBroken == 0 && numDefaultBranchesBroken == 0 { - logger.Info("All %d repos have their HEADs in the correct state") + logger.Info("All %d repos have their HEADs in the correct state", numRepos) } else { if numHeadsBroken == 0 && numDefaultBranchesBroken != 0 { logger.Critical("Default branches are broken for %d/%d repos", numDefaultBranchesBroken, numRepos) diff --git a/modules/doctor/lfs.go b/modules/doctor/lfs.go new file mode 100644 index 0000000000..410ed5a9a5 --- /dev/null +++ b/modules/doctor/lfs.go @@ -0,0 +1,37 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package doctor + +import ( + "context" + "fmt" + + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/services/repository" +) + +func init() { + Register(&Check{ + Title: "Garbage collect LFS", + Name: "gc-lfs", + IsDefault: false, + Run: garbageCollectLFSCheck, + AbortIfFailed: false, + SkipDatabaseInitialization: false, + Priority: 1, + }) +} + +func garbageCollectLFSCheck(ctx context.Context, logger log.Logger, autofix bool) error { + if !setting.LFS.StartServer { + return fmt.Errorf("LFS support is disabled") + } + + if err := repository.GarbageCollectLFSMetaObjects(ctx, logger, autofix); err != nil { + return err + } + + return checkStorage(&checkStorageOptions{LFS: true})(ctx, logger, autofix) +} diff --git a/modules/doctor/mergebase.go b/modules/doctor/mergebase.go index 9f5e336461..e79369e581 100644 --- a/modules/doctor/mergebase.go +++ b/modules/doctor/mergebase.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package doctor diff --git a/modules/doctor/misc.go b/modules/doctor/misc.go index 6f0e066f54..73df513901 100644 --- a/modules/doctor/misc.go +++ b/modules/doctor/misc.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package doctor diff --git a/modules/doctor/paths.go b/modules/doctor/paths.go index 5a27045457..ad50078d3e 100644 --- a/modules/doctor/paths.go +++ b/modules/doctor/paths.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package doctor diff --git a/modules/doctor/storage.go b/modules/doctor/storage.go index dafd989cf0..aa987de447 100644 --- a/modules/doctor/storage.go +++ b/modules/doctor/storage.go @@ -1,76 +1,259 @@ // 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. +// SPDX-License-Identifier: MIT package doctor import ( "context" + "errors" + "io/fs" + "strings" - repo_model "code.gitea.io/gitea/models/repo" + "code.gitea.io/gitea/models/git" + "code.gitea.io/gitea/models/packages" + "code.gitea.io/gitea/models/repo" + "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/log" + packages_module "code.gitea.io/gitea/modules/packages" "code.gitea.io/gitea/modules/storage" + "code.gitea.io/gitea/modules/util" ) -func checkAttachmentStorageFiles(logger log.Logger, autofix bool) error { - var total, garbageNum int - var deletePaths []string - if err := storage.Attachments.IterateObjects(func(p string, obj storage.Object) error { +type commonStorageCheckOptions struct { + storer storage.ObjectStorage + isOrphaned func(path string, obj storage.Object, stat fs.FileInfo) (bool, error) + name string +} + +func commonCheckStorage(ctx context.Context, logger log.Logger, autofix bool, opts *commonStorageCheckOptions) error { + totalCount, orphanedCount := 0, 0 + totalSize, orphanedSize := int64(0), int64(0) + + var pathsToDelete []string + if err := opts.storer.IterateObjects(func(p string, obj storage.Object) error { defer obj.Close() - total++ + totalCount++ stat, err := obj.Stat() if err != nil { return err } - exist, err := repo_model.ExistAttachmentsByUUID(stat.Name()) + totalSize += stat.Size() + + orphaned, err := opts.isOrphaned(p, obj, stat) if err != nil { return err } - if !exist { - garbageNum++ + if orphaned { + orphanedCount++ + orphanedSize += stat.Size() if autofix { - deletePaths = append(deletePaths, p) + pathsToDelete = append(pathsToDelete, p) } } return nil }); err != nil { - logger.Error("storage.Attachments.IterateObjects failed: %v", err) + logger.Error("Error whilst iterating %s storage: %v", opts.name, err) return err } - if garbageNum > 0 { + if orphanedCount > 0 { if autofix { var deletedNum int - for _, p := range deletePaths { - if err := storage.Attachments.Delete(p); err != nil { - log.Error("Delete attachment %s failed: %v", p, err) + for _, p := range pathsToDelete { + if err := opts.storer.Delete(p); err != nil { + log.Error("Error whilst deleting %s from %s storage: %v", p, opts.name, err) } else { deletedNum++ } } - logger.Info("%d missed information attachment detected, %d deleted.", garbageNum, deletedNum) + logger.Info("Deleted %d/%d orphaned %s(s)", deletedNum, orphanedCount, opts.name) } else { - logger.Warn("Checked %d attachment, %d missed information.", total, garbageNum) + logger.Warn("Found %d/%d (%s/%s) orphaned %s(s)", orphanedCount, totalCount, base.FileSize(orphanedSize), base.FileSize(totalSize), opts.name) } + } else { + logger.Info("Found %d (%s) %s(s)", totalCount, base.FileSize(totalSize), opts.name) } return nil } -func checkStorageFiles(ctx context.Context, logger log.Logger, autofix bool) error { - if err := storage.Init(); err != nil { - logger.Error("storage.Init failed: %v", err) - return err +type checkStorageOptions struct { + All bool + Attachments bool + LFS bool + Avatars bool + RepoAvatars bool + RepoArchives bool + Packages bool +} + +// checkStorage will return a doctor check function to check the requested storage types for "orphaned" stored object/files and optionally delete them +func checkStorage(opts *checkStorageOptions) func(ctx context.Context, logger log.Logger, autofix bool) error { + return func(ctx context.Context, logger log.Logger, autofix bool) error { + if err := storage.Init(); err != nil { + logger.Error("storage.Init failed: %v", err) + return err + } + + if opts.Attachments || opts.All { + if err := commonCheckStorage(ctx, logger, autofix, + &commonStorageCheckOptions{ + storer: storage.Attachments, + isOrphaned: func(path string, obj storage.Object, stat fs.FileInfo) (bool, error) { + exists, err := repo.ExistAttachmentsByUUID(ctx, stat.Name()) + return !exists, err + }, + name: "attachment", + }); err != nil { + return err + } + } + + if opts.LFS || opts.All { + if err := commonCheckStorage(ctx, logger, autofix, + &commonStorageCheckOptions{ + storer: storage.LFS, + isOrphaned: func(path string, obj storage.Object, stat fs.FileInfo) (bool, error) { + // The oid of an LFS stored object is the name but with all the path.Separators removed + oid := strings.ReplaceAll(path, "/", "") + exists, err := git.ExistsLFSObject(ctx, oid) + return !exists, err + }, + name: "LFS file", + }); err != nil { + return err + } + } + + if opts.Avatars || opts.All { + if err := commonCheckStorage(ctx, logger, autofix, + &commonStorageCheckOptions{ + storer: storage.Avatars, + isOrphaned: func(path string, obj storage.Object, stat fs.FileInfo) (bool, error) { + exists, err := user.ExistsWithAvatarAtStoragePath(ctx, path) + return !exists, err + }, + name: "avatar", + }); err != nil { + return err + } + } + + if opts.RepoAvatars || opts.All { + if err := commonCheckStorage(ctx, logger, autofix, + &commonStorageCheckOptions{ + storer: storage.RepoAvatars, + isOrphaned: func(path string, obj storage.Object, stat fs.FileInfo) (bool, error) { + exists, err := repo.ExistsWithAvatarAtStoragePath(ctx, path) + return !exists, err + }, + name: "repo avatar", + }); err != nil { + return err + } + } + + if opts.RepoArchives || opts.All { + if err := commonCheckStorage(ctx, logger, autofix, + &commonStorageCheckOptions{ + storer: storage.RepoAvatars, + isOrphaned: func(path string, obj storage.Object, stat fs.FileInfo) (bool, error) { + exists, err := repo.ExistsRepoArchiverWithStoragePath(ctx, path) + if err == nil || errors.Is(err, util.ErrInvalidArgument) { + // invalid arguments mean that the object is not a valid repo archiver and it should be removed + return !exists, nil + } + return !exists, err + }, + name: "repo archive", + }); err != nil { + return err + } + } + + if opts.Packages || opts.All { + if err := commonCheckStorage(ctx, logger, autofix, + &commonStorageCheckOptions{ + storer: storage.Packages, + isOrphaned: func(path string, obj storage.Object, stat fs.FileInfo) (bool, error) { + key, err := packages_module.RelativePathToKey(path) + if err != nil { + // If there is an error here then the relative path does not match a valid package + // Therefore it is orphaned by default + return true, nil + } + + exists, err := packages.ExistPackageBlobWithSHA(ctx, string(key)) + + return !exists, err + }, + name: "package blob", + }); err != nil { + return err + } + } + + return nil } - return checkAttachmentStorageFiles(logger, autofix) } func init() { Register(&Check{ - Title: "Check if there is garbage storage files", + Title: "Check if there are orphaned storage files", Name: "storages", IsDefault: false, - Run: checkStorageFiles, + Run: checkStorage(&checkStorageOptions{All: true}), + AbortIfFailed: false, + SkipDatabaseInitialization: false, + Priority: 1, + }) + + Register(&Check{ + Title: "Check if there are orphaned attachments in storage", + Name: "storage-attachments", + IsDefault: false, + Run: checkStorage(&checkStorageOptions{Attachments: true}), + AbortIfFailed: false, + SkipDatabaseInitialization: false, + Priority: 1, + }) + + Register(&Check{ + Title: "Check if there are orphaned lfs files in storage", + Name: "storage-lfs", + IsDefault: false, + Run: checkStorage(&checkStorageOptions{LFS: true}), + AbortIfFailed: false, + SkipDatabaseInitialization: false, + Priority: 1, + }) + + Register(&Check{ + Title: "Check if there are orphaned avatars in storage", + Name: "storage-avatars", + IsDefault: false, + Run: checkStorage(&checkStorageOptions{Avatars: true, RepoAvatars: true}), + AbortIfFailed: false, + SkipDatabaseInitialization: false, + Priority: 1, + }) + + Register(&Check{ + Title: "Check if there are orphaned archives in storage", + Name: "storage-archives", + IsDefault: false, + Run: checkStorage(&checkStorageOptions{RepoArchives: true}), + AbortIfFailed: false, + SkipDatabaseInitialization: false, + Priority: 1, + }) + + Register(&Check{ + Title: "Check if there are orphaned package blobs in storage", + Name: "storage-packages", + IsDefault: false, + Run: checkStorage(&checkStorageOptions{Packages: true}), AbortIfFailed: false, SkipDatabaseInitialization: false, Priority: 1, diff --git a/modules/doctor/usertype.go b/modules/doctor/usertype.go index 166e38bd24..550e536cbd 100644 --- a/modules/doctor/usertype.go +++ b/modules/doctor/usertype.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package doctor diff --git a/modules/emoji/emoji.go b/modules/emoji/emoji.go index 89a86a7f3e..3d4ef8599b 100644 --- a/modules/emoji/emoji.go +++ b/modules/emoji/emoji.go @@ -1,7 +1,6 @@ // Copyright 2020 The Gitea Authors. All rights reserved. // Copyright 2015 Kenneth Shaw -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package emoji diff --git a/modules/emoji/emoji_data.go b/modules/emoji/emoji_data.go index 1e14d3de6b..b73013ea1b 100644 --- a/modules/emoji/emoji_data.go +++ b/modules/emoji/emoji_data.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package emoji diff --git a/modules/emoji/emoji_test.go b/modules/emoji/emoji_test.go index def252896f..2526cd121e 100644 --- a/modules/emoji/emoji_test.go +++ b/modules/emoji/emoji_test.go @@ -1,7 +1,6 @@ // Copyright 2020 The Gitea Authors. All rights reserved. // Copyright 2015 Kenneth Shaw -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package emoji diff --git a/modules/eventsource/event.go b/modules/eventsource/event.go index 281a1bb135..d5d2f323af 100644 --- a/modules/eventsource/event.go +++ b/modules/eventsource/event.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package eventsource diff --git a/modules/eventsource/event_test.go b/modules/eventsource/event_test.go index a80e062f0e..4c4272880d 100644 --- a/modules/eventsource/event_test.go +++ b/modules/eventsource/event_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package eventsource diff --git a/modules/eventsource/manager.go b/modules/eventsource/manager.go index 812d673992..7ed2a82903 100644 --- a/modules/eventsource/manager.go +++ b/modules/eventsource/manager.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package eventsource diff --git a/modules/eventsource/manager_run.go b/modules/eventsource/manager_run.go index 44e878fd4e..97d08aa8a8 100644 --- a/modules/eventsource/manager_run.go +++ b/modules/eventsource/manager_run.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package eventsource diff --git a/modules/eventsource/messenger.go b/modules/eventsource/messenger.go index 091e1a5c1c..6df26716be 100644 --- a/modules/eventsource/messenger.go +++ b/modules/eventsource/messenger.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package eventsource diff --git a/modules/generate/generate.go b/modules/generate/generate.go index 326fe8036b..f29634e05e 100644 --- a/modules/generate/generate.go +++ b/modules/generate/generate.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2016 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. +// SPDX-License-Identifier: MIT package generate diff --git a/modules/git/batch_reader.go b/modules/git/batch_reader.go index feb0dd31be..75539c0d0a 100644 --- a/modules/git/batch_reader.go +++ b/modules/git/batch_reader.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/blame.go b/modules/git/blame.go index 832b12213c..fea75b4818 100644 --- a/modules/git/blame.go +++ b/modules/git/blame.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/blame_test.go b/modules/git/blame_test.go index 4bee8cd27a..94277b7c1d 100644 --- a/modules/git/blame_test.go +++ b/modules/git/blame_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/blob.go b/modules/git/blob.go index 9567affd03..8864f54d1b 100644 --- a/modules/git/blob.go +++ b/modules/git/blob.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/blob_gogit.go b/modules/git/blob_gogit.go index 2a2b51e422..aa206409d0 100644 --- a/modules/git/blob_gogit.go +++ b/modules/git/blob_gogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/blob_nogogit.go b/modules/git/blob_nogogit.go index 89bb98162f..511332eb50 100644 --- a/modules/git/blob_nogogit.go +++ b/modules/git/blob_nogogit.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/blob_test.go b/modules/git/blob_test.go index 39f3f11162..63374384f6 100644 --- a/modules/git/blob_test.go +++ b/modules/git/blob_test.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/command.go b/modules/git/command.go index abf40b0cd7..d88fcd1a8c 100644 --- a/modules/git/command.go +++ b/modules/git/command.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2016 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. +// SPDX-License-Identifier: MIT package git @@ -202,8 +201,11 @@ func (c *Command) Run(opts *RunOpts) error { if opts == nil { opts = &RunOpts{} } - if opts.Timeout <= 0 { - opts.Timeout = defaultCommandExecutionTimeout + + // We must not change the provided options + timeout := opts.Timeout + if timeout <= 0 { + timeout = defaultCommandExecutionTimeout } if len(opts.Dir) == 0 { @@ -238,7 +240,7 @@ func (c *Command) Run(opts *RunOpts) error { if opts.UseContextTimeout { ctx, cancel, finished = process.GetManager().AddContext(c.parentContext, desc) } else { - ctx, cancel, finished = process.GetManager().AddContextTimeout(c.parentContext, opts.Timeout, desc) + ctx, cancel, finished = process.GetManager().AddContextTimeout(c.parentContext, timeout, desc) } defer finished() @@ -339,9 +341,20 @@ func (c *Command) RunStdBytes(opts *RunOpts) (stdout, stderr []byte, runErr RunS } stdoutBuf := &bytes.Buffer{} stderrBuf := &bytes.Buffer{} - opts.Stdout = stdoutBuf - opts.Stderr = stderrBuf - err := c.Run(opts) + + // We must not change the provided options as it could break future calls - therefore make a copy. + newOpts := &RunOpts{ + Env: opts.Env, + Timeout: opts.Timeout, + UseContextTimeout: opts.UseContextTimeout, + Dir: opts.Dir, + Stdout: stdoutBuf, + Stderr: stderrBuf, + Stdin: opts.Stdin, + PipelineFunc: opts.PipelineFunc, + } + + err := c.Run(newOpts) stderr = stderrBuf.Bytes() if err != nil { return nil, stderr, &runStdError{err: err, stderr: bytesToString(stderr)} diff --git a/modules/git/command_race_test.go b/modules/git/command_race_test.go index ae2acc3a5a..f567406822 100644 --- a/modules/git/command_race_test.go +++ b/modules/git/command_race_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT //go:build race diff --git a/modules/git/command_test.go b/modules/git/command_test.go index 52d25c9c74..2dca2d0d34 100644 --- a/modules/git/command_test.go +++ b/modules/git/command_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/commit.go b/modules/git/commit.go index 061adc1082..14710de612 100644 --- a/modules/git/commit.go +++ b/modules/git/commit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/commit_convert_gogit.go b/modules/git/commit_convert_gogit.go index bb9d3bf8ce..669f1b15d5 100644 --- a/modules/git/commit_convert_gogit.go +++ b/modules/git/commit_convert_gogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/commit_info.go b/modules/git/commit_info.go index 83e23545de..c740a4e13e 100644 --- a/modules/git/commit_info.go +++ b/modules/git/commit_info.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/commit_info_gogit.go b/modules/git/commit_info_gogit.go index 341698ab34..20db5691eb 100644 --- a/modules/git/commit_info_gogit.go +++ b/modules/git/commit_info_gogit.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/commit_info_nogogit.go b/modules/git/commit_info_nogogit.go index d7bca3b948..e469d2cab6 100644 --- a/modules/git/commit_info_nogogit.go +++ b/modules/git/commit_info_nogogit.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/commit_info_test.go b/modules/git/commit_info_test.go index 4bc3596896..1e331fac00 100644 --- a/modules/git/commit_info_test.go +++ b/modules/git/commit_info_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/commit_reader.go b/modules/git/commit_reader.go index 3c1f6f5ffd..23607c43ab 100644 --- a/modules/git/commit_reader.go +++ b/modules/git/commit_reader.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/commit_test.go b/modules/git/commit_test.go index fb8c22dfd3..1d6fb00183 100644 --- a/modules/git/commit_test.go +++ b/modules/git/commit_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/diff.go b/modules/git/diff.go index 1a43d0dd4a..10ef3d83fb 100644 --- a/modules/git/diff.go +++ b/modules/git/diff.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/diff_test.go b/modules/git/diff_test.go index de71248508..0f865c52a8 100644 --- a/modules/git/diff_test.go +++ b/modules/git/diff_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/error.go b/modules/git/error.go index ebfea8e702..dc10d451b3 100644 --- a/modules/git/error.go +++ b/modules/git/error.go @@ -1,6 +1,5 @@ // Copyright 2015 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/foreachref/format.go b/modules/git/foreachref/format.go index c9aa5233e1..97e8ee4724 100644 --- a/modules/git/foreachref/format.go +++ b/modules/git/foreachref/format.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package foreachref diff --git a/modules/git/foreachref/format_test.go b/modules/git/foreachref/format_test.go index 5aca10f752..392a95a4e6 100644 --- a/modules/git/foreachref/format_test.go +++ b/modules/git/foreachref/format_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package foreachref_test diff --git a/modules/git/foreachref/parser.go b/modules/git/foreachref/parser.go index bf83a10ed5..de69eaa2c8 100644 --- a/modules/git/foreachref/parser.go +++ b/modules/git/foreachref/parser.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package foreachref diff --git a/modules/git/foreachref/parser_test.go b/modules/git/foreachref/parser_test.go index cb36428604..5468318ca8 100644 --- a/modules/git/foreachref/parser_test.go +++ b/modules/git/foreachref/parser_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package foreachref_test diff --git a/modules/git/git.go b/modules/git/git.go index 18d62838df..f5919d82dc 100644 --- a/modules/git/git.go +++ b/modules/git/git.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2017 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/git_test.go b/modules/git/git_test.go index 0915737878..e3bfe496da 100644 --- a/modules/git/git_test.go +++ b/modules/git/git_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/hook.go b/modules/git/hook.go index c50f891224..46f93ce13e 100644 --- a/modules/git/hook.go +++ b/modules/git/hook.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/last_commit_cache.go b/modules/git/last_commit_cache.go index 2b51d59720..ec8f1cce62 100644 --- a/modules/git/last_commit_cache.go +++ b/modules/git/last_commit_cache.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/last_commit_cache_gogit.go b/modules/git/last_commit_cache_gogit.go index 82c76bad20..90e609fc81 100644 --- a/modules/git/last_commit_cache_gogit.go +++ b/modules/git/last_commit_cache_gogit.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/last_commit_cache_nogogit.go b/modules/git/last_commit_cache_nogogit.go index 1f4d693a26..155cb3cb7c 100644 --- a/modules/git/last_commit_cache_nogogit.go +++ b/modules/git/last_commit_cache_nogogit.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/log_name_status.go b/modules/git/log_name_status.go index dee4fc226e..fe3b6598d7 100644 --- a/modules/git/log_name_status.go +++ b/modules/git/log_name_status.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/notes.go b/modules/git/notes.go index a8dd66df0b..63539cb3a2 100644 --- a/modules/git/notes.go +++ b/modules/git/notes.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/notes_gogit.go b/modules/git/notes_gogit.go index fe6d1f1e58..c2297d8970 100644 --- a/modules/git/notes_gogit.go +++ b/modules/git/notes_gogit.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/notes_nogogit.go b/modules/git/notes_nogogit.go index ba216ce3e4..4da375c321 100644 --- a/modules/git/notes_nogogit.go +++ b/modules/git/notes_nogogit.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/notes_test.go b/modules/git/notes_test.go index 34e7178bea..267671d8fa 100644 --- a/modules/git/notes_test.go +++ b/modules/git/notes_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/parse_gogit.go b/modules/git/parse_gogit.go index 4a8dcfdf35..226ef5df73 100644 --- a/modules/git/parse_gogit.go +++ b/modules/git/parse_gogit.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/parse_gogit_test.go b/modules/git/parse_gogit_test.go index 075de6d25d..f6e32401e6 100644 --- a/modules/git/parse_gogit_test.go +++ b/modules/git/parse_gogit_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/parse_nogogit.go b/modules/git/parse_nogogit.go index fb5b63def9..8b94c69200 100644 --- a/modules/git/parse_nogogit.go +++ b/modules/git/parse_nogogit.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/parse_nogogit_test.go b/modules/git/parse_nogogit_test.go index cecd3960da..23fddb014c 100644 --- a/modules/git/parse_nogogit_test.go +++ b/modules/git/parse_nogogit_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/pipeline/catfile.go b/modules/git/pipeline/catfile.go index c1d4bd1665..4677218150 100644 --- a/modules/git/pipeline/catfile.go +++ b/modules/git/pipeline/catfile.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package pipeline diff --git a/modules/git/pipeline/lfs.go b/modules/git/pipeline/lfs.go index 18cce34289..ee0505f29f 100644 --- a/modules/git/pipeline/lfs.go +++ b/modules/git/pipeline/lfs.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/pipeline/lfs_nogogit.go b/modules/git/pipeline/lfs_nogogit.go index 061da8ca50..49390f7c00 100644 --- a/modules/git/pipeline/lfs_nogogit.go +++ b/modules/git/pipeline/lfs_nogogit.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/pipeline/namerev.go b/modules/git/pipeline/namerev.go index 85ba7db23e..ad583a7479 100644 --- a/modules/git/pipeline/namerev.go +++ b/modules/git/pipeline/namerev.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package pipeline diff --git a/modules/git/pipeline/revlist.go b/modules/git/pipeline/revlist.go index 93142034ec..09bb2c8b3c 100644 --- a/modules/git/pipeline/revlist.go +++ b/modules/git/pipeline/revlist.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package pipeline diff --git a/modules/git/ref.go b/modules/git/ref.go index 2f459148a2..47cc04b7fb 100644 --- a/modules/git/ref.go +++ b/modules/git/ref.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package git @@ -56,40 +55,57 @@ func (ref *Reference) Commit() (*Commit, error) { // ShortName returns the short name of the reference func (ref *Reference) ShortName() string { - if ref == nil { - return "" - } - if strings.HasPrefix(ref.Name, BranchPrefix) { - return strings.TrimPrefix(ref.Name, BranchPrefix) - } - if strings.HasPrefix(ref.Name, TagPrefix) { - return strings.TrimPrefix(ref.Name, TagPrefix) - } - if strings.HasPrefix(ref.Name, RemotePrefix) { - return strings.TrimPrefix(ref.Name, RemotePrefix) - } - if strings.HasPrefix(ref.Name, PullPrefix) && strings.IndexByte(ref.Name[pullLen:], '/') > -1 { - return ref.Name[pullLen : strings.IndexByte(ref.Name[pullLen:], '/')+pullLen] - } - - return ref.Name + return RefName(ref.Name).ShortName() } // RefGroup returns the group type of the reference func (ref *Reference) RefGroup() string { - if ref == nil { - return "" + return RefName(ref.Name).RefGroup() +} + +// RefName represents a git reference name +type RefName string + +func (ref RefName) IsBranch() bool { + return strings.HasPrefix(string(ref), BranchPrefix) +} + +func (ref RefName) IsTag() bool { + return strings.HasPrefix(string(ref), TagPrefix) +} + +// ShortName returns the short name of the reference name +func (ref RefName) ShortName() string { + refName := string(ref) + if strings.HasPrefix(refName, BranchPrefix) { + return strings.TrimPrefix(refName, BranchPrefix) } - if strings.HasPrefix(ref.Name, BranchPrefix) { + if strings.HasPrefix(refName, TagPrefix) { + return strings.TrimPrefix(refName, TagPrefix) + } + if strings.HasPrefix(refName, RemotePrefix) { + return strings.TrimPrefix(refName, RemotePrefix) + } + if strings.HasPrefix(refName, PullPrefix) && strings.IndexByte(refName[pullLen:], '/') > -1 { + return refName[pullLen : strings.IndexByte(refName[pullLen:], '/')+pullLen] + } + + return refName +} + +// RefGroup returns the group type of the reference +func (ref RefName) RefGroup() string { + refName := string(ref) + if strings.HasPrefix(refName, BranchPrefix) { return "heads" } - if strings.HasPrefix(ref.Name, TagPrefix) { + if strings.HasPrefix(refName, TagPrefix) { return "tags" } - if strings.HasPrefix(ref.Name, RemotePrefix) { + if strings.HasPrefix(refName, RemotePrefix) { return "remotes" } - if strings.HasPrefix(ref.Name, PullPrefix) && strings.IndexByte(ref.Name[pullLen:], '/') > -1 { + if strings.HasPrefix(refName, PullPrefix) && strings.IndexByte(refName[pullLen:], '/') > -1 { return "pull" } return "" diff --git a/modules/git/remote.go b/modules/git/remote.go index c416eea136..3585313f6a 100644 --- a/modules/git/remote.go +++ b/modules/git/remote.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo.go b/modules/git/repo.go index 8ba3ae4fda..4ba40d20af 100644 --- a/modules/git/repo.go +++ b/modules/git/repo.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2017 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_archive.go b/modules/git/repo_archive.go index a0cbfba5d9..cff9724f00 100644 --- a/modules/git/repo_archive.go +++ b/modules/git/repo_archive.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2020 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. +// SPDX-License-Identifier: MIT package git @@ -38,6 +37,18 @@ func (a ArchiveType) String() string { return "unknown" } +func ToArchiveType(s string) ArchiveType { + switch s { + case "zip": + return ZIP + case "tar.gz": + return TARGZ + case "bundle": + return BUNDLE + } + return 0 +} + // CreateArchive create archive content to the target path func (repo *Repository) CreateArchive(ctx context.Context, format ArchiveType, target io.Writer, usePrefix bool, commitID string) error { if format.String() == "unknown" { diff --git a/modules/git/repo_attribute.go b/modules/git/repo_attribute.go index d9c50be6f7..d3a3dc8c83 100644 --- a/modules/git/repo_attribute.go +++ b/modules/git/repo_attribute.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_attribute_test.go b/modules/git/repo_attribute_test.go index 901a0aa244..6882874d2d 100644 --- a/modules/git/repo_attribute_test.go +++ b/modules/git/repo_attribute_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_base.go b/modules/git/repo_base.go index 710f0de9f6..2c6df8b9c4 100644 --- a/modules/git/repo_base.go +++ b/modules/git/repo_base.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_base_gogit.go b/modules/git/repo_base_gogit.go index 8fe9c404c3..ef59ead900 100644 --- a/modules/git/repo_base_gogit.go +++ b/modules/git/repo_base_gogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2017 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/repo_base_nogogit.go b/modules/git/repo_base_nogogit.go index 56af2c640f..a0216d14a6 100644 --- a/modules/git/repo_base_nogogit.go +++ b/modules/git/repo_base_nogogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2017 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/repo_blame.go b/modules/git/repo_blame.go index 8a3707aa09..7f44735f9f 100644 --- a/modules/git/repo_blame.go +++ b/modules/git/repo_blame.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_blob.go b/modules/git/repo_blob.go index 5397f24cb6..698b6c7074 100644 --- a/modules/git/repo_blob.go +++ b/modules/git/repo_blob.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_blob_gogit.go b/modules/git/repo_blob_gogit.go index 5640011f4a..7f0892f6f5 100644 --- a/modules/git/repo_blob_gogit.go +++ b/modules/git/repo_blob_gogit.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/repo_blob_nogogit.go b/modules/git/repo_blob_nogogit.go index 44ba0a36b1..184a2bc9dd 100644 --- a/modules/git/repo_blob_nogogit.go +++ b/modules/git/repo_blob_nogogit.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/repo_blob_test.go b/modules/git/repo_blob_test.go index 9f0b865377..026c73a283 100644 --- a/modules/git/repo_blob_test.go +++ b/modules/git/repo_blob_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_branch.go b/modules/git/repo_branch.go index a3fc7e0c42..14dcf14d8a 100644 --- a/modules/git/repo_branch.go +++ b/modules/git/repo_branch.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_branch_gogit.go b/modules/git/repo_branch_gogit.go index dc29576562..ca19d3827e 100644 --- a/modules/git/repo_branch_gogit.go +++ b/modules/git/repo_branch_gogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/repo_branch_nogogit.go b/modules/git/repo_branch_nogogit.go index 95c3718841..7559513c9b 100644 --- a/modules/git/repo_branch_nogogit.go +++ b/modules/git/repo_branch_nogogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT //go:build !gogit @@ -53,7 +52,7 @@ func (repo *Repository) IsReferenceExist(name string) bool { // IsBranchExist returns true if given branch exists in current repository. func (repo *Repository) IsBranchExist(name string) bool { - if name == "" { + if repo == nil || name == "" { return false } diff --git a/modules/git/repo_branch_test.go b/modules/git/repo_branch_test.go index 58a738e28b..fe788946e5 100644 --- a/modules/git/repo_branch_test.go +++ b/modules/git/repo_branch_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_commit.go b/modules/git/repo_commit.go index 90259fd746..8343e34843 100644 --- a/modules/git/repo_commit.go +++ b/modules/git/repo_commit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_commit_gogit.go b/modules/git/repo_commit_gogit.go index 14fec3f9c6..b6c42a802f 100644 --- a/modules/git/repo_commit_gogit.go +++ b/modules/git/repo_commit_gogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/repo_commit_nogogit.go b/modules/git/repo_commit_nogogit.go index 13a7be778f..35a705fea3 100644 --- a/modules/git/repo_commit_nogogit.go +++ b/modules/git/repo_commit_nogogit.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/repo_commit_test.go b/modules/git/repo_commit_test.go index 7b3a5101f2..af8c0592fe 100644 --- a/modules/git/repo_commit_test.go +++ b/modules/git/repo_commit_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_commitgraph.go b/modules/git/repo_commitgraph.go index 075b59ad06..492438be37 100644 --- a/modules/git/repo_commitgraph.go +++ b/modules/git/repo_commitgraph.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_commitgraph_gogit.go b/modules/git/repo_commitgraph_gogit.go index 6b00a4fdc4..8e92c30e54 100644 --- a/modules/git/repo_commitgraph_gogit.go +++ b/modules/git/repo_commitgraph_gogit.go @@ -1,7 +1,6 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/repo_compare.go b/modules/git/repo_compare.go index 7575b11658..b1b55c88a4 100644 --- a/modules/git/repo_compare.go +++ b/modules/git/repo_compare.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_compare_test.go b/modules/git/repo_compare_test.go index 63f7254dea..5b50bc82ad 100644 --- a/modules/git/repo_compare_test.go +++ b/modules/git/repo_compare_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_gpg.go b/modules/git/repo_gpg.go index 25188d07e3..4803be5816 100644 --- a/modules/git/repo_gpg.go +++ b/modules/git/repo_gpg.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2017 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_hook.go b/modules/git/repo_hook.go index a652e938fa..cdf076505d 100644 --- a/modules/git/repo_hook.go +++ b/modules/git/repo_hook.go @@ -1,6 +1,5 @@ // Copyright 2015 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_index.go b/modules/git/repo_index.go index 5542883288..99eb2b540b 100644 --- a/modules/git/repo_index.go +++ b/modules/git/repo_index.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_language_stats.go b/modules/git/repo_language_stats.go index daeb4b591f..74c76b40a4 100644 --- a/modules/git/repo_language_stats.go +++ b/modules/git/repo_language_stats.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_language_stats_gogit.go b/modules/git/repo_language_stats_gogit.go index 503e774e7a..9674eca275 100644 --- a/modules/git/repo_language_stats_gogit.go +++ b/modules/git/repo_language_stats_gogit.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/repo_language_stats_nogogit.go b/modules/git/repo_language_stats_nogogit.go index baeb114909..a1d28f40e8 100644 --- a/modules/git/repo_language_stats_nogogit.go +++ b/modules/git/repo_language_stats_nogogit.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/repo_language_stats_test.go b/modules/git/repo_language_stats_test.go index 0234c77c0b..d616d95741 100644 --- a/modules/git/repo_language_stats_test.go +++ b/modules/git/repo_language_stats_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/repo_object.go b/modules/git/repo_object.go index af448b0110..9edc201fea 100644 --- a/modules/git/repo_object.go +++ b/modules/git/repo_object.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_ref.go b/modules/git/repo_ref.go index 397434e12f..54e424bb83 100644 --- a/modules/git/repo_ref.go +++ b/modules/git/repo_ref.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_ref_gogit.go b/modules/git/repo_ref_gogit.go index d11c58e005..8a68a4574f 100644 --- a/modules/git/repo_ref_gogit.go +++ b/modules/git/repo_ref_gogit.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/repo_ref_nogogit.go b/modules/git/repo_ref_nogogit.go index d766a8cac3..ac53d661b5 100644 --- a/modules/git/repo_ref_nogogit.go +++ b/modules/git/repo_ref_nogogit.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/repo_ref_test.go b/modules/git/repo_ref_test.go index afd38ca251..776d7ce3e1 100644 --- a/modules/git/repo_ref_test.go +++ b/modules/git/repo_ref_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_stats.go b/modules/git/repo_stats.go index 002e2525e2..d6e91f25a9 100644 --- a/modules/git/repo_stats.go +++ b/modules/git/repo_stats.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_stats_test.go b/modules/git/repo_stats_test.go index 494a161305..668ed67999 100644 --- a/modules/git/repo_stats_test.go +++ b/modules/git/repo_stats_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_tag.go b/modules/git/repo_tag.go index 8585d824f9..8aa06545d4 100644 --- a/modules/git/repo_tag.go +++ b/modules/git/repo_tag.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_tag_gogit.go b/modules/git/repo_tag_gogit.go index c6dec28987..2bc75e7cf9 100644 --- a/modules/git/repo_tag_gogit.go +++ b/modules/git/repo_tag_gogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/repo_tag_nogogit.go b/modules/git/repo_tag_nogogit.go index 5d3aace52f..d3331cf9b7 100644 --- a/modules/git/repo_tag_nogogit.go +++ b/modules/git/repo_tag_nogogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build !gogit @@ -16,7 +15,7 @@ import ( // IsTagExist returns true if given tag exists in the repository. func (repo *Repository) IsTagExist(name string) bool { - if name == "" { + if repo == nil || name == "" { return false } diff --git a/modules/git/repo_tag_test.go b/modules/git/repo_tag_test.go index 6a00473bb7..589349a72c 100644 --- a/modules/git/repo_tag_test.go +++ b/modules/git/repo_tag_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_test.go b/modules/git/repo_test.go index 8ca170cd1f..2a39148192 100644 --- a/modules/git/repo_test.go +++ b/modules/git/repo_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_tree.go b/modules/git/repo_tree.go index ba81bfc6db..5fea5c0aea 100644 --- a/modules/git/repo_tree.go +++ b/modules/git/repo_tree.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/repo_tree_gogit.go b/modules/git/repo_tree_gogit.go index e720164936..e0e5e73fa3 100644 --- a/modules/git/repo_tree_gogit.go +++ b/modules/git/repo_tree_gogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/repo_tree_nogogit.go b/modules/git/repo_tree_nogogit.go index dc4a5becb9..16ea6bbd8a 100644 --- a/modules/git/repo_tree_nogogit.go +++ b/modules/git/repo_tree_nogogit.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/sha1.go b/modules/git/sha1.go index 15f282c6e4..3a02484bc2 100644 --- a/modules/git/sha1.go +++ b/modules/git/sha1.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/sha1_gogit.go b/modules/git/sha1_gogit.go index 16501efb43..28f35d17a9 100644 --- a/modules/git/sha1_gogit.go +++ b/modules/git/sha1_gogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/sha1_nogogit.go b/modules/git/sha1_nogogit.go index a2620cba69..d818d86a3a 100644 --- a/modules/git/sha1_nogogit.go +++ b/modules/git/sha1_nogogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/sha1_test.go b/modules/git/sha1_test.go index c5c00f5445..db2944fc53 100644 --- a/modules/git/sha1_test.go +++ b/modules/git/sha1_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/signature.go b/modules/git/signature.go index b59db8f490..b5b17f23b0 100644 --- a/modules/git/signature.go +++ b/modules/git/signature.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/signature_gogit.go b/modules/git/signature_gogit.go index 6f1c98420d..c984ad6e20 100644 --- a/modules/git/signature_gogit.go +++ b/modules/git/signature_gogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build gogit @@ -10,6 +9,7 @@ package git import ( "bytes" "strconv" + "strings" "time" "github.com/go-git/go-git/v5/plumbing/object" @@ -30,7 +30,9 @@ type Signature = object.Signature func newSignatureFromCommitline(line []byte) (_ *Signature, err error) { sig := new(Signature) emailStart := bytes.IndexByte(line, '<') - sig.Name = string(line[:emailStart-1]) + if emailStart > 0 { // Empty name has already occurred, even if it shouldn't + sig.Name = strings.TrimSpace(string(line[:emailStart-1])) + } emailEnd := bytes.IndexByte(line, '>') sig.Email = string(line[emailStart+1 : emailEnd]) diff --git a/modules/git/signature_nogogit.go b/modules/git/signature_nogogit.go index 07a3b79f1e..a203d5ce6d 100644 --- a/modules/git/signature_nogogit.go +++ b/modules/git/signature_nogogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build !gogit @@ -11,6 +10,7 @@ import ( "bytes" "fmt" "strconv" + "strings" "time" ) @@ -51,7 +51,9 @@ func newSignatureFromCommitline(line []byte) (sig *Signature, err error) { return } - sig.Name = string(line[:emailStart-1]) + if emailStart > 0 { // Empty name has already occurred, even if it shouldn't + sig.Name = strings.TrimSpace(string(line[:emailStart-1])) + } sig.Email = string(line[emailStart+1 : emailEnd]) hasTime := emailEnd+2 < len(line) diff --git a/modules/git/submodule.go b/modules/git/submodule.go index ee61f61179..3afaa334db 100644 --- a/modules/git/submodule.go +++ b/modules/git/submodule.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2015 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/submodule_test.go b/modules/git/submodule_test.go index 653f0a6f08..e05f2510c4 100644 --- a/modules/git/submodule_test.go +++ b/modules/git/submodule_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/tag.go b/modules/git/tag.go index 3482f81e90..d0ddef64e0 100644 --- a/modules/git/tag.go +++ b/modules/git/tag.go @@ -1,6 +1,5 @@ // Copyright 2015 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/tag_test.go b/modules/git/tag_test.go index e5f1660b8e..2337e69c6a 100644 --- a/modules/git/tag_test.go +++ b/modules/git/tag_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/tree.go b/modules/git/tree.go index f5944dd29c..856b8cef53 100644 --- a/modules/git/tree.go +++ b/modules/git/tree.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/tree_blob.go b/modules/git/tree_blob.go index 19edcf4c6c..31d9f3d73b 100644 --- a/modules/git/tree_blob.go +++ b/modules/git/tree_blob.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/tree_blob_gogit.go b/modules/git/tree_blob_gogit.go index bb010b5883..f1afc5d0a6 100644 --- a/modules/git/tree_blob_gogit.go +++ b/modules/git/tree_blob_gogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/tree_blob_nogogit.go b/modules/git/tree_blob_nogogit.go index 3770004d6d..92d3d107a7 100644 --- a/modules/git/tree_blob_nogogit.go +++ b/modules/git/tree_blob_nogogit.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/tree_entry.go b/modules/git/tree_entry.go index 3644d00f36..84b6ea4075 100644 --- a/modules/git/tree_entry.go +++ b/modules/git/tree_entry.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/tree_entry_gogit.go b/modules/git/tree_entry_gogit.go index 2b2992c32a..194dd12f7d 100644 --- a/modules/git/tree_entry_gogit.go +++ b/modules/git/tree_entry_gogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/tree_entry_mode.go b/modules/git/tree_entry_mode.go index d999ccc02a..a399118cf8 100644 --- a/modules/git/tree_entry_mode.go +++ b/modules/git/tree_entry_mode.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/git/tree_entry_nogogit.go b/modules/git/tree_entry_nogogit.go index aff67a3b22..cda755886a 100644 --- a/modules/git/tree_entry_nogogit.go +++ b/modules/git/tree_entry_nogogit.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/tree_entry_test.go b/modules/git/tree_entry_test.go index c512c7348e..30eee13669 100644 --- a/modules/git/tree_entry_test.go +++ b/modules/git/tree_entry_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/tree_gogit.go b/modules/git/tree_gogit.go index 480c5e44da..fa601e6533 100644 --- a/modules/git/tree_gogit.go +++ b/modules/git/tree_gogit.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/git/tree_nogogit.go b/modules/git/tree_nogogit.go index 5cbb5ffc94..185317e7a7 100644 --- a/modules/git/tree_nogogit.go +++ b/modules/git/tree_nogogit.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/git/url/url.go b/modules/git/url/url.go index b41cfab7ef..637685183e 100644 --- a/modules/git/url/url.go +++ b/modules/git/url/url.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package url diff --git a/modules/git/url/url_test.go b/modules/git/url/url_test.go index 611bef8672..da820ed889 100644 --- a/modules/git/url/url_test.go +++ b/modules/git/url/url_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package url diff --git a/modules/git/utils.go b/modules/git/utils.go index d6bf9f4413..628faf509f 100644 --- a/modules/git/utils.go +++ b/modules/git/utils.go @@ -1,6 +1,5 @@ // Copyright 2015 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package git @@ -100,6 +99,9 @@ func RefURL(repoURL, ref string) string { return repoURL + "/src/branch/" + refName case strings.HasPrefix(ref, TagPrefix): return repoURL + "/src/tag/" + refName + case !IsValidSHAPattern(ref): + // assume they mean a branch + return repoURL + "/src/branch/" + refName default: return repoURL + "/src/commit/" + refName } diff --git a/modules/git/utils_test.go b/modules/git/utils_test.go index 9a2d481b63..718db700ae 100644 --- a/modules/git/utils_test.go +++ b/modules/git/utils_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package git diff --git a/modules/gitgraph/graph.go b/modules/gitgraph/graph.go index d6342c9280..baedfe5980 100644 --- a/modules/gitgraph/graph.go +++ b/modules/gitgraph/graph.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package gitgraph diff --git a/modules/gitgraph/graph_models.go b/modules/gitgraph/graph_models.go index c153e5d3be..0e0fc1cd01 100644 --- a/modules/gitgraph/graph_models.go +++ b/modules/gitgraph/graph_models.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package gitgraph diff --git a/modules/gitgraph/graph_test.go b/modules/gitgraph/graph_test.go index 2cfbe4b2fa..18d427acd9 100644 --- a/modules/gitgraph/graph_test.go +++ b/modules/gitgraph/graph_test.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package gitgraph diff --git a/modules/gitgraph/parser.go b/modules/gitgraph/parser.go index 5432962784..f6bf9b0b90 100644 --- a/modules/gitgraph/parser.go +++ b/modules/gitgraph/parser.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package gitgraph diff --git a/modules/graceful/context.go b/modules/graceful/context.go index b9d975a1d5..6b5b207ff3 100644 --- a/modules/graceful/context.go +++ b/modules/graceful/context.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package graceful diff --git a/modules/graceful/manager.go b/modules/graceful/manager.go index 21f019fb56..c7b4c101ef 100644 --- a/modules/graceful/manager.go +++ b/modules/graceful/manager.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package graceful diff --git a/modules/graceful/manager_unix.go b/modules/graceful/manager_unix.go index ba1dbd38f6..ca6ccc1b66 100644 --- a/modules/graceful/manager_unix.go +++ b/modules/graceful/manager_unix.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT //go:build !windows diff --git a/modules/graceful/manager_windows.go b/modules/graceful/manager_windows.go index 10c1d67b97..212ddf437c 100644 --- a/modules/graceful/manager_windows.go +++ b/modules/graceful/manager_windows.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT // This code is heavily inspired by the archived gofacebook/gracenet/net.go handler //go:build windows diff --git a/modules/graceful/net_unix.go b/modules/graceful/net_unix.go index 0bb589e231..a2620d2c80 100644 --- a/modules/graceful/net_unix.go +++ b/modules/graceful/net_unix.go @@ -1,6 +1,6 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT + // This code is heavily inspired by the archived gofacebook/gracenet/net.go handler //go:build !windows diff --git a/modules/graceful/net_windows.go b/modules/graceful/net_windows.go index 07ae51b8dd..a2f58e224a 100644 --- a/modules/graceful/net_windows.go +++ b/modules/graceful/net_windows.go @@ -1,6 +1,6 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT + // This code is heavily inspired by the archived gofacebook/gracenet/net.go handler //go:build windows diff --git a/modules/graceful/restart_unix.go b/modules/graceful/restart_unix.go index 1d0d1059e9..406fe6c8af 100644 --- a/modules/graceful/restart_unix.go +++ b/modules/graceful/restart_unix.go @@ -1,6 +1,6 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT + // This code is heavily inspired by the archived gofacebook/gracenet/net.go handler //go:build !windows diff --git a/modules/graceful/server.go b/modules/graceful/server.go index 30a460a943..e42d35cd49 100644 --- a/modules/graceful/server.go +++ b/modules/graceful/server.go @@ -1,6 +1,6 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT + // This code is highly inspired by endless go package graceful diff --git a/modules/graceful/server_hooks.go b/modules/graceful/server_hooks.go index c634905711..9b67589571 100644 --- a/modules/graceful/server_hooks.go +++ b/modules/graceful/server_hooks.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package graceful diff --git a/modules/graceful/server_http.go b/modules/graceful/server_http.go index 8ab2bdf41f..a1f8e0ff52 100644 --- a/modules/graceful/server_http.go +++ b/modules/graceful/server_http.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package graceful diff --git a/modules/hcaptcha/hcaptcha.go b/modules/hcaptcha/hcaptcha.go index 95fe2dd1c3..4d20cfd483 100644 --- a/modules/hcaptcha/hcaptcha.go +++ b/modules/hcaptcha/hcaptcha.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package hcaptcha diff --git a/modules/highlight/highlight.go b/modules/highlight/highlight.go index 65ed74b019..05e472c083 100644 --- a/modules/highlight/highlight.go +++ b/modules/highlight/highlight.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2020 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. +// SPDX-License-Identifier: MIT package highlight @@ -18,6 +17,7 @@ import ( "code.gitea.io/gitea/modules/analyze" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/util" "github.com/alecthomas/chroma/v2" "github.com/alecthomas/chroma/v2/formatters/html" @@ -56,18 +56,18 @@ func NewContext() { }) } -// Code returns a HTML version of code string with chroma syntax highlighting classes -func Code(fileName, language, code string) string { +// Code returns a HTML version of code string with chroma syntax highlighting classes and the matched lexer name +func Code(fileName, language, code string) (string, string) { NewContext() // diff view newline will be passed as empty, change to literal '\n' so it can be copied // preserve literal newline in blame view if code == "" || code == "\n" { - return "\n" + return "\n", "" } if len(code) > sizeLimit { - return code + return code, "" } var lexer chroma.Lexer @@ -103,7 +103,10 @@ func Code(fileName, language, code string) string { } cache.Add(fileName, lexer) } - return CodeFromLexer(lexer, code) + + lexerName := formatLexerName(lexer.Config().Name) + + return CodeFromLexer(lexer, code), lexerName } // CodeFromLexer returns a HTML version of code string with chroma syntax highlighting classes @@ -134,12 +137,12 @@ func CodeFromLexer(lexer chroma.Lexer, code string) string { return strings.TrimSuffix(htmlbuf.String(), "\n") } -// File returns a slice of chroma syntax highlighted HTML lines of code -func File(fileName, language string, code []byte) ([]string, error) { +// File returns a slice of chroma syntax highlighted HTML lines of code and the matched lexer name +func File(fileName, language string, code []byte) ([]string, string, error) { NewContext() if len(code) > sizeLimit { - return PlainText(code), nil + return PlainText(code), "", nil } formatter := html.New(html.WithClasses(true), @@ -172,9 +175,11 @@ func File(fileName, language string, code []byte) ([]string, error) { } } + lexerName := formatLexerName(lexer.Config().Name) + iterator, err := lexer.Tokenise(nil, string(code)) if err != nil { - return nil, fmt.Errorf("can't tokenize code: %w", err) + return nil, "", fmt.Errorf("can't tokenize code: %w", err) } tokensLines := chroma.SplitTokensIntoLines(iterator.Tokens()) @@ -185,13 +190,13 @@ func File(fileName, language string, code []byte) ([]string, error) { iterator = chroma.Literator(tokens...) err = formatter.Format(htmlBuf, styles.GitHub, iterator) if err != nil { - return nil, fmt.Errorf("can't format code: %w", err) + return nil, "", fmt.Errorf("can't format code: %w", err) } lines = append(lines, htmlBuf.String()) htmlBuf.Reset() } - return lines, nil + return lines, lexerName, nil } // PlainText returns non-highlighted HTML for code @@ -212,3 +217,11 @@ func PlainText(code []byte) []string { } return m } + +func formatLexerName(name string) string { + if name == "fallback" { + return "Plaintext" + } + + return util.ToTitleCaseNoLower(name) +} diff --git a/modules/highlight/highlight_test.go b/modules/highlight/highlight_test.go index 8f83f4a2f6..7a9887728f 100644 --- a/modules/highlight/highlight_test.go +++ b/modules/highlight/highlight_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package highlight @@ -17,34 +16,52 @@ func lines(s string) []string { func TestFile(t *testing.T) { tests := []struct { - name string - code string - want []string + name string + code string + want []string + lexerName string }{ { - name: "empty.py", - code: "", - want: lines(""), + name: "empty.py", + code: "", + want: lines(""), + lexerName: "Python", }, { - name: "tags.txt", - code: "<>", - want: lines("<>"), + name: "empty.js", + code: "", + want: lines(""), + lexerName: "JavaScript", }, { - name: "tags.py", - code: "<>", - want: lines(`<>`), + name: "empty.yaml", + code: "", + want: lines(""), + lexerName: "YAML", }, { - name: "eol-no.py", - code: "a=1", - want: lines(`a=1`), + name: "tags.txt", + code: "<>", + want: lines("<>"), + lexerName: "Plaintext", }, { - name: "eol-newline1.py", - code: "a=1\n", - want: lines(`a=1\n`), + name: "tags.py", + code: "<>", + want: lines(`<>`), + lexerName: "Python", + }, + { + name: "eol-no.py", + code: "a=1", + want: lines(`a=1`), + lexerName: "Python", + }, + { + name: "eol-newline1.py", + code: "a=1\n", + want: lines(`a=1\n`), + lexerName: "Python", }, { name: "eol-newline2.py", @@ -54,6 +71,7 @@ func TestFile(t *testing.T) { \n `, ), + lexerName: "Python", }, { name: "empty-line-with-space.py", @@ -73,17 +91,19 @@ c=2 \n c=2`, ), + lexerName: "Python", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - out, err := File(tt.name, "", []byte(tt.code)) + out, lexerName, err := File(tt.name, "", []byte(tt.code)) assert.NoError(t, err) expected := strings.Join(tt.want, "\n") actual := strings.Join(out, "\n") assert.Equal(t, strings.Count(actual, "")) assert.EqualValues(t, expected, actual) + assert.Equal(t, tt.lexerName, lexerName) }) } } diff --git a/modules/hostmatcher/hostmatcher.go b/modules/hostmatcher/hostmatcher.go index a092e07f41..1069310316 100644 --- a/modules/hostmatcher/hostmatcher.go +++ b/modules/hostmatcher/hostmatcher.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package hostmatcher diff --git a/modules/hostmatcher/hostmatcher_test.go b/modules/hostmatcher/hostmatcher_test.go index b93976df6a..c781847471 100644 --- a/modules/hostmatcher/hostmatcher_test.go +++ b/modules/hostmatcher/hostmatcher_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package hostmatcher diff --git a/modules/hostmatcher/http.go b/modules/hostmatcher/http.go index 84cd2974ec..65f5f78b14 100644 --- a/modules/hostmatcher/http.go +++ b/modules/hostmatcher/http.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package hostmatcher diff --git a/modules/html/html.go b/modules/html/html.go new file mode 100644 index 0000000000..3219b939f4 --- /dev/null +++ b/modules/html/html.go @@ -0,0 +1,33 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package html + +// ParseSizeAndClass get size and class from string with default values +// If present, "others" expects the new size first and then the classes to use +func ParseSizeAndClass(defaultSize int, defaultClass string, others ...interface{}) (int, string) { + if len(others) == 0 { + return defaultSize, defaultClass + } + + size := defaultSize + _size, ok := others[0].(int) + if ok && _size != 0 { + size = _size + } + + if len(others) == 1 { + return size, defaultClass + } + + class := defaultClass + if _class, ok := others[1].(string); ok && _class != "" { + if defaultClass == "" { + class = _class + } else { + class = defaultClass + " " + _class + } + } + + return size, class +} diff --git a/modules/httpcache/httpcache.go b/modules/httpcache/httpcache.go index 750233d4a7..1247a81fea 100644 --- a/modules/httpcache/httpcache.go +++ b/modules/httpcache/httpcache.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package httpcache diff --git a/modules/httpcache/httpcache_test.go b/modules/httpcache/httpcache_test.go index 49e54d147e..624d2f4d4b 100644 --- a/modules/httpcache/httpcache_test.go +++ b/modules/httpcache/httpcache_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package httpcache diff --git a/modules/httplib/httplib.go b/modules/httplib/httplib.go index 32790fb54b..a1984400d6 100644 --- a/modules/httplib/httplib.go +++ b/modules/httplib/httplib.go @@ -1,7 +1,6 @@ // Copyright 2013 The Beego Authors. All rights reserved. // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package httplib diff --git a/modules/indexer/bleve/batch.go b/modules/indexer/bleve/batch.go index 79994e6e5b..77675147b2 100644 --- a/modules/indexer/bleve/batch.go +++ b/modules/indexer/bleve/batch.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package bleve diff --git a/modules/indexer/code/bleve.go b/modules/indexer/code/bleve.go index 3ea1c86178..6ee2639d34 100644 --- a/modules/indexer/code/bleve.go +++ b/modules/indexer/code/bleve.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package code diff --git a/modules/indexer/code/bleve_test.go b/modules/indexer/code/bleve_test.go index a34d54bc0e..00bcd5c90c 100644 --- a/modules/indexer/code/bleve_test.go +++ b/modules/indexer/code/bleve_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package code diff --git a/modules/indexer/code/elastic_search.go b/modules/indexer/code/elastic_search.go index dd3c9c9771..68c8096758 100644 --- a/modules/indexer/code/elastic_search.go +++ b/modules/indexer/code/elastic_search.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package code diff --git a/modules/indexer/code/elastic_search_test.go b/modules/indexer/code/elastic_search_test.go index fc58633f16..e7506eefa6 100644 --- a/modules/indexer/code/elastic_search_test.go +++ b/modules/indexer/code/elastic_search_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package code diff --git a/modules/indexer/code/git.go b/modules/indexer/code/git.go index 774dcc8149..bbcc6ba487 100644 --- a/modules/indexer/code/git.go +++ b/modules/indexer/code/git.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package code diff --git a/modules/indexer/code/indexer.go b/modules/indexer/code/indexer.go index 9845ade3dd..027d13555c 100644 --- a/modules/indexer/code/indexer.go +++ b/modules/indexer/code/indexer.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package code @@ -85,7 +84,7 @@ type IndexerData struct { var indexerQueue queue.UniqueQueue func index(ctx context.Context, indexer Indexer, repoID int64) error { - repo, err := repo_model.GetRepositoryByID(repoID) + repo, err := repo_model.GetRepositoryByID(ctx, repoID) if repo_model.IsErrRepoNotExist(err) { return indexer.Delete(repoID) } diff --git a/modules/indexer/code/indexer_test.go b/modules/indexer/code/indexer_test.go index 06923dfd25..c353d5b688 100644 --- a/modules/indexer/code/indexer_test.go +++ b/modules/indexer/code/indexer_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package code diff --git a/modules/indexer/code/search.go b/modules/indexer/code/search.go index bb7715bafc..1de9ffc224 100644 --- a/modules/indexer/code/search.go +++ b/modules/indexer/code/search.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package code @@ -94,6 +93,9 @@ func searchResult(result *SearchResult, startIndex, endIndex int) (*Result, erro lineNumbers[i] = startLineNum + i index += len(line) } + + highlighted, _ := highlight.Code(result.Filename, "", formattedLinesBuffer.String()) + return &Result{ RepoID: result.RepoID, Filename: result.Filename, @@ -102,7 +104,7 @@ func searchResult(result *SearchResult, startIndex, endIndex int) (*Result, erro Language: result.Language, Color: result.Color, LineNumbers: lineNumbers, - FormattedLines: highlight.Code(result.Filename, "", formattedLinesBuffer.String()), + FormattedLines: highlighted, }, nil } diff --git a/modules/indexer/code/wrapped.go b/modules/indexer/code/wrapped.go index ba58236fba..33ba57a094 100644 --- a/modules/indexer/code/wrapped.go +++ b/modules/indexer/code/wrapped.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package code diff --git a/modules/indexer/issues/bleve.go b/modules/indexer/issues/bleve.go index dff1cf0c60..952bddfb29 100644 --- a/modules/indexer/issues/bleve.go +++ b/modules/indexer/issues/bleve.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package issues diff --git a/modules/indexer/issues/bleve_test.go b/modules/indexer/issues/bleve_test.go index 42d22f06a2..22827158e4 100644 --- a/modules/indexer/issues/bleve_test.go +++ b/modules/indexer/issues/bleve_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package issues diff --git a/modules/indexer/issues/db.go b/modules/indexer/issues/db.go index d21c86337e..d28b536e02 100644 --- a/modules/indexer/issues/db.go +++ b/modules/indexer/issues/db.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issues diff --git a/modules/indexer/issues/elastic_search.go b/modules/indexer/issues/elastic_search.go index 97e32b8975..ee8e3df62f 100644 --- a/modules/indexer/issues/elastic_search.go +++ b/modules/indexer/issues/elastic_search.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issues diff --git a/modules/indexer/issues/indexer.go b/modules/indexer/issues/indexer.go index da6a200aef..55d3c7bc09 100644 --- a/modules/indexer/issues/indexer.go +++ b/modules/indexer/issues/indexer.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package issues @@ -291,7 +290,7 @@ func populateIssueIndexer(ctx context.Context) { return default: } - repos, _, err := repo_model.SearchRepositoryByName(&repo_model.SearchRepoOptions{ + repos, _, err := repo_model.SearchRepositoryByName(ctx, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{Page: page, PageSize: repo_model.RepositoryListDefaultPageSize}, OrderBy: db.SearchOrderByID, Private: true, @@ -313,14 +312,14 @@ func populateIssueIndexer(ctx context.Context) { return default: } - UpdateRepoIndexer(repo) + UpdateRepoIndexer(ctx, repo) } } } // UpdateRepoIndexer add/update all issues of the repositories -func UpdateRepoIndexer(repo *repo_model.Repository) { - is, err := issues_model.Issues(&issues_model.IssuesOptions{ +func UpdateRepoIndexer(ctx context.Context, repo *repo_model.Repository) { + is, err := issues_model.Issues(ctx, &issues_model.IssuesOptions{ RepoID: repo.ID, IsClosed: util.OptionalBoolNone, IsPull: util.OptionalBoolNone, @@ -329,8 +328,8 @@ func UpdateRepoIndexer(repo *repo_model.Repository) { log.Error("Issues: %v", err) return } - if err = issues_model.IssueList(is).LoadDiscussComments(); err != nil { - log.Error("LoadComments: %v", err) + if err = issues_model.IssueList(is).LoadDiscussComments(ctx); err != nil { + log.Error("LoadDiscussComments: %v", err) return } for _, issue := range is { @@ -360,11 +359,11 @@ func UpdateIssueIndexer(issue *issues_model.Issue) { } // DeleteRepoIssueIndexer deletes repo's all issues indexes -func DeleteRepoIssueIndexer(repo *repo_model.Repository) { +func DeleteRepoIssueIndexer(ctx context.Context, repo *repo_model.Repository) { var ids []int64 - ids, err := issues_model.GetIssueIDsByRepoID(db.DefaultContext, repo.ID) + ids, err := issues_model.GetIssueIDsByRepoID(ctx, repo.ID) if err != nil { - log.Error("getIssueIDsByRepoID failed: %v", err) + log.Error("GetIssueIDsByRepoID failed: %v", err) return } diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index e8b9ff8370..ff0541d049 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issues diff --git a/modules/indexer/stats/db.go b/modules/indexer/stats/db.go index d39b1dcf2a..9bbdcad60d 100644 --- a/modules/indexer/stats/db.go +++ b/modules/indexer/stats/db.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package stats @@ -22,7 +21,7 @@ func (db *DBIndexer) Index(id int64) error { ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().ShutdownContext(), fmt.Sprintf("Stats.DB Index Repo[%d]", id)) defer finished() - repo, err := repo_model.GetRepositoryByID(id) + repo, err := repo_model.GetRepositoryByID(ctx, id) if err != nil { return err } diff --git a/modules/indexer/stats/indexer.go b/modules/indexer/stats/indexer.go index f4fe54b8cb..1c01e25e29 100644 --- a/modules/indexer/stats/indexer.go +++ b/modules/indexer/stats/indexer.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package stats diff --git a/modules/indexer/stats/indexer_test.go b/modules/indexer/stats/indexer_test.go index a4a8b63241..bc6c4cd7f8 100644 --- a/modules/indexer/stats/indexer_test.go +++ b/modules/indexer/stats/indexer_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package stats @@ -37,7 +36,7 @@ func TestRepoStatsIndex(t *testing.T) { err := Init() assert.NoError(t, err) - repo, err := repo_model.GetRepositoryByID(1) + repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 1) assert.NoError(t, err) err = UpdateRepoIndexer(repo) diff --git a/modules/indexer/stats/queue.go b/modules/indexer/stats/queue.go index f983fcd11d..32379f2859 100644 --- a/modules/indexer/stats/queue.go +++ b/modules/indexer/stats/queue.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package stats diff --git a/modules/issue/template/template.go b/modules/issue/template/template.go index 3b33852cb5..f8bce3f465 100644 --- a/modules/issue/template/template.go +++ b/modules/issue/template/template.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package template @@ -165,7 +164,7 @@ func validateOptions(field *api.IssueFormField, idx int) error { return position.Errorf("should be a string") } case api.IssueFormFieldTypeCheckboxes: - opt, ok := option.(map[interface{}]interface{}) + opt, ok := option.(map[string]interface{}) if !ok { return position.Errorf("should be a dictionary") } @@ -351,7 +350,7 @@ func (o *valuedOption) Label() string { return label } case api.IssueFormFieldTypeCheckboxes: - if vs, ok := o.data.(map[interface{}]interface{}); ok { + if vs, ok := o.data.(map[string]interface{}); ok { if v, ok := vs["label"].(string); ok { return v } diff --git a/modules/issue/template/template_test.go b/modules/issue/template/template_test.go index 883e1e0780..0845642cd3 100644 --- a/modules/issue/template/template_test.go +++ b/modules/issue/template/template_test.go @@ -1,23 +1,25 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package template import ( "net/url" - "reflect" "testing" "code.gitea.io/gitea/modules/json" api "code.gitea.io/gitea/modules/structs" + + "github.com/stretchr/testify/require" ) func TestValidate(t *testing.T) { tests := []struct { - name string - content string - wantErr string + name string + filename string + content string + want *api.IssueTemplate + wantErr string }{ { name: "miss name", @@ -316,21 +318,9 @@ body: `, wantErr: "body[0](checkboxes), option[0]: 'required' should be a bool", }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - tmpl, err := unmarshal("test.yaml", []byte(tt.content)) - if err != nil { - t.Fatal(err) - } - if err := Validate(tmpl); (err == nil) != (tt.wantErr == "") || err != nil && err.Error() != tt.wantErr { - t.Errorf("Validate() error = %v, wantErr %q", err, tt.wantErr) - } - }) - } - - t.Run("valid", func(t *testing.T) { - content := ` + { + name: "valid", + content: ` name: Name title: Title about: About @@ -386,96 +376,227 @@ body: required: false - label: Option 3 of checkboxes required: true -` - want := &api.IssueTemplate{ - Name: "Name", - Title: "Title", - About: "About", - Labels: []string{"label1", "label2"}, - Ref: "Ref", - Fields: []*api.IssueFormField{ - { - Type: "markdown", - ID: "id1", - Attributes: map[string]interface{}{ - "value": "Value of the markdown", - }, - }, - { - Type: "textarea", - ID: "id2", - Attributes: map[string]interface{}{ - "label": "Label of textarea", - "description": "Description of textarea", - "placeholder": "Placeholder of textarea", - "value": "Value of textarea", - "render": "bash", - }, - Validations: map[string]interface{}{ - "required": true, - }, - }, - { - Type: "input", - ID: "id3", - Attributes: map[string]interface{}{ - "label": "Label of input", - "description": "Description of input", - "placeholder": "Placeholder of input", - "value": "Value of input", - }, - Validations: map[string]interface{}{ - "required": true, - "is_number": true, - "regex": "[a-zA-Z0-9]+", - }, - }, - { - Type: "dropdown", - ID: "id4", - Attributes: map[string]interface{}{ - "label": "Label of dropdown", - "description": "Description of dropdown", - "multiple": true, - "options": []interface{}{ - "Option 1 of dropdown", - "Option 2 of dropdown", - "Option 3 of dropdown", +`, + want: &api.IssueTemplate{ + Name: "Name", + Title: "Title", + About: "About", + Labels: []string{"label1", "label2"}, + Ref: "Ref", + Fields: []*api.IssueFormField{ + { + Type: "markdown", + ID: "id1", + Attributes: map[string]interface{}{ + "value": "Value of the markdown", }, }, - Validations: map[string]interface{}{ - "required": true, + { + Type: "textarea", + ID: "id2", + Attributes: map[string]interface{}{ + "label": "Label of textarea", + "description": "Description of textarea", + "placeholder": "Placeholder of textarea", + "value": "Value of textarea", + "render": "bash", + }, + Validations: map[string]interface{}{ + "required": true, + }, }, - }, - { - Type: "checkboxes", - ID: "id5", - Attributes: map[string]interface{}{ - "label": "Label of checkboxes", - "description": "Description of checkboxes", - "options": []interface{}{ - map[interface{}]interface{}{"label": "Option 1 of checkboxes", "required": true}, - map[interface{}]interface{}{"label": "Option 2 of checkboxes", "required": false}, - map[interface{}]interface{}{"label": "Option 3 of checkboxes", "required": true}, + { + Type: "input", + ID: "id3", + Attributes: map[string]interface{}{ + "label": "Label of input", + "description": "Description of input", + "placeholder": "Placeholder of input", + "value": "Value of input", + }, + Validations: map[string]interface{}{ + "required": true, + "is_number": true, + "regex": "[a-zA-Z0-9]+", + }, + }, + { + Type: "dropdown", + ID: "id4", + Attributes: map[string]interface{}{ + "label": "Label of dropdown", + "description": "Description of dropdown", + "multiple": true, + "options": []interface{}{ + "Option 1 of dropdown", + "Option 2 of dropdown", + "Option 3 of dropdown", + }, + }, + Validations: map[string]interface{}{ + "required": true, + }, + }, + { + Type: "checkboxes", + ID: "id5", + Attributes: map[string]interface{}{ + "label": "Label of checkboxes", + "description": "Description of checkboxes", + "options": []interface{}{ + map[string]interface{}{"label": "Option 1 of checkboxes", "required": true}, + map[string]interface{}{"label": "Option 2 of checkboxes", "required": false}, + map[string]interface{}{"label": "Option 3 of checkboxes", "required": true}, + }, }, }, }, + FileName: "test.yaml", }, - FileName: "test.yaml", - } - got, err := unmarshal("test.yaml", []byte(content)) - if err != nil { - t.Fatal(err) - } - if err := Validate(got); err != nil { - t.Errorf("Validate() error = %v", err) - } - if !reflect.DeepEqual(want, got) { - jsonWant, _ := json.Marshal(want) - jsonGot, _ := json.Marshal(got) - t.Errorf("want:\n%s\ngot:\n%s", jsonWant, jsonGot) - } - }) + wantErr: "", + }, + { + name: "single label", + content: ` +name: Name +title: Title +about: About +labels: label1 +ref: Ref +body: + - type: markdown + id: id1 + attributes: + value: Value of the markdown +`, + want: &api.IssueTemplate{ + Name: "Name", + Title: "Title", + About: "About", + Labels: []string{"label1"}, + Ref: "Ref", + Fields: []*api.IssueFormField{ + { + Type: "markdown", + ID: "id1", + Attributes: map[string]interface{}{ + "value": "Value of the markdown", + }, + }, + }, + FileName: "test.yaml", + }, + wantErr: "", + }, + { + name: "comma-delimited labels", + content: ` +name: Name +title: Title +about: About +labels: label1,label2,,label3 ,, +ref: Ref +body: + - type: markdown + id: id1 + attributes: + value: Value of the markdown +`, + want: &api.IssueTemplate{ + Name: "Name", + Title: "Title", + About: "About", + Labels: []string{"label1", "label2", "label3"}, + Ref: "Ref", + Fields: []*api.IssueFormField{ + { + Type: "markdown", + ID: "id1", + Attributes: map[string]interface{}{ + "value": "Value of the markdown", + }, + }, + }, + FileName: "test.yaml", + }, + wantErr: "", + }, + { + name: "empty string as labels", + content: ` +name: Name +title: Title +about: About +labels: '' +ref: Ref +body: + - type: markdown + id: id1 + attributes: + value: Value of the markdown +`, + want: &api.IssueTemplate{ + Name: "Name", + Title: "Title", + About: "About", + Labels: nil, + Ref: "Ref", + Fields: []*api.IssueFormField{ + { + Type: "markdown", + ID: "id1", + Attributes: map[string]interface{}{ + "value": "Value of the markdown", + }, + }, + }, + FileName: "test.yaml", + }, + wantErr: "", + }, + { + name: "comma delimited labels in markdown", + filename: "test.md", + content: `--- +name: Name +title: Title +about: About +labels: label1,label2,,label3 ,, +ref: Ref +--- +Content +`, + want: &api.IssueTemplate{ + Name: "Name", + Title: "Title", + About: "About", + Labels: []string{"label1", "label2", "label3"}, + Ref: "Ref", + Fields: nil, + Content: "Content\n", + FileName: "test.md", + }, + wantErr: "", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + filename := "test.yaml" + if tt.filename != "" { + filename = tt.filename + } + tmpl, err := unmarshal(filename, []byte(tt.content)) + require.NoError(t, err) + if tt.wantErr != "" { + require.EqualError(t, Validate(tmpl), tt.wantErr) + } else { + require.NoError(t, Validate(tmpl)) + want, _ := json.Marshal(tt.want) + got, _ := json.Marshal(tmpl) + require.JSONEq(t, string(want), string(got)) + } + }) + } } func TestRenderToMarkdown(t *testing.T) { diff --git a/modules/issue/template/unmarshal.go b/modules/issue/template/unmarshal.go index 24587b0fed..8cae8d4c42 100644 --- a/modules/issue/template/unmarshal.go +++ b/modules/issue/template/unmarshal.go @@ -1,13 +1,12 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package template import ( "fmt" "io" - "path/filepath" + "path" "strconv" "code.gitea.io/gitea/modules/git" @@ -16,7 +15,7 @@ import ( api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" - "gopkg.in/yaml.v2" + "gopkg.in/yaml.v3" ) // CouldBe indicates a file with the filename could be a template, @@ -44,7 +43,7 @@ func Unmarshal(filename string, content []byte) (*api.IssueTemplate, error) { // UnmarshalFromEntry parses out a valid template from the blob in entry func UnmarshalFromEntry(entry *git.TreeEntry, dir string) (*api.IssueTemplate, error) { - return unmarshalFromEntry(entry, filepath.Join(dir, entry.Name())) + return unmarshalFromEntry(entry, path.Join(dir, entry.Name())) // Filepaths in Git are ALWAYS '/' separated do not use filepath here } // UnmarshalFromCommit parses out a valid template from the commit @@ -109,7 +108,7 @@ func unmarshal(filename string, content []byte) (*api.IssueTemplate, error) { // It could be a valid markdown with two horizontal lines, or an invalid markdown with wrong metadata. it.Content = string(content) - it.Name = filepath.Base(it.FileName) + it.Name = path.Base(it.FileName) // paths in Git are always '/' separated - do not use filepath! it.About, _ = util.SplitStringAtByteN(it.Content, 80) } else { it.Content = templateBody diff --git a/modules/json/json.go b/modules/json/json.go index 4361262a2f..5f8c474e05 100644 --- a/modules/json/json.go +++ b/modules/json/json.go @@ -1,6 +1,5 @@ // Copyright 2020 The Gitea Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package json diff --git a/modules/lfs/client.go b/modules/lfs/client.go index aaf61aefcf..f810e5c7aa 100644 --- a/modules/lfs/client.go +++ b/modules/lfs/client.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package lfs diff --git a/modules/lfs/client_test.go b/modules/lfs/client_test.go index 88986f06d6..a1369301e0 100644 --- a/modules/lfs/client_test.go +++ b/modules/lfs/client_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package lfs diff --git a/modules/lfs/content_store.go b/modules/lfs/content_store.go index 0eedf4de17..94277a6b8e 100644 --- a/modules/lfs/content_store.go +++ b/modules/lfs/content_store.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package lfs diff --git a/modules/lfs/endpoint.go b/modules/lfs/endpoint.go index 943966ed15..3ae3cf077b 100644 --- a/modules/lfs/endpoint.go +++ b/modules/lfs/endpoint.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package lfs diff --git a/modules/lfs/endpoint_test.go b/modules/lfs/endpoint_test.go index 69f4768650..118abe2d4e 100644 --- a/modules/lfs/endpoint_test.go +++ b/modules/lfs/endpoint_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package lfs diff --git a/modules/lfs/filesystem_client.go b/modules/lfs/filesystem_client.go index dc72981a9e..835551e00c 100644 --- a/modules/lfs/filesystem_client.go +++ b/modules/lfs/filesystem_client.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package lfs diff --git a/modules/lfs/http_client.go b/modules/lfs/http_client.go index a1a3e7f363..ec0d6269bd 100644 --- a/modules/lfs/http_client.go +++ b/modules/lfs/http_client.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package lfs diff --git a/modules/lfs/http_client_test.go b/modules/lfs/http_client_test.go index 8f6dcb1966..a8c7e379f6 100644 --- a/modules/lfs/http_client_test.go +++ b/modules/lfs/http_client_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package lfs diff --git a/modules/lfs/pointer.go b/modules/lfs/pointer.go index 2a3a2116b4..b5e13d56a3 100644 --- a/modules/lfs/pointer.go +++ b/modules/lfs/pointer.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package lfs diff --git a/modules/lfs/pointer_scanner_gogit.go b/modules/lfs/pointer_scanner_gogit.go index ed27cb1f55..f4302c23bc 100644 --- a/modules/lfs/pointer_scanner_gogit.go +++ b/modules/lfs/pointer_scanner_gogit.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT //go:build gogit diff --git a/modules/lfs/pointer_scanner_nogogit.go b/modules/lfs/pointer_scanner_nogogit.go index d17f1f7b98..658b98feab 100644 --- a/modules/lfs/pointer_scanner_nogogit.go +++ b/modules/lfs/pointer_scanner_nogogit.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT //go:build !gogit diff --git a/modules/lfs/pointer_test.go b/modules/lfs/pointer_test.go index 9cd8b15c9e..41b5459fef 100644 --- a/modules/lfs/pointer_test.go +++ b/modules/lfs/pointer_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package lfs diff --git a/modules/lfs/shared.go b/modules/lfs/shared.go index d010b05ee5..6b2e55f2fb 100644 --- a/modules/lfs/shared.go +++ b/modules/lfs/shared.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package lfs diff --git a/modules/lfs/transferadapter.go b/modules/lfs/transferadapter.go index 2fdd92c810..649497aabb 100644 --- a/modules/lfs/transferadapter.go +++ b/modules/lfs/transferadapter.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package lfs diff --git a/modules/lfs/transferadapter_test.go b/modules/lfs/transferadapter_test.go index b26d516c68..f86d2c54be 100644 --- a/modules/lfs/transferadapter_test.go +++ b/modules/lfs/transferadapter_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package lfs diff --git a/modules/log/buffer.go b/modules/log/buffer.go index 9535522bb6..1eee2465f1 100644 --- a/modules/log/buffer.go +++ b/modules/log/buffer.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/buffer_test.go b/modules/log/buffer_test.go index 8ec74bc78d..1c39006050 100644 --- a/modules/log/buffer_test.go +++ b/modules/log/buffer_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/colors.go b/modules/log/colors.go index 15e23a0dac..02781afe84 100644 --- a/modules/log/colors.go +++ b/modules/log/colors.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/colors_router.go b/modules/log/colors_router.go index 888198d4e9..efc7337b6b 100644 --- a/modules/log/colors_router.go +++ b/modules/log/colors_router.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/conn.go b/modules/log/conn.go index 155f2866ca..39d5234214 100644 --- a/modules/log/conn.go +++ b/modules/log/conn.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/conn_test.go b/modules/log/conn_test.go index 1d373506a4..445bd77653 100644 --- a/modules/log/conn_test.go +++ b/modules/log/conn_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/console.go b/modules/log/console.go index fc7c9b4967..8764d984ac 100644 --- a/modules/log/console.go +++ b/modules/log/console.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/console_other.go b/modules/log/console_other.go index b5cac55b52..c30be41544 100644 --- a/modules/log/console_other.go +++ b/modules/log/console_other.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT //go:build !windows diff --git a/modules/log/console_test.go b/modules/log/console_test.go index 4da87b48a3..e4c3882d4f 100644 --- a/modules/log/console_test.go +++ b/modules/log/console_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/console_windows.go b/modules/log/console_windows.go index ea47e5d624..54dac12fa0 100644 --- a/modules/log/console_windows.go +++ b/modules/log/console_windows.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/errors.go b/modules/log/errors.go index 1fe54d4265..942639a434 100644 --- a/modules/log/errors.go +++ b/modules/log/errors.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/event.go b/modules/log/event.go index aebd156212..4466f7ff34 100644 --- a/modules/log/event.go +++ b/modules/log/event.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/file.go b/modules/log/file.go index d0cba7817c..13386a320f 100644 --- a/modules/log/file.go +++ b/modules/log/file.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/file_test.go b/modules/log/file_test.go index cc2b9fe077..f1ca23d342 100644 --- a/modules/log/file_test.go +++ b/modules/log/file_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/flags.go b/modules/log/flags.go index 95950548ec..4a3732600b 100644 --- a/modules/log/flags.go +++ b/modules/log/flags.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/groutinelabel.go b/modules/log/groutinelabel.go index 0d3739fd98..56d7af42da 100644 --- a/modules/log/groutinelabel.go +++ b/modules/log/groutinelabel.go @@ -1,13 +1,12 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package log import "unsafe" //go:linkname runtime_getProfLabel runtime/pprof.runtime_getProfLabel -func runtime_getProfLabel() unsafe.Pointer // nolint +func runtime_getProfLabel() unsafe.Pointer //nolint type labelMap map[string]string diff --git a/modules/log/groutinelabel_test.go b/modules/log/groutinelabel_test.go index 8e23721b86..34e99653d6 100644 --- a/modules/log/groutinelabel_test.go +++ b/modules/log/groutinelabel_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/level.go b/modules/log/level.go index 5964ed8f8b..3c8a736b30 100644 --- a/modules/log/level.go +++ b/modules/log/level.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/level_test.go b/modules/log/level_test.go index 47f77738c5..cd18a807d8 100644 --- a/modules/log/level_test.go +++ b/modules/log/level_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/log.go b/modules/log/log.go index 4303ecf4c0..73f908dfab 100644 --- a/modules/log/log.go +++ b/modules/log/log.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/log_test.go b/modules/log/log_test.go index 33f68c8e8e..819cdb521f 100644 --- a/modules/log/log_test.go +++ b/modules/log/log_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/logger.go b/modules/log/logger.go index 0045d79322..56e39c392e 100644 --- a/modules/log/logger.go +++ b/modules/log/logger.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/multichannel.go b/modules/log/multichannel.go index 519abf663d..8ccb08179c 100644 --- a/modules/log/multichannel.go +++ b/modules/log/multichannel.go @@ -1,6 +1,5 @@ // Copyright 2020 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/provider.go b/modules/log/provider.go index e03e6f74a7..490c3fa71b 100644 --- a/modules/log/provider.go +++ b/modules/log/provider.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/smtp.go b/modules/log/smtp.go index 61af50b81a..e385020c67 100644 --- a/modules/log/smtp.go +++ b/modules/log/smtp.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/smtp_test.go b/modules/log/smtp_test.go index c8758bf6be..d7d28f28f8 100644 --- a/modules/log/smtp_test.go +++ b/modules/log/smtp_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/stack.go b/modules/log/stack.go index 4b40d81ab7..d4496cff03 100644 --- a/modules/log/stack.go +++ b/modules/log/stack.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/writer.go b/modules/log/writer.go index 1c4f5b4a19..ac4b3c8c4e 100644 --- a/modules/log/writer.go +++ b/modules/log/writer.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/log/writer_test.go b/modules/log/writer_test.go index 99a5fd3406..8c03f87d90 100644 --- a/modules/log/writer_test.go +++ b/modules/log/writer_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package log diff --git a/modules/markup/camo.go b/modules/markup/camo.go index f804447f2d..e93797de2b 100644 --- a/modules/markup/camo.go +++ b/modules/markup/camo.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package markup diff --git a/modules/markup/camo_test.go b/modules/markup/camo_test.go index cc917039d8..ba58835221 100644 --- a/modules/markup/camo_test.go +++ b/modules/markup/camo_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package markup diff --git a/modules/markup/common/footnote.go b/modules/markup/common/footnote.go index d07f5e6090..0e75e2adfd 100644 --- a/modules/markup/common/footnote.go +++ b/modules/markup/common/footnote.go @@ -1,7 +1,6 @@ // Copyright 2019 Yusuke Inuzuka // Copyright 2019 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. +// SPDX-License-Identifier: MIT // Most of what follows is a subtly changed version of github.com/yuin/goldmark/extension/footnote.go diff --git a/modules/markup/common/html.go b/modules/markup/common/html.go index a2328a2288..5658839c6f 100644 --- a/modules/markup/common/html.go +++ b/modules/markup/common/html.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package common diff --git a/modules/markup/common/linkify.go b/modules/markup/common/linkify.go index 2140486a30..f84680205e 100644 --- a/modules/markup/common/linkify.go +++ b/modules/markup/common/linkify.go @@ -1,7 +1,6 @@ // Copyright 2019 Yusuke Inuzuka // Copyright 2019 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. +// SPDX-License-Identifier: MIT // Most of this file is a subtly changed version of github.com/yuin/goldmark/extension/linkify.go diff --git a/modules/markup/console/console.go b/modules/markup/console/console.go index 597593eee1..cf42c9cceb 100644 --- a/modules/markup/console/console.go +++ b/modules/markup/console/console.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package console diff --git a/modules/markup/console/console_test.go b/modules/markup/console/console_test.go index 282fbb0598..506f86194c 100644 --- a/modules/markup/console/console_test.go +++ b/modules/markup/console/console_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package console diff --git a/modules/markup/csv/csv.go b/modules/markup/csv/csv.go index 5095b85465..7af34a6cbc 100644 --- a/modules/markup/csv/csv.go +++ b/modules/markup/csv/csv.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package markup diff --git a/modules/markup/csv/csv_test.go b/modules/markup/csv/csv_test.go index 612f78c76c..b9f5769be2 100644 --- a/modules/markup/csv/csv_test.go +++ b/modules/markup/csv/csv_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package markup diff --git a/modules/markup/external/external.go b/modules/markup/external/external.go index 0eeb2d70a5..f47776690f 100644 --- a/modules/markup/external/external.go +++ b/modules/markup/external/external.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package external diff --git a/modules/markup/html.go b/modules/markup/html.go index ae00c3905f..6b5a8e32d4 100644 --- a/modules/markup/html.go +++ b/modules/markup/html.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package markup @@ -306,18 +305,15 @@ func postProcess(ctx *RenderContext, procs []processor, input io.Reader, output return err } - res := bytes.NewBuffer(make([]byte, 0, len(rawHTML)+50)) - // prepend "" - _, _ = res.WriteString("") - - // Strip out nuls - they're always invalid - _, _ = res.Write(tagCleaner.ReplaceAll([]byte(nulCleaner.Replace(string(rawHTML))), []byte("<$1"))) - - // close the tags - _, _ = res.WriteString("") - // parse the HTML - node, err := html.Parse(res) + node, err := html.Parse(io.MultiReader( + // prepend "" + strings.NewReader(""), + // Strip out nuls - they're always invalid + bytes.NewReader(tagCleaner.ReplaceAll([]byte(nulCleaner.Replace(string(rawHTML))), []byte("<$1"))), + // close the tags + strings.NewReader(""), + )) if err != nil { return &postProcessError{"invalid HTML", err} } diff --git a/modules/markup/html_internal_test.go b/modules/markup/html_internal_test.go index 25b0f7b7a5..6746c40d18 100644 --- a/modules/markup/html_internal_test.go +++ b/modules/markup/html_internal_test.go @@ -1,6 +1,6 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT + package markup import ( diff --git a/modules/markup/html_test.go b/modules/markup/html_test.go index e57187a677..32f26bffab 100644 --- a/modules/markup/html_test.go +++ b/modules/markup/html_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package markup_test diff --git a/modules/markup/markdown/ast.go b/modules/markup/markdown/ast.go index c82d5e5e73..e844f801c4 100644 --- a/modules/markup/markdown/ast.go +++ b/modules/markup/markdown/ast.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package markdown @@ -180,3 +179,37 @@ func IsColorPreview(node ast.Node) bool { _, ok := node.(*ColorPreview) return ok } + +const ( + AttentionNote string = "Note" + AttentionWarning string = "Warning" +) + +// Attention is an inline for a color preview +type Attention struct { + ast.BaseInline + AttentionType string +} + +// Dump implements Node.Dump. +func (n *Attention) Dump(source []byte, level int) { + m := map[string]string{} + m["AttentionType"] = n.AttentionType + ast.DumpHelper(n, source, level, m, nil) +} + +// KindAttention is the NodeKind for Attention +var KindAttention = ast.NewNodeKind("Attention") + +// Kind implements Node.Kind. +func (n *Attention) Kind() ast.NodeKind { + return KindAttention +} + +// NewAttention returns a new Attention node. +func NewAttention(attentionType string) *Attention { + return &Attention{ + BaseInline: ast.BaseInline{}, + AttentionType: attentionType, + } +} diff --git a/modules/markup/markdown/convertyaml.go b/modules/markup/markdown/convertyaml.go index 3f5ebec908..6e90847e06 100644 --- a/modules/markup/markdown/convertyaml.go +++ b/modules/markup/markdown/convertyaml.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package markdown diff --git a/modules/markup/markdown/goldmark.go b/modules/markup/markdown/goldmark.go index 1a36681366..50b438219b 100644 --- a/modules/markup/markdown/goldmark.go +++ b/modules/markup/markdown/goldmark.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package markdown @@ -14,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/markup" "code.gitea.io/gitea/modules/markup/common" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/svg" giteautil "code.gitea.io/gitea/modules/util" "github.com/microcosm-cc/bluemonday/css" @@ -46,6 +46,7 @@ func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc pa ctx.TableOfContents = make([]markup.Header, 0, 100) } + attentionMarkedBlockquotes := make(container.Set[*ast.Blockquote]) _ = ast.Walk(node, func(n ast.Node, entering bool) (ast.WalkStatus, error) { if !entering { return ast.WalkContinue, nil @@ -184,6 +185,18 @@ func (g *ASTTransformer) Transform(node *ast.Document, reader text.Reader, pc pa if css.ColorHandler(strings.ToLower(string(colorContent))) { v.AppendChild(v, NewColorPreview(colorContent)) } + case *ast.Emphasis: + // check if inside blockquote for attention, expected hierarchy is + // Emphasis < Paragraph < Blockquote + blockquote, isInBlockquote := n.Parent().Parent().(*ast.Blockquote) + if isInBlockquote && !attentionMarkedBlockquotes.Contains(blockquote) { + fullText := string(n.Text(reader.Source())) + if fullText == AttentionNote || fullText == AttentionWarning { + v.SetAttributeString("class", []byte("attention-"+strings.ToLower(fullText))) + v.Parent().InsertBefore(v.Parent(), v, NewAttention(fullText)) + attentionMarkedBlockquotes.Add(blockquote) + } + } } return ast.WalkContinue, nil }) @@ -273,6 +286,7 @@ func (r *HTMLRenderer) RegisterFuncs(reg renderer.NodeRendererFuncRegisterer) { reg.Register(KindSummary, r.renderSummary) reg.Register(KindIcon, r.renderIcon) reg.Register(ast.KindCodeSpan, r.renderCodeSpan) + reg.Register(KindAttention, r.renderAttention) reg.Register(KindTaskCheckBoxListItem, r.renderTaskCheckBoxListItem) reg.Register(east.KindTaskCheckBox, r.renderTaskCheckBox) } @@ -309,6 +323,28 @@ func (r *HTMLRenderer) renderCodeSpan(w util.BufWriter, source []byte, n ast.Nod return ast.WalkContinue, nil } +// renderAttention renders a quote marked with i.e. "> **Note**" or "> **Warning**" with a corresponding svg +func (r *HTMLRenderer) renderAttention(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { + if entering { + _, _ = w.WriteString(``) + + var octiconType string + switch n.AttentionType { + case AttentionNote: + octiconType = "info" + case AttentionWarning: + octiconType = "alert" + } + _, _ = w.WriteString(string(svg.RenderHTML("octicon-" + octiconType))) + } else { + _, _ = w.WriteString("\n") + } + return ast.WalkContinue, nil +} + func (r *HTMLRenderer) renderDocument(w util.BufWriter, source []byte, node ast.Node, entering bool) (ast.WalkStatus, error) { n := node.(*ast.Document) diff --git a/modules/markup/markdown/markdown.go b/modules/markup/markdown/markdown.go index fa289986cc..1e5c470758 100644 --- a/modules/markup/markdown/markdown.go +++ b/modules/markup/markdown/markdown.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package markdown diff --git a/modules/markup/markdown/markdown_test.go b/modules/markup/markdown/markdown_test.go index fbb741d1cd..bb2c47f18e 100644 --- a/modules/markup/markdown/markdown_test.go +++ b/modules/markup/markdown/markdown_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package markdown_test diff --git a/modules/markup/markdown/math/block_node.go b/modules/markup/markdown/math/block_node.go index bd8449babf..10d17ff8d3 100644 --- a/modules/markup/markdown/math/block_node.go +++ b/modules/markup/markdown/math/block_node.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package math diff --git a/modules/markup/markdown/math/block_parser.go b/modules/markup/markdown/math/block_parser.go index f865122886..7f714d7239 100644 --- a/modules/markup/markdown/math/block_parser.go +++ b/modules/markup/markdown/math/block_parser.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package math diff --git a/modules/markup/markdown/math/block_renderer.go b/modules/markup/markdown/math/block_renderer.go index d502065259..84817ef1e4 100644 --- a/modules/markup/markdown/math/block_renderer.go +++ b/modules/markup/markdown/math/block_renderer.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package math diff --git a/modules/markup/markdown/math/inline_node.go b/modules/markup/markdown/math/inline_node.go index 245ff8dab0..2221a251bf 100644 --- a/modules/markup/markdown/math/inline_node.go +++ b/modules/markup/markdown/math/inline_node.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package math diff --git a/modules/markup/markdown/math/inline_parser.go b/modules/markup/markdown/math/inline_parser.go index 8dc88eb858..0ac25c2b2a 100644 --- a/modules/markup/markdown/math/inline_parser.go +++ b/modules/markup/markdown/math/inline_parser.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package math diff --git a/modules/markup/markdown/math/inline_renderer.go b/modules/markup/markdown/math/inline_renderer.go index e4c0f3761d..b4e9ade0ae 100644 --- a/modules/markup/markdown/math/inline_renderer.go +++ b/modules/markup/markdown/math/inline_renderer.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package math diff --git a/modules/markup/markdown/math/math.go b/modules/markup/markdown/math/math.go index 7854ac84db..8a50753574 100644 --- a/modules/markup/markdown/math/math.go +++ b/modules/markup/markdown/math/math.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package math diff --git a/modules/markup/markdown/meta.go b/modules/markup/markdown/meta.go index fb37236d77..bbefbd380c 100644 --- a/modules/markup/markdown/meta.go +++ b/modules/markup/markdown/meta.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package markdown diff --git a/modules/markup/markdown/meta_test.go b/modules/markup/markdown/meta_test.go index 720d0066f4..6949966328 100644 --- a/modules/markup/markdown/meta_test.go +++ b/modules/markup/markdown/meta_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package markdown @@ -9,82 +8,86 @@ import ( "strings" "testing" - "code.gitea.io/gitea/modules/structs" - "github.com/stretchr/testify/assert" ) -func validateMetadata(it structs.IssueTemplate) bool { - /* - A legacy to keep the unit tests working. - Copied from the method "func (it IssueTemplate) Valid() bool", the original method has been removed. - Because it becomes quite complicated to validate an issue template which is support yaml form now. - The new way to validate an issue template is to call the Validate in modules/issue/template, - */ +/* +IssueTemplate is a legacy to keep the unit tests working. +Copied from structs.IssueTemplate, the original type has been changed a lot to support yaml template. +*/ +type IssueTemplate struct { + Name string `json:"name" yaml:"name"` + Title string `json:"title" yaml:"title"` + About string `json:"about" yaml:"about"` + Labels []string `json:"labels" yaml:"labels"` + Ref string `json:"ref" yaml:"ref"` +} + +func (it *IssueTemplate) Valid() bool { return strings.TrimSpace(it.Name) != "" && strings.TrimSpace(it.About) != "" } func TestExtractMetadata(t *testing.T) { t.Run("ValidFrontAndBody", func(t *testing.T) { - var meta structs.IssueTemplate + var meta IssueTemplate body, err := ExtractMetadata(fmt.Sprintf("%s\n%s\n%s\n%s", sepTest, frontTest, sepTest, bodyTest), &meta) assert.NoError(t, err) assert.Equal(t, bodyTest, body) assert.Equal(t, metaTest, meta) - assert.True(t, validateMetadata(meta)) + assert.True(t, meta.Valid()) }) t.Run("NoFirstSeparator", func(t *testing.T) { - var meta structs.IssueTemplate + var meta IssueTemplate _, err := ExtractMetadata(fmt.Sprintf("%s\n%s\n%s", frontTest, sepTest, bodyTest), &meta) assert.Error(t, err) }) t.Run("NoLastSeparator", func(t *testing.T) { - var meta structs.IssueTemplate + var meta IssueTemplate _, err := ExtractMetadata(fmt.Sprintf("%s\n%s\n%s", sepTest, frontTest, bodyTest), &meta) assert.Error(t, err) }) t.Run("NoBody", func(t *testing.T) { - var meta structs.IssueTemplate + var meta IssueTemplate body, err := ExtractMetadata(fmt.Sprintf("%s\n%s\n%s", sepTest, frontTest, sepTest), &meta) assert.NoError(t, err) assert.Equal(t, "", body) assert.Equal(t, metaTest, meta) - assert.True(t, validateMetadata(meta)) + assert.True(t, meta.Valid()) }) } func TestExtractMetadataBytes(t *testing.T) { t.Run("ValidFrontAndBody", func(t *testing.T) { - var meta structs.IssueTemplate + var meta IssueTemplate body, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s\n%s", sepTest, frontTest, sepTest, bodyTest)), &meta) assert.NoError(t, err) assert.Equal(t, bodyTest, string(body)) assert.Equal(t, metaTest, meta) - assert.True(t, validateMetadata(meta)) + assert.True(t, meta.Valid()) }) t.Run("NoFirstSeparator", func(t *testing.T) { - var meta structs.IssueTemplate + var meta IssueTemplate _, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s", frontTest, sepTest, bodyTest)), &meta) assert.Error(t, err) }) t.Run("NoLastSeparator", func(t *testing.T) { - var meta structs.IssueTemplate + var meta IssueTemplate _, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s", sepTest, frontTest, bodyTest)), &meta) assert.Error(t, err) }) t.Run("NoBody", func(t *testing.T) { - var meta structs.IssueTemplate + var meta IssueTemplate body, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s", sepTest, frontTest, sepTest)), &meta) assert.NoError(t, err) assert.Equal(t, "", string(body)) assert.Equal(t, metaTest, meta) - assert.True(t, validateMetadata(meta)) + assert.True(t, meta.Valid()) }) } @@ -97,7 +100,7 @@ labels: - bug - "test label"` bodyTest = "This is the body" - metaTest = structs.IssueTemplate{ + metaTest = IssueTemplate{ Name: "Test", About: "A Test", Title: "Test Title", diff --git a/modules/markup/markdown/renderconfig.go b/modules/markup/markdown/renderconfig.go index 1ba75dbb68..f9c9cbc5f4 100644 --- a/modules/markup/markdown/renderconfig.go +++ b/modules/markup/markdown/renderconfig.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package markdown diff --git a/modules/markup/markdown/renderconfig_test.go b/modules/markup/markdown/renderconfig_test.go index 672edbf46d..f7f5e885a3 100644 --- a/modules/markup/markdown/renderconfig_test.go +++ b/modules/markup/markdown/renderconfig_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package markdown diff --git a/modules/markup/markdown/toc.go b/modules/markup/markdown/toc.go index 103894d1ab..3715f031af 100644 --- a/modules/markup/markdown/toc.go +++ b/modules/markup/markdown/toc.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package markdown diff --git a/modules/markup/mdstripper/mdstripper.go b/modules/markup/mdstripper/mdstripper.go index c7f8ee69f1..e19f8f6419 100644 --- a/modules/markup/mdstripper/mdstripper.go +++ b/modules/markup/mdstripper/mdstripper.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package mdstripper diff --git a/modules/markup/mdstripper/mdstripper_test.go b/modules/markup/mdstripper/mdstripper_test.go index 8045c34c07..ea34df0a3b 100644 --- a/modules/markup/mdstripper/mdstripper_test.go +++ b/modules/markup/mdstripper/mdstripper_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package mdstripper diff --git a/modules/markup/orgmode/orgmode.go b/modules/markup/orgmode/orgmode.go index abbff1e435..5a8485e571 100644 --- a/modules/markup/orgmode/orgmode.go +++ b/modules/markup/orgmode/orgmode.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package markup diff --git a/modules/markup/orgmode/orgmode_test.go b/modules/markup/orgmode/orgmode_test.go index cd12cd8c17..4acb678cd7 100644 --- a/modules/markup/orgmode/orgmode_test.go +++ b/modules/markup/orgmode/orgmode_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package markup diff --git a/modules/markup/renderer.go b/modules/markup/renderer.go index b3289cb3c3..5a31e961fb 100644 --- a/modules/markup/renderer.go +++ b/modules/markup/renderer.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package markup diff --git a/modules/markup/renderer_test.go b/modules/markup/renderer_test.go index 950ee15b91..624558c3f7 100644 --- a/modules/markup/renderer_test.go +++ b/modules/markup/renderer_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package markup_test diff --git a/modules/markup/sanitizer.go b/modules/markup/sanitizer.go index ff7165c131..e59f6c7c84 100644 --- a/modules/markup/sanitizer.go +++ b/modules/markup/sanitizer.go @@ -1,7 +1,6 @@ // Copyright 2017 The Gitea Authors. All rights reserved. // Copyright 2017 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package markup @@ -58,6 +57,13 @@ func createDefaultPolicy() *bluemonday.Policy { // For color preview policy.AllowAttrs("class").Matching(regexp.MustCompile(`^color-preview$`)).OnElements("span") + // For attention + policy.AllowAttrs("class").Matching(regexp.MustCompile(`^attention-\w+$`)).OnElements("strong") + policy.AllowAttrs("class").Matching(regexp.MustCompile(`^attention-icon attention-\w+$`)).OnElements("span", "strong") + policy.AllowAttrs("class").Matching(regexp.MustCompile(`^svg octicon-\w+$`)).OnElements("svg") + policy.AllowAttrs("viewBox", "width", "height", "aria-hidden").OnElements("svg") + policy.AllowAttrs("fill-rule", "d").OnElements("path") + // For Chroma markdown plugin policy.AllowAttrs("class").Matching(regexp.MustCompile(`^(chroma )?language-[\w-]+( display)?( is-loading)?$`)).OnElements("code") diff --git a/modules/markup/sanitizer_test.go b/modules/markup/sanitizer_test.go index b3b07404b4..c792ec2dc6 100644 --- a/modules/markup/sanitizer_test.go +++ b/modules/markup/sanitizer_test.go @@ -1,7 +1,6 @@ // Copyright 2017 The Gitea Authors. All rights reserved. // Copyright 2017 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package markup diff --git a/modules/mcaptcha/mcaptcha.go b/modules/mcaptcha/mcaptcha.go index 0c0fcce49d..74142aa863 100644 --- a/modules/mcaptcha/mcaptcha.go +++ b/modules/mcaptcha/mcaptcha.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package mcaptcha diff --git a/modules/metrics/collector.go b/modules/metrics/collector.go index dcd80b05a9..17f8dd133f 100755 --- a/modules/metrics/collector.go +++ b/modules/metrics/collector.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package metrics diff --git a/modules/migration/comment.go b/modules/migration/comment.go index 0447689b74..27ecaa830a 100644 --- a/modules/migration/comment.go +++ b/modules/migration/comment.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/downloader.go b/modules/migration/downloader.go index 7759c96056..ebd3672d63 100644 --- a/modules/migration/downloader.go +++ b/modules/migration/downloader.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/error.go b/modules/migration/error.go index b2608aa09f..64cda9d047 100644 --- a/modules/migration/error.go +++ b/modules/migration/error.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/file_format.go b/modules/migration/file_format.go index 30e1d256cd..f319f02ef1 100644 --- a/modules/migration/file_format.go +++ b/modules/migration/file_format.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package migration @@ -8,12 +7,13 @@ import ( "fmt" "os" "strings" + "time" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" "github.com/santhosh-tekuri/jsonschema/v5" - "gopkg.in/yaml.v2" + "gopkg.in/yaml.v3" ) // Load project data from file, with optional validation @@ -84,13 +84,9 @@ func validate(bs []byte, datatype interface{}, isJSON bool) error { func toStringKeys(val interface{}) (interface{}, error) { var err error switch val := val.(type) { - case map[interface{}]interface{}: + case map[string]interface{}: m := make(map[string]interface{}) for k, v := range val { - k, ok := k.(string) - if !ok { - return nil, fmt.Errorf("found non-string key %T %s", k, k) - } m[k], err = toStringKeys(v) if err != nil { return nil, err @@ -106,6 +102,8 @@ func toStringKeys(val interface{}) (interface{}, error) { } } return l, nil + case time.Time: + return val.Format(time.RFC3339), nil default: return val, nil } diff --git a/modules/migration/file_format_test.go b/modules/migration/file_format_test.go index 27104e209c..da997f645b 100644 --- a/modules/migration/file_format_test.go +++ b/modules/migration/file_format_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/issue.go b/modules/migration/issue.go index cc13570afb..7cb9f84b0d 100644 --- a/modules/migration/issue.go +++ b/modules/migration/issue.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/label.go b/modules/migration/label.go index f49fbe3ee4..38f0eb10da 100644 --- a/modules/migration/label.go +++ b/modules/migration/label.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/messenger.go b/modules/migration/messenger.go index fa8218cf93..1fd5456259 100644 --- a/modules/migration/messenger.go +++ b/modules/migration/messenger.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/milestone.go b/modules/migration/milestone.go index f3b725de67..34355b8f9c 100644 --- a/modules/migration/milestone.go +++ b/modules/migration/milestone.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/null_downloader.go b/modules/migration/null_downloader.go index ad925c32ce..e5b69331df 100644 --- a/modules/migration/null_downloader.go +++ b/modules/migration/null_downloader.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/options.go b/modules/migration/options.go index 1e92a1b0b3..234e72c295 100644 --- a/modules/migration/options.go +++ b/modules/migration/options.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/pullrequest.go b/modules/migration/pullrequest.go index dd520cd63f..4e7500f0d6 100644 --- a/modules/migration/pullrequest.go +++ b/modules/migration/pullrequest.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/reaction.go b/modules/migration/reaction.go index 0946bdd40b..ca1df6c763 100644 --- a/modules/migration/reaction.go +++ b/modules/migration/reaction.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/release.go b/modules/migration/release.go index 923b3817b0..f92cf25e7b 100644 --- a/modules/migration/release.go +++ b/modules/migration/release.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/repo.go b/modules/migration/repo.go index 75622595d9..22c2cf6fb3 100644 --- a/modules/migration/repo.go +++ b/modules/migration/repo.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/retry_downloader.go b/modules/migration/retry_downloader.go index 2e40c102be..1cacf5f375 100644 --- a/modules/migration/retry_downloader.go +++ b/modules/migration/retry_downloader.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/review.go b/modules/migration/review.go index b5a054c642..a420c130c7 100644 --- a/modules/migration/review.go +++ b/modules/migration/review.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/migration/schemas_bindata.go b/modules/migration/schemas_bindata.go index febe0f75c0..c5db3b3461 100644 --- a/modules/migration/schemas_bindata.go +++ b/modules/migration/schemas_bindata.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT //go:build bindata diff --git a/modules/migration/schemas_dynamic.go b/modules/migration/schemas_dynamic.go index 1b767b2e72..dca109d6af 100644 --- a/modules/migration/schemas_dynamic.go +++ b/modules/migration/schemas_dynamic.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT //go:build !bindata diff --git a/modules/migration/schemas_static.go b/modules/migration/schemas_static.go index 02957fc4ed..8a0c340a65 100644 --- a/modules/migration/schemas_static.go +++ b/modules/migration/schemas_static.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT //go:build bindata diff --git a/modules/migration/uploader.go b/modules/migration/uploader.go index 57571861aa..ff642aa4fa 100644 --- a/modules/migration/uploader.go +++ b/modules/migration/uploader.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migration diff --git a/modules/mirror/mirror.go b/modules/mirror/mirror.go index b261bd0242..37b4c2ac95 100644 --- a/modules/mirror/mirror.go +++ b/modules/mirror/mirror.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package mirror diff --git a/modules/nosql/leveldb.go b/modules/nosql/leveldb.go index 5da2291e03..aac5b2178e 100644 --- a/modules/nosql/leveldb.go +++ b/modules/nosql/leveldb.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package nosql diff --git a/modules/nosql/manager.go b/modules/nosql/manager.go index 6092a67827..bc530bc148 100644 --- a/modules/nosql/manager.go +++ b/modules/nosql/manager.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package nosql diff --git a/modules/nosql/manager_leveldb.go b/modules/nosql/manager_leveldb.go index 7539952cf1..078a802811 100644 --- a/modules/nosql/manager_leveldb.go +++ b/modules/nosql/manager_leveldb.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package nosql diff --git a/modules/nosql/manager_redis.go b/modules/nosql/manager_redis.go index f7d5a72ed2..728bc2f2ef 100644 --- a/modules/nosql/manager_redis.go +++ b/modules/nosql/manager_redis.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package nosql diff --git a/modules/nosql/manager_redis_test.go b/modules/nosql/manager_redis_test.go index 99a8856f1e..d979ea07f6 100644 --- a/modules/nosql/manager_redis_test.go +++ b/modules/nosql/manager_redis_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package nosql diff --git a/modules/nosql/redis.go b/modules/nosql/redis.go index 13795f3d7b..52e8ff9d02 100644 --- a/modules/nosql/redis.go +++ b/modules/nosql/redis.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package nosql diff --git a/modules/nosql/redis_test.go b/modules/nosql/redis_test.go index c70d236bdc..43652e314c 100644 --- a/modules/nosql/redis_test.go +++ b/modules/nosql/redis_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package nosql diff --git a/modules/notification/action/action.go b/modules/notification/action/action.go index 44d115f3d7..2f882c2cb8 100644 --- a/modules/notification/action/action.go +++ b/modules/notification/action/action.go @@ -1,24 +1,21 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package action import ( + "context" "fmt" "path" "strings" activities_model "code.gitea.io/gitea/models/activities" - "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" - "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/notification/base" - "code.gitea.io/gitea/modules/process" "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/util" ) @@ -34,18 +31,18 @@ func NewNotifier() base.Notifier { return &actionNotifier{} } -func (a *actionNotifier) NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) { - if err := issue.LoadPoster(); err != nil { +func (a *actionNotifier) NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) { + if err := issue.LoadPoster(ctx); err != nil { log.Error("issue.LoadPoster: %v", err) return } - if err := issue.LoadRepo(db.DefaultContext); err != nil { + if err := issue.LoadRepo(ctx); err != nil { log.Error("issue.LoadRepo: %v", err) return } repo := issue.Repo - if err := activities_model.NotifyWatchers(&activities_model.Action{ + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: issue.Poster.ID, ActUser: issue.Poster, OpType: activities_model.ActionCreateIssue, @@ -59,7 +56,7 @@ func (a *actionNotifier) NotifyNewIssue(issue *issues_model.Issue, mentions []*u } // NotifyIssueChangeStatus notifies close or reopen issue to notifiers -func (a *actionNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, closeOrReopen bool) { +func (a *actionNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, closeOrReopen bool) { // Compose comment action, could be plain comment, close or reopen issue/pull request. // This object will be used to notify watchers in the end of function. act := &activities_model.Action{ @@ -86,13 +83,13 @@ func (a *actionNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *i } // Notify watchers for whatever action comes in, ignore if no action type. - if err := activities_model.NotifyWatchers(act); err != nil { + if err := activities_model.NotifyWatchers(ctx, act); err != nil { log.Error("NotifyWatchers: %v", err) } } // NotifyCreateIssueComment notifies comment on an issue to notifiers -func (a *actionNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, +func (a *actionNotifier) NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User, ) { act := &activities_model.Action{ @@ -122,26 +119,26 @@ func (a *actionNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *r } // Notify watchers for whatever action comes in, ignore if no action type. - if err := activities_model.NotifyWatchers(act); err != nil { + if err := activities_model.NotifyWatchers(ctx, act); err != nil { log.Error("NotifyWatchers: %v", err) } } -func (a *actionNotifier) NotifyNewPullRequest(pull *issues_model.PullRequest, mentions []*user_model.User) { - if err := pull.LoadIssue(); err != nil { +func (a *actionNotifier) NotifyNewPullRequest(ctx context.Context, pull *issues_model.PullRequest, mentions []*user_model.User) { + if err := pull.LoadIssue(ctx); err != nil { log.Error("pull.LoadIssue: %v", err) return } - if err := pull.Issue.LoadRepo(db.DefaultContext); err != nil { + if err := pull.Issue.LoadRepo(ctx); err != nil { log.Error("pull.Issue.LoadRepo: %v", err) return } - if err := pull.Issue.LoadPoster(); err != nil { + if err := pull.Issue.LoadPoster(ctx); err != nil { log.Error("pull.Issue.LoadPoster: %v", err) return } - if err := activities_model.NotifyWatchers(&activities_model.Action{ + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: pull.Issue.Poster.ID, ActUser: pull.Issue.Poster, OpType: activities_model.ActionCreatePullRequest, @@ -154,8 +151,8 @@ func (a *actionNotifier) NotifyNewPullRequest(pull *issues_model.PullRequest, me } } -func (a *actionNotifier) NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldRepoName string) { - if err := activities_model.NotifyWatchers(&activities_model.Action{ +func (a *actionNotifier) NotifyRenameRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldRepoName string) { + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: doer.ID, ActUser: doer, OpType: activities_model.ActionRenameRepo, @@ -168,8 +165,8 @@ func (a *actionNotifier) NotifyRenameRepository(doer *user_model.User, repo *rep } } -func (a *actionNotifier) NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) { - if err := activities_model.NotifyWatchers(&activities_model.Action{ +func (a *actionNotifier) NotifyTransferRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) { + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: doer.ID, ActUser: doer, OpType: activities_model.ActionTransferRepo, @@ -182,8 +179,8 @@ func (a *actionNotifier) NotifyTransferRepository(doer *user_model.User, repo *r } } -func (a *actionNotifier) NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) { - if err := activities_model.NotifyWatchers(&activities_model.Action{ +func (a *actionNotifier) NotifyCreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) { + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: doer.ID, ActUser: doer, OpType: activities_model.ActionCreateRepo, @@ -195,8 +192,8 @@ func (a *actionNotifier) NotifyCreateRepository(doer, u *user_model.User, repo * } } -func (a *actionNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) { - if err := activities_model.NotifyWatchers(&activities_model.Action{ +func (a *actionNotifier) NotifyForkRepository(ctx context.Context, doer *user_model.User, oldRepo, repo *repo_model.Repository) { + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: doer.ID, ActUser: doer, OpType: activities_model.ActionCreateRepo, @@ -208,11 +205,8 @@ func (a *actionNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, re } } -func (a *actionNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("actionNotifier.NotifyPullRequestReview Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID)) - defer finished() - - if err := review.LoadReviewer(); err != nil { +func (a *actionNotifier) NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { + if err := review.LoadReviewer(ctx); err != nil { log.Error("LoadReviewer '%d/%d': %v", review.ID, review.ReviewerID, err) return } @@ -269,8 +263,8 @@ func (a *actionNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, r } } -func (*actionNotifier) NotifyMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { - if err := activities_model.NotifyWatchers(&activities_model.Action{ +func (*actionNotifier) NotifyMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: doer.ID, ActUser: doer, OpType: activities_model.ActionMergePullRequest, @@ -283,8 +277,8 @@ func (*actionNotifier) NotifyMergePullRequest(pr *issues_model.PullRequest, doer } } -func (*actionNotifier) NotifyAutoMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { - if err := activities_model.NotifyWatchers(&activities_model.Action{ +func (*actionNotifier) NotifyAutoMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: doer.ID, ActUser: doer, OpType: activities_model.ActionAutoMergePullRequest, @@ -297,12 +291,12 @@ func (*actionNotifier) NotifyAutoMergePullRequest(pr *issues_model.PullRequest, } } -func (*actionNotifier) NotifyPullRevieweDismiss(doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { +func (*actionNotifier) NotifyPullRevieweDismiss(ctx context.Context, doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { reviewerName := review.Reviewer.Name if len(review.OriginalAuthor) > 0 { reviewerName = review.OriginalAuthor } - if err := activities_model.NotifyWatchers(&activities_model.Action{ + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: doer.ID, ActUser: doer, OpType: activities_model.ActionPullReviewDismissed, @@ -317,7 +311,7 @@ func (*actionNotifier) NotifyPullRevieweDismiss(doer *user_model.User, review *i } } -func (a *actionNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func (a *actionNotifier) NotifyPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { data, err := json.Marshal(commits) if err != nil { log.Error("Marshal: %v", err) @@ -336,7 +330,7 @@ func (a *actionNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_m opType = activities_model.ActionDeleteBranch } - if err = activities_model.NotifyWatchers(&activities_model.Action{ + if err = activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: pusher.ID, ActUser: pusher, OpType: opType, @@ -346,17 +340,17 @@ func (a *actionNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_m RefName: opts.RefFullName, IsPrivate: repo.IsPrivate, }); err != nil { - log.Error("notifyWatchers: %v", err) + log.Error("NotifyWatchers: %v", err) } } -func (a *actionNotifier) NotifyCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { +func (a *actionNotifier) NotifyCreateRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { opType := activities_model.ActionCommitRepo if refType == "tag" { // has sent same action in `NotifyPushCommits`, so skip it. return } - if err := activities_model.NotifyWatchers(&activities_model.Action{ + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: doer.ID, ActUser: doer, OpType: opType, @@ -365,17 +359,17 @@ func (a *actionNotifier) NotifyCreateRef(doer *user_model.User, repo *repo_model IsPrivate: repo.IsPrivate, RefName: refFullName, }); err != nil { - log.Error("notifyWatchers: %v", err) + log.Error("NotifyWatchers: %v", err) } } -func (a *actionNotifier) NotifyDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { +func (a *actionNotifier) NotifyDeleteRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { opType := activities_model.ActionDeleteBranch if refType == "tag" { // has sent same action in `NotifyPushCommits`, so skip it. return } - if err := activities_model.NotifyWatchers(&activities_model.Action{ + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: doer.ID, ActUser: doer, OpType: opType, @@ -384,20 +378,20 @@ func (a *actionNotifier) NotifyDeleteRef(doer *user_model.User, repo *repo_model IsPrivate: repo.IsPrivate, RefName: refFullName, }); err != nil { - log.Error("notifyWatchers: %v", err) + log.Error("NotifyWatchers: %v", err) } } -func (a *actionNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func (a *actionNotifier) NotifySyncPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { data, err := json.Marshal(commits) if err != nil { log.Error("json.Marshal: %v", err) return } - if err := activities_model.NotifyWatchers(&activities_model.Action{ + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: repo.OwnerID, - ActUser: repo.MustOwner(), + ActUser: repo.MustOwner(ctx), OpType: activities_model.ActionMirrorSyncPush, RepoID: repo.ID, Repo: repo, @@ -405,44 +399,44 @@ func (a *actionNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *re RefName: opts.RefFullName, Content: string(data), }); err != nil { - log.Error("notifyWatchers: %v", err) + log.Error("NotifyWatchers: %v", err) } } -func (a *actionNotifier) NotifySyncCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { - if err := activities_model.NotifyWatchers(&activities_model.Action{ +func (a *actionNotifier) NotifySyncCreateRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: repo.OwnerID, - ActUser: repo.MustOwner(), + ActUser: repo.MustOwner(ctx), OpType: activities_model.ActionMirrorSyncCreate, RepoID: repo.ID, Repo: repo, IsPrivate: repo.IsPrivate, RefName: refFullName, }); err != nil { - log.Error("notifyWatchers: %v", err) + log.Error("NotifyWatchers: %v", err) } } -func (a *actionNotifier) NotifySyncDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { - if err := activities_model.NotifyWatchers(&activities_model.Action{ +func (a *actionNotifier) NotifySyncDeleteRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: repo.OwnerID, - ActUser: repo.MustOwner(), + ActUser: repo.MustOwner(ctx), OpType: activities_model.ActionMirrorSyncDelete, RepoID: repo.ID, Repo: repo, IsPrivate: repo.IsPrivate, RefName: refFullName, }); err != nil { - log.Error("notifyWatchers: %v", err) + log.Error("NotifyWatchers: %v", err) } } -func (a *actionNotifier) NotifyNewRelease(rel *repo_model.Release) { - if err := rel.LoadAttributes(); err != nil { - log.Error("NotifyNewRelease: %v", err) +func (a *actionNotifier) NotifyNewRelease(ctx context.Context, rel *repo_model.Release) { + if err := rel.LoadAttributes(ctx); err != nil { + log.Error("LoadAttributes: %v", err) return } - if err := activities_model.NotifyWatchers(&activities_model.Action{ + if err := activities_model.NotifyWatchers(ctx, &activities_model.Action{ ActUserID: rel.PublisherID, ActUser: rel.Publisher, OpType: activities_model.ActionPublishRelease, @@ -452,6 +446,6 @@ func (a *actionNotifier) NotifyNewRelease(rel *repo_model.Release) { Content: rel.Title, RefName: rel.TagName, }); err != nil { - log.Error("notifyWatchers: %v", err) + log.Error("NotifyWatchers: %v", err) } } diff --git a/modules/notification/action/action_test.go b/modules/notification/action/action_test.go index 79a938d6cd..05ce70f388 100644 --- a/modules/notification/action/action_test.go +++ b/modules/notification/action/action_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package action @@ -10,6 +9,7 @@ import ( "testing" activities_model "code.gitea.io/gitea/models/activities" + "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -46,7 +46,7 @@ func TestRenameRepoAction(t *testing.T) { } unittest.AssertNotExistsBean(t, actionBean) - NewNotifier().NotifyRenameRepository(user, repo, oldRepoName) + NewNotifier().NotifyRenameRepository(db.DefaultContext, user, repo, oldRepoName) unittest.AssertExistsAndLoadBean(t, actionBean) unittest.CheckConsistencyFor(t, &activities_model.Action{}) diff --git a/modules/notification/base/notifier.go b/modules/notification/base/notifier.go index 9edab8213f..dbed20ba3a 100644 --- a/modules/notification/base/notifier.go +++ b/modules/notification/base/notifier.go @@ -1,10 +1,11 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package base import ( + "context" + issues_model "code.gitea.io/gitea/models/issues" packages_model "code.gitea.io/gitea/models/packages" repo_model "code.gitea.io/gitea/models/repo" @@ -15,50 +16,50 @@ import ( // Notifier defines an interface to notify receiver type Notifier interface { Run() - NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) - NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) - NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) - NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) - NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldRepoName string) - NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) - NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) - NotifyIssueChangeStatus(*user_model.User, *issues_model.Issue, *issues_model.Comment, bool) - NotifyDeleteIssue(*user_model.User, *issues_model.Issue) - NotifyIssueChangeMilestone(doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) - NotifyIssueChangeAssignee(doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) - NotifyPullReviewRequest(doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) - NotifyIssueChangeContent(doer *user_model.User, issue *issues_model.Issue, oldContent string) - NotifyIssueClearLabels(doer *user_model.User, issue *issues_model.Issue) - NotifyIssueChangeTitle(doer *user_model.User, issue *issues_model.Issue, oldTitle string) - NotifyIssueChangeRef(doer *user_model.User, issue *issues_model.Issue, oldRef string) - NotifyIssueChangeLabels(doer *user_model.User, issue *issues_model.Issue, + NotifyCreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) + NotifyMigrateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) + NotifyDeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository) + NotifyForkRepository(ctx context.Context, doer *user_model.User, oldRepo, repo *repo_model.Repository) + NotifyRenameRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldRepoName string) + NotifyTransferRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) + NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) + NotifyIssueChangeStatus(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, closeOrReopen bool) + NotifyDeleteIssue(ctx context.Context, doer *user_model.User, issue *issues_model.Issue) + NotifyIssueChangeMilestone(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) + NotifyIssueChangeAssignee(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) + NotifyPullReviewRequest(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) + NotifyIssueChangeContent(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldContent string) + NotifyIssueClearLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue) + NotifyIssueChangeTitle(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) + NotifyIssueChangeRef(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldRef string) + NotifyIssueChangeLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, addedLabels, removedLabels []*issues_model.Label) - NotifyNewPullRequest(pr *issues_model.PullRequest, mentions []*user_model.User) - NotifyMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) - NotifyAutoMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) - NotifyPullRequestSynchronized(doer *user_model.User, pr *issues_model.PullRequest) - NotifyPullRequestReview(pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) - NotifyPullRequestCodeComment(pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) - NotifyPullRequestChangeTargetBranch(doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) - NotifyPullRequestPushCommits(doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) - NotifyPullRevieweDismiss(doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) - NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, + NotifyNewPullRequest(ctx context.Context, pr *issues_model.PullRequest, mentions []*user_model.User) + NotifyMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) + NotifyAutoMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) + NotifyPullRequestSynchronized(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) + NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) + NotifyPullRequestCodeComment(ctx context.Context, pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) + NotifyPullRequestChangeTargetBranch(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) + NotifyPullRequestPushCommits(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) + NotifyPullReviewDismiss(ctx context.Context, doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) + NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User) - NotifyUpdateComment(*user_model.User, *issues_model.Comment, string) - NotifyDeleteComment(*user_model.User, *issues_model.Comment) - NotifyNewWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) - NotifyEditWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) - NotifyDeleteWikiPage(doer *user_model.User, repo *repo_model.Repository, page string) - NotifyNewRelease(rel *repo_model.Release) - NotifyUpdateRelease(doer *user_model.User, rel *repo_model.Release) - NotifyDeleteRelease(doer *user_model.User, rel *repo_model.Release) - NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) - NotifyCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) - NotifyDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) - NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) - NotifySyncCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) - NotifySyncDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) - NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) - NotifyPackageCreate(doer *user_model.User, pd *packages_model.PackageDescriptor) - NotifyPackageDelete(doer *user_model.User, pd *packages_model.PackageDescriptor) + NotifyUpdateComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment, oldContent string) + NotifyDeleteComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment) + NotifyNewWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) + NotifyEditWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) + NotifyDeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page string) + NotifyNewRelease(ctx context.Context, rel *repo_model.Release) + NotifyUpdateRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release) + NotifyDeleteRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release) + NotifyPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) + NotifyCreateRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) + NotifyDeleteRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) + NotifySyncPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) + NotifySyncCreateRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) + NotifySyncDeleteRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) + NotifyRepoPendingTransfer(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository) + NotifyPackageCreate(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) + NotifyPackageDelete(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) } diff --git a/modules/notification/base/null.go b/modules/notification/base/null.go index f051fbc26f..de5f072d24 100644 --- a/modules/notification/base/null.go +++ b/modules/notification/base/null.go @@ -1,10 +1,11 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package base import ( + "context" + issues_model "code.gitea.io/gitea/models/issues" packages_model "code.gitea.io/gitea/models/packages" repo_model "code.gitea.io/gitea/models/repo" @@ -22,179 +23,179 @@ func (*NullNotifier) Run() { } // NotifyCreateIssueComment places a place holder function -func (*NullNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, +func (*NullNotifier) NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User) { } // NotifyNewIssue places a place holder function -func (*NullNotifier) NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) { +func (*NullNotifier) NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) { } // NotifyIssueChangeStatus places a place holder function -func (*NullNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) { +func (*NullNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) { } // NotifyDeleteIssue notify when some issue deleted -func (*NullNotifier) NotifyDeleteIssue(doer *user_model.User, issue *issues_model.Issue) { +func (*NullNotifier) NotifyDeleteIssue(ctx context.Context, doer *user_model.User, issue *issues_model.Issue) { } // NotifyNewPullRequest places a place holder function -func (*NullNotifier) NotifyNewPullRequest(pr *issues_model.PullRequest, mentions []*user_model.User) { +func (*NullNotifier) NotifyNewPullRequest(ctx context.Context, pr *issues_model.PullRequest, mentions []*user_model.User) { } // NotifyPullRequestReview places a place holder function -func (*NullNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, r *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { +func (*NullNotifier) NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, r *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { } // NotifyPullRequestCodeComment places a place holder function -func (*NullNotifier) NotifyPullRequestCodeComment(pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) { +func (*NullNotifier) NotifyPullRequestCodeComment(ctx context.Context, pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) { } // NotifyMergePullRequest places a place holder function -func (*NullNotifier) NotifyMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { +func (*NullNotifier) NotifyMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { } // NotifyAutoMergePullRequest places a place holder function -func (*NullNotifier) NotifyAutoMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { +func (*NullNotifier) NotifyAutoMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { } // NotifyPullRequestSynchronized places a place holder function -func (*NullNotifier) NotifyPullRequestSynchronized(doer *user_model.User, pr *issues_model.PullRequest) { +func (*NullNotifier) NotifyPullRequestSynchronized(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { } // NotifyPullRequestChangeTargetBranch places a place holder function -func (*NullNotifier) NotifyPullRequestChangeTargetBranch(doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) { +func (*NullNotifier) NotifyPullRequestChangeTargetBranch(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) { } // NotifyPullRequestPushCommits notifies when push commits to pull request's head branch -func (*NullNotifier) NotifyPullRequestPushCommits(doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) { +func (*NullNotifier) NotifyPullRequestPushCommits(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) { } -// NotifyPullRevieweDismiss notifies when a review was dismissed by repo admin -func (*NullNotifier) NotifyPullRevieweDismiss(doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { +// NotifyPullReviewDismiss notifies when a review was dismissed by repo admin +func (*NullNotifier) NotifyPullReviewDismiss(ctx context.Context, doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { } // NotifyUpdateComment places a place holder function -func (*NullNotifier) NotifyUpdateComment(doer *user_model.User, c *issues_model.Comment, oldContent string) { +func (*NullNotifier) NotifyUpdateComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment, oldContent string) { } // NotifyDeleteComment places a place holder function -func (*NullNotifier) NotifyDeleteComment(doer *user_model.User, c *issues_model.Comment) { +func (*NullNotifier) NotifyDeleteComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment) { } // NotifyNewWikiPage places a place holder function -func (*NullNotifier) NotifyNewWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) { +func (*NullNotifier) NotifyNewWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) { } // NotifyEditWikiPage places a place holder function -func (*NullNotifier) NotifyEditWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) { +func (*NullNotifier) NotifyEditWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) { } // NotifyDeleteWikiPage places a place holder function -func (*NullNotifier) NotifyDeleteWikiPage(doer *user_model.User, repo *repo_model.Repository, page string) { +func (*NullNotifier) NotifyDeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page string) { } // NotifyNewRelease places a place holder function -func (*NullNotifier) NotifyNewRelease(rel *repo_model.Release) { +func (*NullNotifier) NotifyNewRelease(ctx context.Context, rel *repo_model.Release) { } // NotifyUpdateRelease places a place holder function -func (*NullNotifier) NotifyUpdateRelease(doer *user_model.User, rel *repo_model.Release) { +func (*NullNotifier) NotifyUpdateRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release) { } // NotifyDeleteRelease places a place holder function -func (*NullNotifier) NotifyDeleteRelease(doer *user_model.User, rel *repo_model.Release) { +func (*NullNotifier) NotifyDeleteRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release) { } // NotifyIssueChangeMilestone places a place holder function -func (*NullNotifier) NotifyIssueChangeMilestone(doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) { +func (*NullNotifier) NotifyIssueChangeMilestone(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) { } // NotifyIssueChangeContent places a place holder function -func (*NullNotifier) NotifyIssueChangeContent(doer *user_model.User, issue *issues_model.Issue, oldContent string) { +func (*NullNotifier) NotifyIssueChangeContent(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldContent string) { } // NotifyIssueChangeAssignee places a place holder function -func (*NullNotifier) NotifyIssueChangeAssignee(doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { +func (*NullNotifier) NotifyIssueChangeAssignee(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { } // NotifyPullReviewRequest places a place holder function -func (*NullNotifier) NotifyPullReviewRequest(doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) { +func (*NullNotifier) NotifyPullReviewRequest(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) { } // NotifyIssueClearLabels places a place holder function -func (*NullNotifier) NotifyIssueClearLabels(doer *user_model.User, issue *issues_model.Issue) { +func (*NullNotifier) NotifyIssueClearLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue) { } // NotifyIssueChangeTitle places a place holder function -func (*NullNotifier) NotifyIssueChangeTitle(doer *user_model.User, issue *issues_model.Issue, oldTitle string) { +func (*NullNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) { } // NotifyIssueChangeRef places a place holder function -func (*NullNotifier) NotifyIssueChangeRef(doer *user_model.User, issue *issues_model.Issue, oldTitle string) { +func (*NullNotifier) NotifyIssueChangeRef(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) { } // NotifyIssueChangeLabels places a place holder function -func (*NullNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *issues_model.Issue, +func (*NullNotifier) NotifyIssueChangeLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, addedLabels, removedLabels []*issues_model.Label) { } // NotifyCreateRepository places a place holder function -func (*NullNotifier) NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) { +func (*NullNotifier) NotifyCreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) { } // NotifyDeleteRepository places a place holder function -func (*NullNotifier) NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) { +func (*NullNotifier) NotifyDeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository) { } // NotifyForkRepository places a place holder function -func (*NullNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) { +func (*NullNotifier) NotifyForkRepository(ctx context.Context, doer *user_model.User, oldRepo, repo *repo_model.Repository) { } // NotifyMigrateRepository places a place holder function -func (*NullNotifier) NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) { +func (*NullNotifier) NotifyMigrateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) { } // NotifyPushCommits notifies commits pushed to notifiers -func (*NullNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func (*NullNotifier) NotifyPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { } // NotifyCreateRef notifies branch or tag creation to notifiers -func (*NullNotifier) NotifyCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { +func (*NullNotifier) NotifyCreateRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { } // NotifyDeleteRef notifies branch or tag deletion to notifiers -func (*NullNotifier) NotifyDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { +func (*NullNotifier) NotifyDeleteRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { } // NotifyRenameRepository places a place holder function -func (*NullNotifier) NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldRepoName string) { +func (*NullNotifier) NotifyRenameRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldRepoName string) { } // NotifyTransferRepository places a place holder function -func (*NullNotifier) NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) { +func (*NullNotifier) NotifyTransferRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldOwnerName string) { } // NotifySyncPushCommits places a place holder function -func (*NullNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func (*NullNotifier) NotifySyncPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { } // NotifySyncCreateRef places a place holder function -func (*NullNotifier) NotifySyncCreateRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { +func (*NullNotifier) NotifySyncCreateRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { } // NotifySyncDeleteRef places a place holder function -func (*NullNotifier) NotifySyncDeleteRef(doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { +func (*NullNotifier) NotifySyncDeleteRef(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, refType, refFullName string) { } // NotifyRepoPendingTransfer places a place holder function -func (*NullNotifier) NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) { +func (*NullNotifier) NotifyRepoPendingTransfer(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository) { } // NotifyPackageCreate places a place holder function -func (*NullNotifier) NotifyPackageCreate(doer *user_model.User, pd *packages_model.PackageDescriptor) { +func (*NullNotifier) NotifyPackageCreate(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) { } // NotifyPackageDelete places a place holder function -func (*NullNotifier) NotifyPackageDelete(doer *user_model.User, pd *packages_model.PackageDescriptor) { +func (*NullNotifier) NotifyPackageDelete(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) { } diff --git a/modules/notification/indexer/indexer.go b/modules/notification/indexer/indexer.go index fc9afdd4bc..c67f79d0f2 100644 --- a/modules/notification/indexer/indexer.go +++ b/modules/notification/indexer/indexer.go @@ -1,10 +1,11 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package indexer import ( + "context" + issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" @@ -29,13 +30,13 @@ func NewNotifier() base.Notifier { return &indexerNotifier{} } -func (r *indexerNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, +func (r *indexerNotifier) NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User, ) { if comment.Type == issues_model.CommentTypeComment { if issue.Comments == nil { - if err := issue.LoadDiscussComments(); err != nil { - log.Error("LoadComments failed: %v", err) + if err := issue.LoadDiscussComments(ctx); err != nil { + log.Error("LoadDiscussComments failed: %v", err) return } } else { @@ -46,15 +47,15 @@ func (r *indexerNotifier) NotifyCreateIssueComment(doer *user_model.User, repo * } } -func (r *indexerNotifier) NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) { +func (r *indexerNotifier) NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) { issue_indexer.UpdateIssueIndexer(issue) } -func (r *indexerNotifier) NotifyNewPullRequest(pr *issues_model.PullRequest, mentions []*user_model.User) { +func (r *indexerNotifier) NotifyNewPullRequest(ctx context.Context, pr *issues_model.PullRequest, mentions []*user_model.User) { issue_indexer.UpdateIssueIndexer(pr.Issue) } -func (r *indexerNotifier) NotifyUpdateComment(doer *user_model.User, c *issues_model.Comment, oldContent string) { +func (r *indexerNotifier) NotifyUpdateComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment, oldContent string) { if c.Type == issues_model.CommentTypeComment { var found bool if c.Issue.Comments != nil { @@ -68,8 +69,8 @@ func (r *indexerNotifier) NotifyUpdateComment(doer *user_model.User, c *issues_m } if !found { - if err := c.Issue.LoadDiscussComments(); err != nil { - log.Error("LoadComments failed: %v", err) + if err := c.Issue.LoadDiscussComments(ctx); err != nil { + log.Error("LoadDiscussComments failed: %v", err) return } } @@ -78,9 +79,9 @@ func (r *indexerNotifier) NotifyUpdateComment(doer *user_model.User, c *issues_m } } -func (r *indexerNotifier) NotifyDeleteComment(doer *user_model.User, comment *issues_model.Comment) { +func (r *indexerNotifier) NotifyDeleteComment(ctx context.Context, doer *user_model.User, comment *issues_model.Comment) { if comment.Type == issues_model.CommentTypeComment { - if err := comment.LoadIssue(); err != nil { + if err := comment.LoadIssue(ctx); err != nil { log.Error("LoadIssue: %v", err) return } @@ -97,8 +98,8 @@ func (r *indexerNotifier) NotifyDeleteComment(doer *user_model.User, comment *is } if !found { - if err := comment.Issue.LoadDiscussComments(); err != nil { - log.Error("LoadComments failed: %v", err) + if err := comment.Issue.LoadDiscussComments(ctx); err != nil { + log.Error("LoadDiscussComments failed: %v", err) return } } @@ -107,15 +108,15 @@ func (r *indexerNotifier) NotifyDeleteComment(doer *user_model.User, comment *is } } -func (r *indexerNotifier) NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) { - issue_indexer.DeleteRepoIssueIndexer(repo) +func (r *indexerNotifier) NotifyDeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository) { + issue_indexer.DeleteRepoIssueIndexer(ctx, repo) if setting.Indexer.RepoIndexerEnabled { code_indexer.UpdateRepoIndexer(repo) } } -func (r *indexerNotifier) NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) { - issue_indexer.UpdateRepoIndexer(repo) +func (r *indexerNotifier) NotifyMigrateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) { + issue_indexer.UpdateRepoIndexer(ctx, repo) if setting.Indexer.RepoIndexerEnabled && !repo.IsEmpty { code_indexer.UpdateRepoIndexer(repo) } @@ -124,7 +125,7 @@ func (r *indexerNotifier) NotifyMigrateRepository(doer, u *user_model.User, repo } } -func (r *indexerNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func (r *indexerNotifier) NotifyPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { if setting.Indexer.RepoIndexerEnabled && opts.RefFullName == git.BranchPrefix+repo.DefaultBranch { code_indexer.UpdateRepoIndexer(repo) } @@ -133,7 +134,7 @@ func (r *indexerNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_ } } -func (r *indexerNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func (r *indexerNotifier) NotifySyncPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { if setting.Indexer.RepoIndexerEnabled && opts.RefFullName == git.BranchPrefix+repo.DefaultBranch { code_indexer.UpdateRepoIndexer(repo) } @@ -142,14 +143,14 @@ func (r *indexerNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *r } } -func (r *indexerNotifier) NotifyIssueChangeContent(doer *user_model.User, issue *issues_model.Issue, oldContent string) { +func (r *indexerNotifier) NotifyIssueChangeContent(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldContent string) { issue_indexer.UpdateIssueIndexer(issue) } -func (r *indexerNotifier) NotifyIssueChangeTitle(doer *user_model.User, issue *issues_model.Issue, oldTitle string) { +func (r *indexerNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) { issue_indexer.UpdateIssueIndexer(issue) } -func (r *indexerNotifier) NotifyIssueChangeRef(doer *user_model.User, issue *issues_model.Issue, oldRef string) { +func (r *indexerNotifier) NotifyIssueChangeRef(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldRef string) { issue_indexer.UpdateIssueIndexer(issue) } diff --git a/modules/notification/mail/mail.go b/modules/notification/mail/mail.go index 54f561839d..18f7fa22ae 100644 --- a/modules/notification/mail/mail.go +++ b/modules/notification/mail/mail.go @@ -1,20 +1,18 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package mail import ( + "context" "fmt" activities_model "code.gitea.io/gitea/models/activities" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" - "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/notification/base" - "code.gitea.io/gitea/modules/process" "code.gitea.io/gitea/services/mailer" ) @@ -29,12 +27,9 @@ func NewNotifier() base.Notifier { return &mailNotifier{} } -func (m *mailNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, +func (m *mailNotifier) NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User, ) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("mailNotifier.NotifyCreateIssueComment Issue[%d] #%d in [%d]", issue.ID, issue.Index, issue.RepoID)) - defer finished() - var act activities_model.ActionType if comment.Type == issues_model.CommentTypeClose { act = activities_model.ActionCloseIssue @@ -53,13 +48,13 @@ func (m *mailNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *rep } } -func (m *mailNotifier) NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) { - if err := mailer.MailParticipants(issue, issue.Poster, activities_model.ActionCreateIssue, mentions); err != nil { +func (m *mailNotifier) NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) { + if err := mailer.MailParticipants(ctx, issue, issue.Poster, activities_model.ActionCreateIssue, mentions); err != nil { log.Error("MailParticipants: %v", err) } } -func (m *mailNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) { +func (m *mailNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) { var actionType activities_model.ActionType if issue.IsPull { if isClosed { @@ -75,33 +70,30 @@ func (m *mailNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *iss } } - if err := mailer.MailParticipants(issue, doer, actionType, nil); err != nil { + if err := mailer.MailParticipants(ctx, issue, doer, actionType, nil); err != nil { log.Error("MailParticipants: %v", err) } } -func (m *mailNotifier) NotifyIssueChangeTitle(doer *user_model.User, issue *issues_model.Issue, oldTitle string) { - if err := issue.LoadPullRequest(); err != nil { +func (m *mailNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) { + if err := issue.LoadPullRequest(ctx); err != nil { log.Error("issue.LoadPullRequest: %v", err) return } if issue.IsPull && issues_model.HasWorkInProgressPrefix(oldTitle) && !issue.PullRequest.IsWorkInProgress() { - if err := mailer.MailParticipants(issue, doer, activities_model.ActionPullRequestReadyForReview, nil); err != nil { + if err := mailer.MailParticipants(ctx, issue, doer, activities_model.ActionPullRequestReadyForReview, nil); err != nil { log.Error("MailParticipants: %v", err) } } } -func (m *mailNotifier) NotifyNewPullRequest(pr *issues_model.PullRequest, mentions []*user_model.User) { - if err := mailer.MailParticipants(pr.Issue, pr.Issue.Poster, activities_model.ActionCreatePullRequest, mentions); err != nil { +func (m *mailNotifier) NotifyNewPullRequest(ctx context.Context, pr *issues_model.PullRequest, mentions []*user_model.User) { + if err := mailer.MailParticipants(ctx, pr.Issue, pr.Issue.Poster, activities_model.ActionCreatePullRequest, mentions); err != nil { log.Error("MailParticipants: %v", err) } } -func (m *mailNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, r *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("mailNotifier.NotifyPullRequestReview Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID)) - defer finished() - +func (m *mailNotifier) NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, r *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { var act activities_model.ActionType if comment.Type == issues_model.CommentTypeClose { act = activities_model.ActionCloseIssue @@ -115,60 +107,54 @@ func (m *mailNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, r * } } -func (m *mailNotifier) NotifyPullRequestCodeComment(pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("mailNotifier.NotifyPullRequestCodeComment Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID)) - defer finished() - +func (m *mailNotifier) NotifyPullRequestCodeComment(ctx context.Context, pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) { if err := mailer.MailMentionsComment(ctx, pr, comment, mentions); err != nil { log.Error("MailMentionsComment: %v", err) } } -func (m *mailNotifier) NotifyIssueChangeAssignee(doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { +func (m *mailNotifier) NotifyIssueChangeAssignee(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { // mail only sent to added assignees and not self-assignee if !removed && doer.ID != assignee.ID && assignee.EmailNotifications() != user_model.EmailNotificationsDisabled { ct := fmt.Sprintf("Assigned #%d.", issue.Index) - if err := mailer.SendIssueAssignedMail(issue, doer, ct, comment, []*user_model.User{assignee}); err != nil { + if err := mailer.SendIssueAssignedMail(ctx, issue, doer, ct, comment, []*user_model.User{assignee}); err != nil { log.Error("Error in SendIssueAssignedMail for issue[%d] to assignee[%d]: %v", issue.ID, assignee.ID, err) } } } -func (m *mailNotifier) NotifyPullReviewRequest(doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) { +func (m *mailNotifier) NotifyPullReviewRequest(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) { if isRequest && doer.ID != reviewer.ID && reviewer.EmailNotifications() != user_model.EmailNotificationsDisabled { ct := fmt.Sprintf("Requested to review %s.", issue.HTMLURL()) - if err := mailer.SendIssueAssignedMail(issue, doer, ct, comment, []*user_model.User{reviewer}); err != nil { + if err := mailer.SendIssueAssignedMail(ctx, issue, doer, ct, comment, []*user_model.User{reviewer}); err != nil { log.Error("Error in SendIssueAssignedMail for issue[%d] to reviewer[%d]: %v", issue.ID, reviewer.ID, err) } } } -func (m *mailNotifier) NotifyMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { - if err := pr.LoadIssue(); err != nil { - log.Error("pr.LoadIssue: %v", err) +func (m *mailNotifier) NotifyMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { + if err := pr.LoadIssue(ctx); err != nil { + log.Error("LoadIssue: %v", err) return } - if err := mailer.MailParticipants(pr.Issue, doer, activities_model.ActionMergePullRequest, nil); err != nil { + if err := mailer.MailParticipants(ctx, pr.Issue, doer, activities_model.ActionMergePullRequest, nil); err != nil { log.Error("MailParticipants: %v", err) } } -func (m *mailNotifier) NotifyAutoMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { - if err := pr.LoadIssue(); err != nil { +func (m *mailNotifier) NotifyAutoMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { + if err := pr.LoadIssue(ctx); err != nil { log.Error("pr.LoadIssue: %v", err) return } - if err := mailer.MailParticipants(pr.Issue, doer, activities_model.ActionAutoMergePullRequest, nil); err != nil { + if err := mailer.MailParticipants(ctx, pr.Issue, doer, activities_model.ActionAutoMergePullRequest, nil); err != nil { log.Error("MailParticipants: %v", err) } } -func (m *mailNotifier) NotifyPullRequestPushCommits(doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("mailNotifier.NotifyPullRequestPushCommits Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID)) - defer finished() - +func (m *mailNotifier) NotifyPullRequestPushCommits(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) { var err error - if err = comment.LoadIssue(); err != nil { + if err = comment.LoadIssue(ctx); err != nil { log.Error("comment.LoadIssue: %v", err) return } @@ -176,35 +162,29 @@ func (m *mailNotifier) NotifyPullRequestPushCommits(doer *user_model.User, pr *i log.Error("comment.Issue.LoadRepo: %v", err) return } - if err = comment.Issue.LoadPullRequest(); err != nil { + if err = comment.Issue.LoadPullRequest(ctx); err != nil { log.Error("comment.Issue.LoadPullRequest: %v", err) return } - if err = comment.Issue.PullRequest.LoadBaseRepoCtx(ctx); err != nil { + if err = comment.Issue.PullRequest.LoadBaseRepo(ctx); err != nil { log.Error("comment.Issue.PullRequest.LoadBaseRepo: %v", err) return } if err := comment.LoadPushCommits(ctx); err != nil { log.Error("comment.LoadPushCommits: %v", err) } - m.NotifyCreateIssueComment(doer, comment.Issue.Repo, comment.Issue, comment, nil) + m.NotifyCreateIssueComment(ctx, doer, comment.Issue.Repo, comment.Issue, comment, nil) } -func (m *mailNotifier) NotifyPullRevieweDismiss(doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("mailNotifier.NotifyPullRevieweDismiss Review[%d] in Issue[%d]", review.ID, review.IssueID)) - defer finished() - +func (m *mailNotifier) NotifyPullReviewDismiss(ctx context.Context, doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { if err := mailer.MailParticipantsComment(ctx, comment, activities_model.ActionPullReviewDismissed, review.Issue, nil); err != nil { log.Error("MailParticipantsComment: %v", err) } } -func (m *mailNotifier) NotifyNewRelease(rel *repo_model.Release) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("mailNotifier.NotifyNewRelease rel[%d]%s in [%d]", rel.ID, rel.Title, rel.RepoID)) - defer finished() - - if err := rel.LoadAttributes(); err != nil { - log.Error("NotifyNewRelease: %v", err) +func (m *mailNotifier) NotifyNewRelease(ctx context.Context, rel *repo_model.Release) { + if err := rel.LoadAttributes(ctx); err != nil { + log.Error("LoadAttributes: %v", err) return } @@ -215,8 +195,8 @@ func (m *mailNotifier) NotifyNewRelease(rel *repo_model.Release) { mailer.MailNewRelease(ctx, rel) } -func (m *mailNotifier) NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) { - if err := mailer.SendRepoTransferNotifyMail(doer, newOwner, repo); err != nil { - log.Error("NotifyRepoPendingTransfer: %v", err) +func (m *mailNotifier) NotifyRepoPendingTransfer(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository) { + if err := mailer.SendRepoTransferNotifyMail(ctx, doer, newOwner, repo); err != nil { + log.Error("SendRepoTransferNotifyMail: %v", err) } } diff --git a/modules/notification/mirror/mirror.go b/modules/notification/mirror/mirror.go index 646b09a4ab..426e36ee58 100644 --- a/modules/notification/mirror/mirror.go +++ b/modules/notification/mirror/mirror.go @@ -1,10 +1,11 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package mirror import ( + "context" + repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/log" @@ -24,16 +25,16 @@ func NewNotifier() base.Notifier { return &mirrorNotifier{} } -func (m *mirrorNotifier) NotifyPushCommits(_ *user_model.User, repo *repo_model.Repository, _ *repository.PushUpdateOptions, _ *repository.PushCommits) { - syncPushMirrorWithSyncOnCommit(repo.ID) +func (m *mirrorNotifier) NotifyPushCommits(ctx context.Context, _ *user_model.User, repo *repo_model.Repository, _ *repository.PushUpdateOptions, _ *repository.PushCommits) { + syncPushMirrorWithSyncOnCommit(ctx, repo.ID) } -func (m *mirrorNotifier) NotifySyncPushCommits(_ *user_model.User, repo *repo_model.Repository, _ *repository.PushUpdateOptions, _ *repository.PushCommits) { - syncPushMirrorWithSyncOnCommit(repo.ID) +func (m *mirrorNotifier) NotifySyncPushCommits(ctx context.Context, _ *user_model.User, repo *repo_model.Repository, _ *repository.PushUpdateOptions, _ *repository.PushCommits) { + syncPushMirrorWithSyncOnCommit(ctx, repo.ID) } -func syncPushMirrorWithSyncOnCommit(repoID int64) { - pushMirrors, err := repo_model.GetPushMirrorsSyncedOnCommit(repoID) +func syncPushMirrorWithSyncOnCommit(ctx context.Context, repoID int64) { + pushMirrors, err := repo_model.GetPushMirrorsSyncedOnCommit(ctx, repoID) if err != nil { log.Error("repo_model.GetPushMirrorsSyncedOnCommit failed: %v", err) return diff --git a/modules/notification/notification.go b/modules/notification/notification.go index 7bdc0a04c4..c3e09bb8a9 100644 --- a/modules/notification/notification.go +++ b/modules/notification/notification.go @@ -1,10 +1,11 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package notification import ( + "context" + issues_model "code.gitea.io/gitea/models/issues" packages_model "code.gitea.io/gitea/models/packages" repo_model "code.gitea.io/gitea/models/repo" @@ -41,313 +42,313 @@ func NewContext() { } // NotifyNewWikiPage notifies creating new wiki pages to notifiers -func NotifyNewWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) { +func NotifyNewWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) { for _, notifier := range notifiers { - notifier.NotifyNewWikiPage(doer, repo, page, comment) + notifier.NotifyNewWikiPage(ctx, doer, repo, page, comment) } } // NotifyEditWikiPage notifies editing or renaming wiki pages to notifiers -func NotifyEditWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) { +func NotifyEditWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) { for _, notifier := range notifiers { - notifier.NotifyEditWikiPage(doer, repo, page, comment) + notifier.NotifyEditWikiPage(ctx, doer, repo, page, comment) } } // NotifyDeleteWikiPage notifies deleting wiki pages to notifiers -func NotifyDeleteWikiPage(doer *user_model.User, repo *repo_model.Repository, page string) { +func NotifyDeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page string) { for _, notifier := range notifiers { - notifier.NotifyDeleteWikiPage(doer, repo, page) + notifier.NotifyDeleteWikiPage(ctx, doer, repo, page) } } // NotifyCreateIssueComment notifies issue comment related message to notifiers -func NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, +func NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User, ) { for _, notifier := range notifiers { - notifier.NotifyCreateIssueComment(doer, repo, issue, comment, mentions) + notifier.NotifyCreateIssueComment(ctx, doer, repo, issue, comment, mentions) } } // NotifyNewIssue notifies new issue to notifiers -func NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) { +func NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) { for _, notifier := range notifiers { - notifier.NotifyNewIssue(issue, mentions) + notifier.NotifyNewIssue(ctx, issue, mentions) } } // NotifyIssueChangeStatus notifies close or reopen issue to notifiers -func NotifyIssueChangeStatus(doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, closeOrReopen bool) { +func NotifyIssueChangeStatus(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, closeOrReopen bool) { for _, notifier := range notifiers { - notifier.NotifyIssueChangeStatus(doer, issue, actionComment, closeOrReopen) + notifier.NotifyIssueChangeStatus(ctx, doer, issue, actionComment, closeOrReopen) } } // NotifyDeleteIssue notify when some issue deleted -func NotifyDeleteIssue(doer *user_model.User, issue *issues_model.Issue) { +func NotifyDeleteIssue(ctx context.Context, doer *user_model.User, issue *issues_model.Issue) { for _, notifier := range notifiers { - notifier.NotifyDeleteIssue(doer, issue) + notifier.NotifyDeleteIssue(ctx, doer, issue) } } // NotifyMergePullRequest notifies merge pull request to notifiers -func NotifyMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { +func NotifyMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { for _, notifier := range notifiers { - notifier.NotifyMergePullRequest(pr, doer) + notifier.NotifyMergePullRequest(ctx, doer, pr) } } // NotifyAutoMergePullRequest notifies merge pull request to notifiers -func NotifyAutoMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { +func NotifyAutoMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { for _, notifier := range notifiers { - notifier.NotifyAutoMergePullRequest(pr, doer) + notifier.NotifyAutoMergePullRequest(ctx, doer, pr) } } // NotifyNewPullRequest notifies new pull request to notifiers -func NotifyNewPullRequest(pr *issues_model.PullRequest, mentions []*user_model.User) { +func NotifyNewPullRequest(ctx context.Context, pr *issues_model.PullRequest, mentions []*user_model.User) { for _, notifier := range notifiers { - notifier.NotifyNewPullRequest(pr, mentions) + notifier.NotifyNewPullRequest(ctx, pr, mentions) } } // NotifyPullRequestSynchronized notifies Synchronized pull request -func NotifyPullRequestSynchronized(doer *user_model.User, pr *issues_model.PullRequest) { +func NotifyPullRequestSynchronized(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { for _, notifier := range notifiers { - notifier.NotifyPullRequestSynchronized(doer, pr) + notifier.NotifyPullRequestSynchronized(ctx, doer, pr) } } // NotifyPullRequestReview notifies new pull request review -func NotifyPullRequestReview(pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { +func NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { for _, notifier := range notifiers { - notifier.NotifyPullRequestReview(pr, review, comment, mentions) + notifier.NotifyPullRequestReview(ctx, pr, review, comment, mentions) } } // NotifyPullRequestCodeComment notifies new pull request code comment -func NotifyPullRequestCodeComment(pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) { +func NotifyPullRequestCodeComment(ctx context.Context, pr *issues_model.PullRequest, comment *issues_model.Comment, mentions []*user_model.User) { for _, notifier := range notifiers { - notifier.NotifyPullRequestCodeComment(pr, comment, mentions) + notifier.NotifyPullRequestCodeComment(ctx, pr, comment, mentions) } } // NotifyPullRequestChangeTargetBranch notifies when a pull request's target branch was changed -func NotifyPullRequestChangeTargetBranch(doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) { +func NotifyPullRequestChangeTargetBranch(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) { for _, notifier := range notifiers { - notifier.NotifyPullRequestChangeTargetBranch(doer, pr, oldBranch) + notifier.NotifyPullRequestChangeTargetBranch(ctx, doer, pr, oldBranch) } } // NotifyPullRequestPushCommits notifies when push commits to pull request's head branch -func NotifyPullRequestPushCommits(doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) { +func NotifyPullRequestPushCommits(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) { for _, notifier := range notifiers { - notifier.NotifyPullRequestPushCommits(doer, pr, comment) + notifier.NotifyPullRequestPushCommits(ctx, doer, pr, comment) } } -// NotifyPullRevieweDismiss notifies when a review was dismissed by repo admin -func NotifyPullRevieweDismiss(doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { +// NotifyPullReviewDismiss notifies when a review was dismissed by repo admin +func NotifyPullReviewDismiss(ctx context.Context, doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { for _, notifier := range notifiers { - notifier.NotifyPullRevieweDismiss(doer, review, comment) + notifier.NotifyPullReviewDismiss(ctx, doer, review, comment) } } // NotifyUpdateComment notifies update comment to notifiers -func NotifyUpdateComment(doer *user_model.User, c *issues_model.Comment, oldContent string) { +func NotifyUpdateComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment, oldContent string) { for _, notifier := range notifiers { - notifier.NotifyUpdateComment(doer, c, oldContent) + notifier.NotifyUpdateComment(ctx, doer, c, oldContent) } } // NotifyDeleteComment notifies delete comment to notifiers -func NotifyDeleteComment(doer *user_model.User, c *issues_model.Comment) { +func NotifyDeleteComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment) { for _, notifier := range notifiers { - notifier.NotifyDeleteComment(doer, c) + notifier.NotifyDeleteComment(ctx, doer, c) } } // NotifyNewRelease notifies new release to notifiers -func NotifyNewRelease(rel *repo_model.Release) { +func NotifyNewRelease(ctx context.Context, rel *repo_model.Release) { for _, notifier := range notifiers { - notifier.NotifyNewRelease(rel) + notifier.NotifyNewRelease(ctx, rel) } } // NotifyUpdateRelease notifies update release to notifiers -func NotifyUpdateRelease(doer *user_model.User, rel *repo_model.Release) { +func NotifyUpdateRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release) { for _, notifier := range notifiers { - notifier.NotifyUpdateRelease(doer, rel) + notifier.NotifyUpdateRelease(ctx, doer, rel) } } // NotifyDeleteRelease notifies delete release to notifiers -func NotifyDeleteRelease(doer *user_model.User, rel *repo_model.Release) { +func NotifyDeleteRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release) { for _, notifier := range notifiers { - notifier.NotifyDeleteRelease(doer, rel) + notifier.NotifyDeleteRelease(ctx, doer, rel) } } // NotifyIssueChangeMilestone notifies change milestone to notifiers -func NotifyIssueChangeMilestone(doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) { +func NotifyIssueChangeMilestone(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) { for _, notifier := range notifiers { - notifier.NotifyIssueChangeMilestone(doer, issue, oldMilestoneID) + notifier.NotifyIssueChangeMilestone(ctx, doer, issue, oldMilestoneID) } } // NotifyIssueChangeContent notifies change content to notifiers -func NotifyIssueChangeContent(doer *user_model.User, issue *issues_model.Issue, oldContent string) { +func NotifyIssueChangeContent(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldContent string) { for _, notifier := range notifiers { - notifier.NotifyIssueChangeContent(doer, issue, oldContent) + notifier.NotifyIssueChangeContent(ctx, doer, issue, oldContent) } } // NotifyIssueChangeAssignee notifies change content to notifiers -func NotifyIssueChangeAssignee(doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { +func NotifyIssueChangeAssignee(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { for _, notifier := range notifiers { - notifier.NotifyIssueChangeAssignee(doer, issue, assignee, removed, comment) + notifier.NotifyIssueChangeAssignee(ctx, doer, issue, assignee, removed, comment) } } // NotifyPullReviewRequest notifies Request Review change -func NotifyPullReviewRequest(doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) { +func NotifyPullReviewRequest(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) { for _, notifier := range notifiers { - notifier.NotifyPullReviewRequest(doer, issue, reviewer, isRequest, comment) + notifier.NotifyPullReviewRequest(ctx, doer, issue, reviewer, isRequest, comment) } } // NotifyIssueClearLabels notifies clear labels to notifiers -func NotifyIssueClearLabels(doer *user_model.User, issue *issues_model.Issue) { +func NotifyIssueClearLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue) { for _, notifier := range notifiers { - notifier.NotifyIssueClearLabels(doer, issue) + notifier.NotifyIssueClearLabels(ctx, doer, issue) } } // NotifyIssueChangeTitle notifies change title to notifiers -func NotifyIssueChangeTitle(doer *user_model.User, issue *issues_model.Issue, oldTitle string) { +func NotifyIssueChangeTitle(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) { for _, notifier := range notifiers { - notifier.NotifyIssueChangeTitle(doer, issue, oldTitle) + notifier.NotifyIssueChangeTitle(ctx, doer, issue, oldTitle) } } // NotifyIssueChangeRef notifies change reference to notifiers -func NotifyIssueChangeRef(doer *user_model.User, issue *issues_model.Issue, oldRef string) { +func NotifyIssueChangeRef(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldRef string) { for _, notifier := range notifiers { - notifier.NotifyIssueChangeRef(doer, issue, oldRef) + notifier.NotifyIssueChangeRef(ctx, doer, issue, oldRef) } } // NotifyIssueChangeLabels notifies change labels to notifiers -func NotifyIssueChangeLabels(doer *user_model.User, issue *issues_model.Issue, +func NotifyIssueChangeLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, addedLabels, removedLabels []*issues_model.Label, ) { for _, notifier := range notifiers { - notifier.NotifyIssueChangeLabels(doer, issue, addedLabels, removedLabels) + notifier.NotifyIssueChangeLabels(ctx, doer, issue, addedLabels, removedLabels) } } // NotifyCreateRepository notifies create repository to notifiers -func NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) { +func NotifyCreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) { for _, notifier := range notifiers { - notifier.NotifyCreateRepository(doer, u, repo) + notifier.NotifyCreateRepository(ctx, doer, u, repo) } } // NotifyMigrateRepository notifies create repository to notifiers -func NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) { +func NotifyMigrateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) { for _, notifier := range notifiers { - notifier.NotifyMigrateRepository(doer, u, repo) + notifier.NotifyMigrateRepository(ctx, doer, u, repo) } } // NotifyTransferRepository notifies create repository to notifiers -func NotifyTransferRepository(doer *user_model.User, repo *repo_model.Repository, newOwnerName string) { +func NotifyTransferRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, newOwnerName string) { for _, notifier := range notifiers { - notifier.NotifyTransferRepository(doer, repo, newOwnerName) + notifier.NotifyTransferRepository(ctx, doer, repo, newOwnerName) } } // NotifyDeleteRepository notifies delete repository to notifiers -func NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) { +func NotifyDeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository) { for _, notifier := range notifiers { - notifier.NotifyDeleteRepository(doer, repo) + notifier.NotifyDeleteRepository(ctx, doer, repo) } } // NotifyForkRepository notifies fork repository to notifiers -func NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) { +func NotifyForkRepository(ctx context.Context, doer *user_model.User, oldRepo, repo *repo_model.Repository) { for _, notifier := range notifiers { - notifier.NotifyForkRepository(doer, oldRepo, repo) + notifier.NotifyForkRepository(ctx, doer, oldRepo, repo) } } // NotifyRenameRepository notifies repository renamed -func NotifyRenameRepository(doer *user_model.User, repo *repo_model.Repository, oldName string) { +func NotifyRenameRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, oldName string) { for _, notifier := range notifiers { - notifier.NotifyRenameRepository(doer, repo, oldName) + notifier.NotifyRenameRepository(ctx, doer, repo, oldName) } } // NotifyPushCommits notifies commits pushed to notifiers -func NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func NotifyPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { for _, notifier := range notifiers { - notifier.NotifyPushCommits(pusher, repo, opts, commits) + notifier.NotifyPushCommits(ctx, pusher, repo, opts, commits) } } // NotifyCreateRef notifies branch or tag creation to notifiers -func NotifyCreateRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { +func NotifyCreateRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { for _, notifier := range notifiers { - notifier.NotifyCreateRef(pusher, repo, refType, refFullName, refID) + notifier.NotifyCreateRef(ctx, pusher, repo, refType, refFullName, refID) } } // NotifyDeleteRef notifies branch or tag deletion to notifiers -func NotifyDeleteRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { +func NotifyDeleteRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { for _, notifier := range notifiers { - notifier.NotifyDeleteRef(pusher, repo, refType, refFullName) + notifier.NotifyDeleteRef(ctx, pusher, repo, refType, refFullName) } } // NotifySyncPushCommits notifies commits pushed to notifiers -func NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { +func NotifySyncPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { for _, notifier := range notifiers { - notifier.NotifySyncPushCommits(pusher, repo, opts, commits) + notifier.NotifySyncPushCommits(ctx, pusher, repo, opts, commits) } } // NotifySyncCreateRef notifies branch or tag creation to notifiers -func NotifySyncCreateRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { +func NotifySyncCreateRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { for _, notifier := range notifiers { - notifier.NotifySyncCreateRef(pusher, repo, refType, refFullName, refID) + notifier.NotifySyncCreateRef(ctx, pusher, repo, refType, refFullName, refID) } } // NotifySyncDeleteRef notifies branch or tag deletion to notifiers -func NotifySyncDeleteRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { +func NotifySyncDeleteRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { for _, notifier := range notifiers { - notifier.NotifySyncDeleteRef(pusher, repo, refType, refFullName) + notifier.NotifySyncDeleteRef(ctx, pusher, repo, refType, refFullName) } } // NotifyRepoPendingTransfer notifies creation of pending transfer to notifiers -func NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) { +func NotifyRepoPendingTransfer(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository) { for _, notifier := range notifiers { - notifier.NotifyRepoPendingTransfer(doer, newOwner, repo) + notifier.NotifyRepoPendingTransfer(ctx, doer, newOwner, repo) } } // NotifyPackageCreate notifies creation of a package to notifiers -func NotifyPackageCreate(doer *user_model.User, pd *packages_model.PackageDescriptor) { +func NotifyPackageCreate(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) { for _, notifier := range notifiers { - notifier.NotifyPackageCreate(doer, pd) + notifier.NotifyPackageCreate(ctx, doer, pd) } } // NotifyPackageDelete notifies deletion of a package to notifiers -func NotifyPackageDelete(doer *user_model.User, pd *packages_model.PackageDescriptor) { +func NotifyPackageDelete(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) { for _, notifier := range notifiers { - notifier.NotifyPackageDelete(doer, pd) + notifier.NotifyPackageDelete(ctx, doer, pd) } } diff --git a/modules/notification/ui/ui.go b/modules/notification/ui/ui.go index 0e2b3e67c7..63a3ffd199 100644 --- a/modules/notification/ui/ui.go +++ b/modules/notification/ui/ui.go @@ -1,10 +1,11 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package ui import ( + "context" + activities_model "code.gitea.io/gitea/models/activities" "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" @@ -54,7 +55,7 @@ func (ns *notificationService) Run() { graceful.GetManager().RunWithShutdownFns(ns.issueQueue.Run) } -func (ns *notificationService) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, +func (ns *notificationService) NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User, ) { opts := issueNotificationOpts{ @@ -78,7 +79,7 @@ func (ns *notificationService) NotifyCreateIssueComment(doer *user_model.User, r } } -func (ns *notificationService) NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) { +func (ns *notificationService) NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) { _ = ns.issueQueue.Push(issueNotificationOpts{ IssueID: issue.ID, NotificationAuthorID: issue.Poster.ID, @@ -92,15 +93,15 @@ func (ns *notificationService) NotifyNewIssue(issue *issues_model.Issue, mention } } -func (ns *notificationService) NotifyIssueChangeStatus(doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) { +func (ns *notificationService) NotifyIssueChangeStatus(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) { _ = ns.issueQueue.Push(issueNotificationOpts{ IssueID: issue.ID, NotificationAuthorID: doer.ID, }) } -func (ns *notificationService) NotifyIssueChangeTitle(doer *user_model.User, issue *issues_model.Issue, oldTitle string) { - if err := issue.LoadPullRequest(); err != nil { +func (ns *notificationService) NotifyIssueChangeTitle(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) { + if err := issue.LoadPullRequest(ctx); err != nil { log.Error("issue.LoadPullRequest: %v", err) return } @@ -112,24 +113,24 @@ func (ns *notificationService) NotifyIssueChangeTitle(doer *user_model.User, iss } } -func (ns *notificationService) NotifyMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { +func (ns *notificationService) NotifyMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { _ = ns.issueQueue.Push(issueNotificationOpts{ IssueID: pr.Issue.ID, NotificationAuthorID: doer.ID, }) } -func (ns *notificationService) NotifyAutoMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { - ns.NotifyMergePullRequest(pr, doer) +func (ns *notificationService) NotifyAutoMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { + ns.NotifyMergePullRequest(ctx, doer, pr) } -func (ns *notificationService) NotifyNewPullRequest(pr *issues_model.PullRequest, mentions []*user_model.User) { - if err := pr.LoadIssue(); err != nil { +func (ns *notificationService) NotifyNewPullRequest(ctx context.Context, pr *issues_model.PullRequest, mentions []*user_model.User) { + if err := pr.LoadIssue(ctx); err != nil { log.Error("Unable to load issue: %d for pr: %d: Error: %v", pr.IssueID, pr.ID, err) return } toNotify := make(container.Set[int64], 32) - repoWatchers, err := repo_model.GetRepoWatchersIDs(db.DefaultContext, pr.Issue.RepoID) + repoWatchers, err := repo_model.GetRepoWatchersIDs(ctx, pr.Issue.RepoID) if err != nil { log.Error("GetRepoWatchersIDs: %v", err) return @@ -137,7 +138,7 @@ func (ns *notificationService) NotifyNewPullRequest(pr *issues_model.PullRequest for _, id := range repoWatchers { toNotify.Add(id) } - issueParticipants, err := issues_model.GetParticipantsIDsByIssueID(pr.IssueID) + issueParticipants, err := issues_model.GetParticipantsIDsByIssueID(ctx, pr.IssueID) if err != nil { log.Error("GetParticipantsIDsByIssueID: %v", err) return @@ -158,7 +159,7 @@ func (ns *notificationService) NotifyNewPullRequest(pr *issues_model.PullRequest } } -func (ns *notificationService) NotifyPullRequestReview(pr *issues_model.PullRequest, r *issues_model.Review, c *issues_model.Comment, mentions []*user_model.User) { +func (ns *notificationService) NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, r *issues_model.Review, c *issues_model.Comment, mentions []*user_model.User) { opts := issueNotificationOpts{ IssueID: pr.Issue.ID, NotificationAuthorID: r.Reviewer.ID, @@ -180,7 +181,7 @@ func (ns *notificationService) NotifyPullRequestReview(pr *issues_model.PullRequ } } -func (ns *notificationService) NotifyPullRequestCodeComment(pr *issues_model.PullRequest, c *issues_model.Comment, mentions []*user_model.User) { +func (ns *notificationService) NotifyPullRequestCodeComment(ctx context.Context, pr *issues_model.PullRequest, c *issues_model.Comment, mentions []*user_model.User) { for _, mention := range mentions { _ = ns.issueQueue.Push(issueNotificationOpts{ IssueID: pr.Issue.ID, @@ -191,7 +192,7 @@ func (ns *notificationService) NotifyPullRequestCodeComment(pr *issues_model.Pul } } -func (ns *notificationService) NotifyPullRequestPushCommits(doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) { +func (ns *notificationService) NotifyPullRequestPushCommits(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, comment *issues_model.Comment) { opts := issueNotificationOpts{ IssueID: pr.IssueID, NotificationAuthorID: doer.ID, @@ -200,7 +201,7 @@ func (ns *notificationService) NotifyPullRequestPushCommits(doer *user_model.Use _ = ns.issueQueue.Push(opts) } -func (ns *notificationService) NotifyPullRevieweDismiss(doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { +func (ns *notificationService) NotifyPullReviewDismiss(ctx context.Context, doer *user_model.User, review *issues_model.Review, comment *issues_model.Comment) { opts := issueNotificationOpts{ IssueID: review.IssueID, NotificationAuthorID: doer.ID, @@ -209,7 +210,7 @@ func (ns *notificationService) NotifyPullRevieweDismiss(doer *user_model.User, r _ = ns.issueQueue.Push(opts) } -func (ns *notificationService) NotifyIssueChangeAssignee(doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { +func (ns *notificationService) NotifyIssueChangeAssignee(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { if !removed && doer.ID != assignee.ID { opts := issueNotificationOpts{ IssueID: issue.ID, @@ -225,7 +226,7 @@ func (ns *notificationService) NotifyIssueChangeAssignee(doer *user_model.User, } } -func (ns *notificationService) NotifyPullReviewRequest(doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) { +func (ns *notificationService) NotifyPullReviewRequest(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, reviewer *user_model.User, isRequest bool, comment *issues_model.Comment) { if isRequest { opts := issueNotificationOpts{ IssueID: issue.ID, @@ -241,8 +242,11 @@ func (ns *notificationService) NotifyPullReviewRequest(doer *user_model.User, is } } -func (ns *notificationService) NotifyRepoPendingTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository) { - if err := activities_model.CreateRepoTransferNotification(doer, newOwner, repo); err != nil { - log.Error("NotifyRepoPendingTransfer: %v", err) +func (ns *notificationService) NotifyRepoPendingTransfer(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository) { + err := db.AutoTx(ctx, func(ctx context.Context) error { + return activities_model.CreateRepoTransferNotification(ctx, doer, newOwner, repo) + }) + if err != nil { + log.Error("CreateRepoTransferNotification: %v", err) } } diff --git a/modules/notification/webhook/webhook.go b/modules/notification/webhook/webhook.go index c591e1e34d..cf056f54c1 100644 --- a/modules/notification/webhook/webhook.go +++ b/modules/notification/webhook/webhook.go @@ -1,13 +1,11 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package webhook import ( - "fmt" + "context" - "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" packages_model "code.gitea.io/gitea/models/packages" "code.gitea.io/gitea/models/perm" @@ -18,10 +16,8 @@ import ( "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/convert" "code.gitea.io/gitea/modules/git" - "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/notification/base" - "code.gitea.io/gitea/modules/process" "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" @@ -39,12 +35,9 @@ func NewNotifier() base.Notifier { return &webhookNotifier{} } -func (m *webhookNotifier) NotifyIssueClearLabels(doer *user_model.User, issue *issues_model.Issue) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueClearLabels User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID)) - defer finished() - - if err := issue.LoadPoster(); err != nil { - log.Error("loadPoster: %v", err) +func (m *webhookNotifier) NotifyIssueClearLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue) { + if err := issue.LoadPoster(ctx); err != nil { + log.Error("LoadPoster: %v", err) return } @@ -53,10 +46,10 @@ func (m *webhookNotifier) NotifyIssueClearLabels(doer *user_model.User, issue *i return } - mode, _ := access_model.AccessLevel(issue.Poster, issue.Repo) + mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo) var err error if issue.IsPull { - if err = issue.LoadPullRequest(); err != nil { + if err = issue.LoadPullRequest(ctx); err != nil { log.Error("LoadPullRequest: %v", err) return } @@ -65,15 +58,15 @@ func (m *webhookNotifier) NotifyIssueClearLabels(doer *user_model.User, issue *i Action: api.HookIssueLabelCleared, Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } else { err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueLabel, &api.IssuePayload{ Action: api.HookIssueLabelCleared, Index: issue.Index, - Issue: convert.ToAPIIssue(issue), - Repository: convert.ToRepo(issue.Repo, mode), + Issue: convert.ToAPIIssue(ctx, issue), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } @@ -82,26 +75,26 @@ func (m *webhookNotifier) NotifyIssueClearLabels(doer *user_model.User, issue *i } } -func (m *webhookNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, repo *repo_model.Repository) { - oldMode, _ := access_model.AccessLevel(doer, oldRepo) - mode, _ := access_model.AccessLevel(doer, repo) +func (m *webhookNotifier) NotifyForkRepository(ctx context.Context, doer *user_model.User, oldRepo, repo *repo_model.Repository) { + oldMode, _ := access_model.AccessLevel(ctx, doer, oldRepo) + mode, _ := access_model.AccessLevel(ctx, doer, repo) // forked webhook - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: oldRepo}, webhook.HookEventFork, &api.ForkPayload{ - Forkee: convert.ToRepo(oldRepo, oldMode), - Repo: convert.ToRepo(repo, mode), + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: oldRepo}, webhook.HookEventFork, &api.ForkPayload{ + Forkee: convert.ToRepo(ctx, oldRepo, oldMode), + Repo: convert.ToRepo(ctx, repo, mode), Sender: convert.ToUser(doer, nil), }); err != nil { log.Error("PrepareWebhooks [repo_id: %d]: %v", oldRepo.ID, err) } - u := repo.MustOwner() + u := repo.MustOwner(ctx) // Add to hook queue for created repo after session commit. if u.IsOrganization() { - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, - Repository: convert.ToRepo(repo, perm.AccessModeOwner), + Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Organization: convert.ToUser(u, nil), Sender: convert.ToUser(doer, nil), }); err != nil { @@ -110,11 +103,11 @@ func (m *webhookNotifier) NotifyForkRepository(doer *user_model.User, oldRepo, r } } -func (m *webhookNotifier) NotifyCreateRepository(doer, u *user_model.User, repo *repo_model.Repository) { +func (m *webhookNotifier) NotifyCreateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) { // Add to hook queue for created repo after session commit. - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, - Repository: convert.ToRepo(repo, perm.AccessModeOwner), + Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Organization: convert.ToUser(u, nil), Sender: convert.ToUser(doer, nil), }); err != nil { @@ -122,24 +115,22 @@ func (m *webhookNotifier) NotifyCreateRepository(doer, u *user_model.User, repo } } -func (m *webhookNotifier) NotifyDeleteRepository(doer *user_model.User, repo *repo_model.Repository) { - u := repo.MustOwner() - - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ +func (m *webhookNotifier) NotifyDeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_model.Repository) { + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoDeleted, - Repository: convert.ToRepo(repo, perm.AccessModeOwner), - Organization: convert.ToUser(u, nil), + Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), + Organization: convert.ToUser(repo.MustOwner(ctx), nil), Sender: convert.ToUser(doer, nil), }); err != nil { log.Error("PrepareWebhooks [repo_id: %d]: %v", repo.ID, err) } } -func (m *webhookNotifier) NotifyMigrateRepository(doer, u *user_model.User, repo *repo_model.Repository) { +func (m *webhookNotifier) NotifyMigrateRepository(ctx context.Context, doer, u *user_model.User, repo *repo_model.Repository) { // Add to hook queue for created repo after session commit. - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventRepository, &api.RepositoryPayload{ Action: api.HookRepoCreated, - Repository: convert.ToRepo(repo, perm.AccessModeOwner), + Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Organization: convert.ToUser(u, nil), Sender: convert.ToUser(doer, nil), }); err != nil { @@ -147,14 +138,11 @@ func (m *webhookNotifier) NotifyMigrateRepository(doer, u *user_model.User, repo } } -func (m *webhookNotifier) NotifyIssueChangeAssignee(doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeAssignee User: %s[%d] Issue[%d] #%d in [%d] Assignee %s[%d] removed: %t", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID, assignee.Name, assignee.ID, removed)) - defer finished() - +func (m *webhookNotifier) NotifyIssueChangeAssignee(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, assignee *user_model.User, removed bool, comment *issues_model.Comment) { if issue.IsPull { - mode, _ := access_model.AccessLevelUnit(doer, issue.Repo, unit.TypePullRequests) + mode, _ := access_model.AccessLevelUnit(ctx, doer, issue.Repo, unit.TypePullRequests) - if err := issue.LoadPullRequest(); err != nil { + if err := issue.LoadPullRequest(ctx); err != nil { log.Error("LoadPullRequest failed: %v", err) return } @@ -162,7 +150,7 @@ func (m *webhookNotifier) NotifyIssueChangeAssignee(doer *user_model.User, issue apiPullRequest := &api.PullRequestPayload{ Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), } if removed { @@ -176,11 +164,11 @@ func (m *webhookNotifier) NotifyIssueChangeAssignee(doer *user_model.User, issue return } } else { - mode, _ := access_model.AccessLevelUnit(doer, issue.Repo, unit.TypeIssues) + mode, _ := access_model.AccessLevelUnit(ctx, doer, issue.Repo, unit.TypeIssues) apiIssue := &api.IssuePayload{ Index: issue.Index, - Issue: convert.ToAPIIssue(issue), - Repository: convert.ToRepo(issue.Repo, mode), + Issue: convert.ToAPIIssue(ctx, issue), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), } if removed { @@ -196,14 +184,11 @@ func (m *webhookNotifier) NotifyIssueChangeAssignee(doer *user_model.User, issue } } -func (m *webhookNotifier) NotifyIssueChangeTitle(doer *user_model.User, issue *issues_model.Issue, oldTitle string) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeTitle User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID)) - defer finished() - - mode, _ := access_model.AccessLevel(issue.Poster, issue.Repo) +func (m *webhookNotifier) NotifyIssueChangeTitle(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldTitle string) { + mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo) var err error if issue.IsPull { - if err = issue.LoadPullRequest(); err != nil { + if err = issue.LoadPullRequest(ctx); err != nil { log.Error("LoadPullRequest failed: %v", err) return } @@ -217,7 +202,7 @@ func (m *webhookNotifier) NotifyIssueChangeTitle(doer *user_model.User, issue *i }, }, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } else { @@ -229,8 +214,8 @@ func (m *webhookNotifier) NotifyIssueChangeTitle(doer *user_model.User, issue *i From: oldTitle, }, }, - Issue: convert.ToAPIIssue(issue), - Repository: convert.ToRepo(issue.Repo, mode), + Issue: convert.ToAPIIssue(ctx, issue), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } @@ -240,14 +225,11 @@ func (m *webhookNotifier) NotifyIssueChangeTitle(doer *user_model.User, issue *i } } -func (m *webhookNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeStatus User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID)) - defer finished() - - mode, _ := access_model.AccessLevel(issue.Poster, issue.Repo) +func (m *webhookNotifier) NotifyIssueChangeStatus(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, actionComment *issues_model.Comment, isClosed bool) { + mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo) var err error if issue.IsPull { - if err = issue.LoadPullRequest(); err != nil { + if err = issue.LoadPullRequest(ctx); err != nil { log.Error("LoadPullRequest: %v", err) return } @@ -255,7 +237,7 @@ func (m *webhookNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue * apiPullRequest := &api.PullRequestPayload{ Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), } if isClosed { @@ -267,8 +249,8 @@ func (m *webhookNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue * } else { apiIssue := &api.IssuePayload{ Index: issue.Index, - Issue: convert.ToAPIIssue(issue), - Repository: convert.ToRepo(issue.Repo, mode), + Issue: convert.ToAPIIssue(ctx, issue), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), } if isClosed { @@ -283,33 +265,30 @@ func (m *webhookNotifier) NotifyIssueChangeStatus(doer *user_model.User, issue * } } -func (m *webhookNotifier) NotifyNewIssue(issue *issues_model.Issue, mentions []*user_model.User) { - if err := issue.LoadRepo(db.DefaultContext); err != nil { +func (m *webhookNotifier) NotifyNewIssue(ctx context.Context, issue *issues_model.Issue, mentions []*user_model.User) { + if err := issue.LoadRepo(ctx); err != nil { log.Error("issue.LoadRepo: %v", err) return } - if err := issue.LoadPoster(); err != nil { + if err := issue.LoadPoster(ctx); err != nil { log.Error("issue.LoadPoster: %v", err) return } - mode, _ := access_model.AccessLevel(issue.Poster, issue.Repo) - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssues, &api.IssuePayload{ + mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo) + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssues, &api.IssuePayload{ Action: api.HookIssueOpened, Index: issue.Index, - Issue: convert.ToAPIIssue(issue), - Repository: convert.ToRepo(issue.Repo, mode), + Issue: convert.ToAPIIssue(ctx, issue), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(issue.Poster, nil), }); err != nil { log.Error("PrepareWebhooks: %v", err) } } -func (m *webhookNotifier) NotifyNewPullRequest(pull *issues_model.PullRequest, mentions []*user_model.User) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyNewPullRequest Pull[%d] #%d in [%d]", pull.ID, pull.Index, pull.BaseRepoID)) - defer finished() - - if err := pull.LoadIssue(); err != nil { +func (m *webhookNotifier) NotifyNewPullRequest(ctx context.Context, pull *issues_model.PullRequest, mentions []*user_model.User) { + if err := pull.LoadIssue(ctx); err != nil { log.Error("pull.LoadIssue: %v", err) return } @@ -317,28 +296,30 @@ func (m *webhookNotifier) NotifyNewPullRequest(pull *issues_model.PullRequest, m log.Error("pull.Issue.LoadRepo: %v", err) return } - if err := pull.Issue.LoadPoster(); err != nil { + if err := pull.Issue.LoadPoster(ctx); err != nil { log.Error("pull.Issue.LoadPoster: %v", err) return } - mode, _ := access_model.AccessLevel(pull.Issue.Poster, pull.Issue.Repo) + mode, _ := access_model.AccessLevel(ctx, pull.Issue.Poster, pull.Issue.Repo) if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: pull.Issue.Repo}, webhook.HookEventPullRequest, &api.PullRequestPayload{ Action: api.HookIssueOpened, Index: pull.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pull, nil), - Repository: convert.ToRepo(pull.Issue.Repo, mode), + Repository: convert.ToRepo(ctx, pull.Issue.Repo, mode), Sender: convert.ToUser(pull.Issue.Poster, nil), }); err != nil { log.Error("PrepareWebhooks: %v", err) } } -func (m *webhookNotifier) NotifyIssueChangeContent(doer *user_model.User, issue *issues_model.Issue, oldContent string) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeContent User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID)) - defer finished() +func (m *webhookNotifier) NotifyIssueChangeContent(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldContent string) { + if err := issue.LoadRepo(ctx); err != nil { + log.Error("LoadRepo: %v", err) + return + } - mode, _ := access_model.AccessLevel(issue.Poster, issue.Repo) + mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo) var err error if issue.IsPull { issue.PullRequest.Issue = issue @@ -351,7 +332,7 @@ func (m *webhookNotifier) NotifyIssueChangeContent(doer *user_model.User, issue }, }, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } else { @@ -363,8 +344,8 @@ func (m *webhookNotifier) NotifyIssueChangeContent(doer *user_model.User, issue From: oldContent, }, }, - Issue: convert.ToAPIIssue(issue), - Repository: convert.ToRepo(issue.Repo, mode), + Issue: convert.ToAPIIssue(ctx, issue), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } @@ -373,17 +354,17 @@ func (m *webhookNotifier) NotifyIssueChangeContent(doer *user_model.User, issue } } -func (m *webhookNotifier) NotifyUpdateComment(doer *user_model.User, c *issues_model.Comment, oldContent string) { - if err := c.LoadPoster(); err != nil { +func (m *webhookNotifier) NotifyUpdateComment(ctx context.Context, doer *user_model.User, c *issues_model.Comment, oldContent string) { + if err := c.LoadPoster(ctx); err != nil { log.Error("LoadPoster: %v", err) return } - if err := c.LoadIssue(); err != nil { + if err := c.LoadIssue(ctx); err != nil { log.Error("LoadIssue: %v", err) return } - if err := c.Issue.LoadAttributes(db.DefaultContext); err != nil { + if err := c.Issue.LoadAttributes(ctx); err != nil { log.Error("LoadAttributes: %v", err) return } @@ -395,17 +376,17 @@ func (m *webhookNotifier) NotifyUpdateComment(doer *user_model.User, c *issues_m eventType = webhook.HookEventIssueComment } - mode, _ := access_model.AccessLevel(doer, c.Issue.Repo) - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: c.Issue.Repo}, eventType, &api.IssueCommentPayload{ + mode, _ := access_model.AccessLevel(ctx, doer, c.Issue.Repo) + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: c.Issue.Repo}, eventType, &api.IssueCommentPayload{ Action: api.HookIssueCommentEdited, - Issue: convert.ToAPIIssue(c.Issue), + Issue: convert.ToAPIIssue(ctx, c.Issue), Comment: convert.ToComment(c), Changes: &api.ChangesPayload{ Body: &api.ChangesFromPayload{ From: oldContent, }, }, - Repository: convert.ToRepo(c.Issue.Repo, mode), + Repository: convert.ToRepo(ctx, c.Issue.Repo, mode), Sender: convert.ToUser(doer, nil), IsPull: c.Issue.IsPull, }); err != nil { @@ -413,7 +394,7 @@ func (m *webhookNotifier) NotifyUpdateComment(doer *user_model.User, c *issues_m } } -func (m *webhookNotifier) NotifyCreateIssueComment(doer *user_model.User, repo *repo_model.Repository, +func (m *webhookNotifier) NotifyCreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, comment *issues_model.Comment, mentions []*user_model.User, ) { var eventType webhook.HookEventType @@ -423,12 +404,12 @@ func (m *webhookNotifier) NotifyCreateIssueComment(doer *user_model.User, repo * eventType = webhook.HookEventIssueComment } - mode, _ := access_model.AccessLevel(doer, repo) - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: issue.Repo}, eventType, &api.IssueCommentPayload{ + mode, _ := access_model.AccessLevel(ctx, doer, repo) + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, eventType, &api.IssueCommentPayload{ Action: api.HookIssueCommentCreated, - Issue: convert.ToAPIIssue(issue), + Issue: convert.ToAPIIssue(ctx, issue), Comment: convert.ToComment(comment), - Repository: convert.ToRepo(repo, mode), + Repository: convert.ToRepo(ctx, repo, mode), Sender: convert.ToUser(doer, nil), IsPull: issue.IsPull, }); err != nil { @@ -436,19 +417,19 @@ func (m *webhookNotifier) NotifyCreateIssueComment(doer *user_model.User, repo * } } -func (m *webhookNotifier) NotifyDeleteComment(doer *user_model.User, comment *issues_model.Comment) { +func (m *webhookNotifier) NotifyDeleteComment(ctx context.Context, doer *user_model.User, comment *issues_model.Comment) { var err error - if err = comment.LoadPoster(); err != nil { + if err = comment.LoadPoster(ctx); err != nil { log.Error("LoadPoster: %v", err) return } - if err = comment.LoadIssue(); err != nil { + if err = comment.LoadIssue(ctx); err != nil { log.Error("LoadIssue: %v", err) return } - if err = comment.Issue.LoadAttributes(db.DefaultContext); err != nil { + if err = comment.Issue.LoadAttributes(ctx); err != nil { log.Error("LoadAttributes: %v", err) return } @@ -460,12 +441,12 @@ func (m *webhookNotifier) NotifyDeleteComment(doer *user_model.User, comment *is eventType = webhook.HookEventIssueComment } - mode, _ := access_model.AccessLevel(doer, comment.Issue.Repo) - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: comment.Issue.Repo}, eventType, &api.IssueCommentPayload{ + mode, _ := access_model.AccessLevel(ctx, doer, comment.Issue.Repo) + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: comment.Issue.Repo}, eventType, &api.IssueCommentPayload{ Action: api.HookIssueCommentDeleted, - Issue: convert.ToAPIIssue(comment.Issue), + Issue: convert.ToAPIIssue(ctx, comment.Issue), Comment: convert.ToComment(comment), - Repository: convert.ToRepo(comment.Issue.Repo, mode), + Repository: convert.ToRepo(ctx, comment.Issue.Repo, mode), Sender: convert.ToUser(doer, nil), IsPull: comment.Issue.IsPull, }); err != nil { @@ -473,11 +454,11 @@ func (m *webhookNotifier) NotifyDeleteComment(doer *user_model.User, comment *is } } -func (m *webhookNotifier) NotifyNewWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) { +func (m *webhookNotifier) NotifyNewWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) { // Add to hook queue for created wiki page. - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ Action: api.HookWikiCreated, - Repository: convert.ToRepo(repo, perm.AccessModeOwner), + Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Sender: convert.ToUser(doer, nil), Page: page, Comment: comment, @@ -486,11 +467,11 @@ func (m *webhookNotifier) NotifyNewWikiPage(doer *user_model.User, repo *repo_mo } } -func (m *webhookNotifier) NotifyEditWikiPage(doer *user_model.User, repo *repo_model.Repository, page, comment string) { +func (m *webhookNotifier) NotifyEditWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page, comment string) { // Add to hook queue for edit wiki page. - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ Action: api.HookWikiEdited, - Repository: convert.ToRepo(repo, perm.AccessModeOwner), + Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Sender: convert.ToUser(doer, nil), Page: page, Comment: comment, @@ -499,11 +480,11 @@ func (m *webhookNotifier) NotifyEditWikiPage(doer *user_model.User, repo *repo_m } } -func (m *webhookNotifier) NotifyDeleteWikiPage(doer *user_model.User, repo *repo_model.Repository, page string) { +func (m *webhookNotifier) NotifyDeleteWikiPage(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, page string) { // Add to hook queue for edit wiki page. - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventWiki, &api.WikiPayload{ Action: api.HookWikiDeleted, - Repository: convert.ToRepo(repo, perm.AccessModeOwner), + Repository: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Sender: convert.ToUser(doer, nil), Page: page, }); err != nil { @@ -511,12 +492,9 @@ func (m *webhookNotifier) NotifyDeleteWikiPage(doer *user_model.User, repo *repo } } -func (m *webhookNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue *issues_model.Issue, +func (m *webhookNotifier) NotifyIssueChangeLabels(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, addedLabels, removedLabels []*issues_model.Label, ) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeLabels User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID)) - defer finished() - var err error if err = issue.LoadRepo(ctx); err != nil { @@ -524,18 +502,18 @@ func (m *webhookNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue * return } - if err = issue.LoadPoster(); err != nil { + if err = issue.LoadPoster(ctx); err != nil { log.Error("LoadPoster: %v", err) return } - mode, _ := access_model.AccessLevel(issue.Poster, issue.Repo) + mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo) if issue.IsPull { - if err = issue.LoadPullRequest(); err != nil { + if err = issue.LoadPullRequest(ctx); err != nil { log.Error("loadPullRequest: %v", err) return } - if err = issue.PullRequest.LoadIssue(); err != nil { + if err = issue.PullRequest.LoadIssue(ctx); err != nil { log.Error("LoadIssue: %v", err) return } @@ -543,15 +521,15 @@ func (m *webhookNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue * Action: api.HookIssueLabelUpdated, Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, perm.AccessModeNone), + Repository: convert.ToRepo(ctx, issue.Repo, perm.AccessModeNone), Sender: convert.ToUser(doer, nil), }) } else { err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueLabel, &api.IssuePayload{ Action: api.HookIssueLabelUpdated, Index: issue.Index, - Issue: convert.ToAPIIssue(issue), - Repository: convert.ToRepo(issue.Repo, mode), + Issue: convert.ToAPIIssue(ctx, issue), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } @@ -560,10 +538,7 @@ func (m *webhookNotifier) NotifyIssueChangeLabels(doer *user_model.User, issue * } } -func (m *webhookNotifier) NotifyIssueChangeMilestone(doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyIssueChangeMilestone User: %s[%d] Issue[%d] #%d in [%d]", doer.Name, doer.ID, issue.ID, issue.Index, issue.RepoID)) - defer finished() - +func (m *webhookNotifier) NotifyIssueChangeMilestone(ctx context.Context, doer *user_model.User, issue *issues_model.Issue, oldMilestoneID int64) { var hookAction api.HookIssueAction var err error if issue.MilestoneID > 0 { @@ -572,14 +547,14 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(doer *user_model.User, issu hookAction = api.HookIssueDemilestoned } - if err = issue.LoadAttributes(db.DefaultContext); err != nil { + if err = issue.LoadAttributes(ctx); err != nil { log.Error("issue.LoadAttributes failed: %v", err) return } - mode, _ := access_model.AccessLevel(doer, issue.Repo) + mode, _ := access_model.AccessLevel(ctx, doer, issue.Repo) if issue.IsPull { - err = issue.PullRequest.LoadIssue() + err = issue.PullRequest.LoadIssue(ctx) if err != nil { log.Error("LoadIssue: %v", err) return @@ -588,15 +563,15 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(doer *user_model.User, issu Action: hookAction, Index: issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, mode), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } else { err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventIssueMilestone, &api.IssuePayload{ Action: hookAction, Index: issue.Index, - Issue: convert.ToAPIIssue(issue), - Repository: convert.ToRepo(issue.Repo, mode), + Issue: convert.ToAPIIssue(ctx, issue), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), }) } @@ -605,10 +580,7 @@ func (m *webhookNotifier) NotifyIssueChangeMilestone(doer *user_model.User, issu } } -func (m *webhookNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyPushCommits User: %s[%d] in %s[%d]", pusher.Name, pusher.ID, repo.FullName(), repo.ID)) - defer finished() - +func (m *webhookNotifier) NotifyPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { apiPusher := convert.ToUser(pusher, nil) apiCommits, apiHeadCommit, err := commits.ToAPIPayloadCommits(ctx, repo.RepoPath(), repo.HTMLURL()) if err != nil { @@ -624,7 +596,7 @@ func (m *webhookNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_ Commits: apiCommits, TotalCommits: commits.Len, HeadCommit: apiHeadCommit, - Repo: convert.ToRepo(repo, perm.AccessModeOwner), + Repo: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Pusher: apiPusher, Sender: apiPusher, }); err != nil { @@ -632,23 +604,20 @@ func (m *webhookNotifier) NotifyPushCommits(pusher *user_model.User, repo *repo_ } } -func (m *webhookNotifier) NotifyAutoMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { +func (m *webhookNotifier) NotifyAutoMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { // just redirect to the NotifyMergePullRequest - m.NotifyMergePullRequest(pr, doer) + m.NotifyMergePullRequest(ctx, doer, pr) } -func (*webhookNotifier) NotifyMergePullRequest(pr *issues_model.PullRequest, doer *user_model.User) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyMergePullRequest Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID)) - defer finished() - +func (*webhookNotifier) NotifyMergePullRequest(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { // Reload pull request information. - if err := pr.LoadAttributes(); err != nil { + if err := pr.LoadAttributes(ctx); err != nil { log.Error("LoadAttributes: %v", err) return } - if err := pr.LoadIssue(); err != nil { - log.Error("LoadAttributes: %v", err) + if err := pr.LoadIssue(ctx); err != nil { + log.Error("LoadIssue: %v", err) return } @@ -657,7 +626,7 @@ func (*webhookNotifier) NotifyMergePullRequest(pr *issues_model.PullRequest, doe return } - mode, err := access_model.AccessLevel(doer, pr.Issue.Repo) + mode, err := access_model.AccessLevel(ctx, doer, pr.Issue.Repo) if err != nil { log.Error("models.AccessLevel: %v", err) return @@ -667,34 +636,26 @@ func (*webhookNotifier) NotifyMergePullRequest(pr *issues_model.PullRequest, doe apiPullRequest := &api.PullRequestPayload{ Index: pr.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), - Repository: convert.ToRepo(pr.Issue.Repo, mode), + Repository: convert.ToRepo(ctx, pr.Issue.Repo, mode), Sender: convert.ToUser(doer, nil), Action: api.HookIssueClosed, } - err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: pr.Issue.Repo}, webhook.HookEventPullRequest, apiPullRequest) - if err != nil { + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: pr.Issue.Repo}, webhook.HookEventPullRequest, apiPullRequest); err != nil { log.Error("PrepareWebhooks: %v", err) } } -func (m *webhookNotifier) NotifyPullRequestChangeTargetBranch(doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyPullRequestChangeTargetBranch Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID)) - defer finished() +func (m *webhookNotifier) NotifyPullRequestChangeTargetBranch(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest, oldBranch string) { + if err := pr.LoadIssue(ctx); err != nil { + log.Error("LoadIssue: %v", err) + return + } issue := pr.Issue - if !issue.IsPull { - return - } - var err error - if err = issue.LoadPullRequest(); err != nil { - log.Error("LoadPullRequest failed: %v", err) - return - } - issue.PullRequest.Issue = issue - mode, _ := access_model.AccessLevel(issue.Poster, issue.Repo) - err = webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventPullRequest, &api.PullRequestPayload{ + mode, _ := access_model.AccessLevel(ctx, issue.Poster, issue.Repo) + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: issue.Repo}, webhook.HookEventPullRequest, &api.PullRequestPayload{ Action: api.HookIssueEdited, Index: issue.Index, Changes: &api.ChangesPayload{ @@ -702,20 +663,15 @@ func (m *webhookNotifier) NotifyPullRequestChangeTargetBranch(doer *user_model.U From: oldBranch, }, }, - PullRequest: convert.ToAPIPullRequest(ctx, issue.PullRequest, nil), - Repository: convert.ToRepo(issue.Repo, mode), + PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), + Repository: convert.ToRepo(ctx, issue.Repo, mode), Sender: convert.ToUser(doer, nil), - }) - - if err != nil { - log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err) + }); err != nil { + log.Error("PrepareWebhooks [pr: %d]: %v", pr.ID, err) } } -func (m *webhookNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyPullRequestReview Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID)) - defer finished() - +func (m *webhookNotifier) NotifyPullRequestReview(ctx context.Context, pr *issues_model.PullRequest, review *issues_model.Review, comment *issues_model.Comment, mentions []*user_model.User) { var reviewHookType webhook.HookEventType switch review.Type { @@ -731,12 +687,12 @@ func (m *webhookNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, return } - if err := pr.LoadIssue(); err != nil { - log.Error("pr.LoadIssue: %v", err) + if err := pr.LoadIssue(ctx); err != nil { + log.Error("LoadIssue: %v", err) return } - mode, err := access_model.AccessLevel(review.Issue.Poster, review.Issue.Repo) + mode, err := access_model.AccessLevel(ctx, review.Issue.Poster, review.Issue.Repo) if err != nil { log.Error("models.AccessLevel: %v", err) return @@ -745,7 +701,7 @@ func (m *webhookNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, Action: api.HookIssueReviewed, Index: review.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), - Repository: convert.ToRepo(review.Issue.Repo, mode), + Repository: convert.ToRepo(ctx, review.Issue.Repo, mode), Sender: convert.ToUser(review.Reviewer, nil), Review: &api.ReviewPayload{ Type: string(reviewHookType), @@ -756,12 +712,12 @@ func (m *webhookNotifier) NotifyPullRequestReview(pr *issues_model.PullRequest, } } -func (m *webhookNotifier) NotifyCreateRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { +func (m *webhookNotifier) NotifyCreateRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { apiPusher := convert.ToUser(pusher, nil) - apiRepo := convert.ToRepo(repo, perm.AccessModeNone) + apiRepo := convert.ToRepo(ctx, repo, perm.AccessModeNone) refName := git.RefEndName(refFullName) - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventCreate, &api.CreatePayload{ + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventCreate, &api.CreatePayload{ Ref: refName, Sha: refID, RefType: refType, @@ -772,15 +728,12 @@ func (m *webhookNotifier) NotifyCreateRef(pusher *user_model.User, repo *repo_mo } } -func (m *webhookNotifier) NotifyPullRequestSynchronized(doer *user_model.User, pr *issues_model.PullRequest) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifyPullRequestSynchronized Pull[%d] #%d in [%d]", pr.ID, pr.Index, pr.BaseRepoID)) - defer finished() - - if err := pr.LoadIssue(); err != nil { - log.Error("pr.LoadIssue: %v", err) +func (m *webhookNotifier) NotifyPullRequestSynchronized(ctx context.Context, doer *user_model.User, pr *issues_model.PullRequest) { + if err := pr.LoadIssue(ctx); err != nil { + log.Error("LoadIssue: %v", err) return } - if err := pr.Issue.LoadAttributes(db.DefaultContext); err != nil { + if err := pr.Issue.LoadAttributes(ctx); err != nil { log.Error("LoadAttributes: %v", err) return } @@ -789,19 +742,19 @@ func (m *webhookNotifier) NotifyPullRequestSynchronized(doer *user_model.User, p Action: api.HookIssueSynchronized, Index: pr.Issue.Index, PullRequest: convert.ToAPIPullRequest(ctx, pr, nil), - Repository: convert.ToRepo(pr.Issue.Repo, perm.AccessModeNone), + Repository: convert.ToRepo(ctx, pr.Issue.Repo, perm.AccessModeNone), Sender: convert.ToUser(doer, nil), }); err != nil { log.Error("PrepareWebhooks [pull_id: %v]: %v", pr.ID, err) } } -func (m *webhookNotifier) NotifyDeleteRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { +func (m *webhookNotifier) NotifyDeleteRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { apiPusher := convert.ToUser(pusher, nil) - apiRepo := convert.ToRepo(repo, perm.AccessModeNone) + apiRepo := convert.ToRepo(ctx, repo, perm.AccessModeNone) refName := git.RefEndName(refFullName) - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: repo}, webhook.HookEventDelete, &api.DeletePayload{ + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: repo}, webhook.HookEventDelete, &api.DeletePayload{ Ref: refName, RefType: refType, PusherType: api.PusherTypeUser, @@ -812,39 +765,36 @@ func (m *webhookNotifier) NotifyDeleteRef(pusher *user_model.User, repo *repo_mo } } -func sendReleaseHook(doer *user_model.User, rel *repo_model.Release, action api.HookReleaseAction) { - if err := rel.LoadAttributes(); err != nil { +func sendReleaseHook(ctx context.Context, doer *user_model.User, rel *repo_model.Release, action api.HookReleaseAction) { + if err := rel.LoadAttributes(ctx); err != nil { log.Error("LoadAttributes: %v", err) return } - mode, _ := access_model.AccessLevel(doer, rel.Repo) - if err := webhook_services.PrepareWebhooks(db.DefaultContext, webhook_services.EventSource{Repository: rel.Repo}, webhook.HookEventRelease, &api.ReleasePayload{ + mode, _ := access_model.AccessLevel(ctx, doer, rel.Repo) + if err := webhook_services.PrepareWebhooks(ctx, webhook_services.EventSource{Repository: rel.Repo}, webhook.HookEventRelease, &api.ReleasePayload{ Action: action, Release: convert.ToRelease(rel), - Repository: convert.ToRepo(rel.Repo, mode), + Repository: convert.ToRepo(ctx, rel.Repo, mode), Sender: convert.ToUser(doer, nil), }); err != nil { log.Error("PrepareWebhooks: %v", err) } } -func (m *webhookNotifier) NotifyNewRelease(rel *repo_model.Release) { - sendReleaseHook(rel.Publisher, rel, api.HookReleasePublished) +func (m *webhookNotifier) NotifyNewRelease(ctx context.Context, rel *repo_model.Release) { + sendReleaseHook(ctx, rel.Publisher, rel, api.HookReleasePublished) } -func (m *webhookNotifier) NotifyUpdateRelease(doer *user_model.User, rel *repo_model.Release) { - sendReleaseHook(doer, rel, api.HookReleaseUpdated) +func (m *webhookNotifier) NotifyUpdateRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release) { + sendReleaseHook(ctx, doer, rel, api.HookReleaseUpdated) } -func (m *webhookNotifier) NotifyDeleteRelease(doer *user_model.User, rel *repo_model.Release) { - sendReleaseHook(doer, rel, api.HookReleaseDeleted) +func (m *webhookNotifier) NotifyDeleteRelease(ctx context.Context, doer *user_model.User, rel *repo_model.Release) { + sendReleaseHook(ctx, doer, rel, api.HookReleaseDeleted) } -func (m *webhookNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.NotifySyncPushCommits User: %s[%d] in %s[%d]", pusher.Name, pusher.ID, repo.FullName(), repo.ID)) - defer finished() - +func (m *webhookNotifier) NotifySyncPushCommits(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, opts *repository.PushUpdateOptions, commits *repository.PushCommits) { apiPusher := convert.ToUser(pusher, nil) apiCommits, apiHeadCommit, err := commits.ToAPIPayloadCommits(ctx, repo.RepoPath(), repo.HTMLURL()) if err != nil { @@ -860,7 +810,7 @@ func (m *webhookNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *r Commits: apiCommits, TotalCommits: commits.Len, HeadCommit: apiHeadCommit, - Repo: convert.ToRepo(repo, perm.AccessModeOwner), + Repo: convert.ToRepo(ctx, repo, perm.AccessModeOwner), Pusher: apiPusher, Sender: apiPusher, }); err != nil { @@ -868,31 +818,28 @@ func (m *webhookNotifier) NotifySyncPushCommits(pusher *user_model.User, repo *r } } -func (m *webhookNotifier) NotifySyncCreateRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { - m.NotifyCreateRef(pusher, repo, refType, refFullName, refID) +func (m *webhookNotifier) NotifySyncCreateRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName, refID string) { + m.NotifyCreateRef(ctx, pusher, repo, refType, refFullName, refID) } -func (m *webhookNotifier) NotifySyncDeleteRef(pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { - m.NotifyDeleteRef(pusher, repo, refType, refFullName) +func (m *webhookNotifier) NotifySyncDeleteRef(ctx context.Context, pusher *user_model.User, repo *repo_model.Repository, refType, refFullName string) { + m.NotifyDeleteRef(ctx, pusher, repo, refType, refFullName) } -func (m *webhookNotifier) NotifyPackageCreate(doer *user_model.User, pd *packages_model.PackageDescriptor) { - notifyPackage(doer, pd, api.HookPackageCreated) +func (m *webhookNotifier) NotifyPackageCreate(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) { + notifyPackage(ctx, doer, pd, api.HookPackageCreated) } -func (m *webhookNotifier) NotifyPackageDelete(doer *user_model.User, pd *packages_model.PackageDescriptor) { - notifyPackage(doer, pd, api.HookPackageDeleted) +func (m *webhookNotifier) NotifyPackageDelete(ctx context.Context, doer *user_model.User, pd *packages_model.PackageDescriptor) { + notifyPackage(ctx, doer, pd, api.HookPackageDeleted) } -func notifyPackage(sender *user_model.User, pd *packages_model.PackageDescriptor, action api.HookPackageAction) { +func notifyPackage(ctx context.Context, sender *user_model.User, pd *packages_model.PackageDescriptor, action api.HookPackageAction) { source := webhook_services.EventSource{ Repository: pd.Repository, Owner: pd.Owner, } - ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("webhook.notifyPackage Package: %s[%d]", pd.Package.Name, pd.Package.ID)) - defer finished() - apiPackage, err := convert.ToPackage(ctx, pd, sender) if err != nil { log.Error("Error converting package: %v", err) diff --git a/modules/options/base.go b/modules/options/base.go index e1d6efa7f0..039e934b3a 100644 --- a/modules/options/base.go +++ b/modules/options/base.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package options diff --git a/modules/options/dynamic.go b/modules/options/dynamic.go index 3739867580..a20253676e 100644 --- a/modules/options/dynamic.go +++ b/modules/options/dynamic.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT //go:build !bindata diff --git a/modules/options/options.go b/modules/options/options.go index 6ba3bd6a86..17a8fa482e 100644 --- a/modules/options/options.go +++ b/modules/options/options.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package options diff --git a/modules/options/options_bindata.go b/modules/options/options_bindata.go index 77b7a7ef41..29151cb3cb 100644 --- a/modules/options/options_bindata.go +++ b/modules/options/options_bindata.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build bindata diff --git a/modules/options/static.go b/modules/options/static.go index 4d60879be3..ff3c86d3f8 100644 --- a/modules/options/static.go +++ b/modules/options/static.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT //go:build bindata diff --git a/modules/packages/composer/metadata.go b/modules/packages/composer/metadata.go index 797576b1e7..b98294001c 100644 --- a/modules/packages/composer/metadata.go +++ b/modules/packages/composer/metadata.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package composer diff --git a/modules/packages/composer/metadata_test.go b/modules/packages/composer/metadata_test.go index feadc18b6a..a0e1a77a6e 100644 --- a/modules/packages/composer/metadata_test.go +++ b/modules/packages/composer/metadata_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package composer diff --git a/modules/packages/conan/conanfile_parser.go b/modules/packages/conan/conanfile_parser.go index 960e813533..c47b242cdc 100644 --- a/modules/packages/conan/conanfile_parser.go +++ b/modules/packages/conan/conanfile_parser.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package conan diff --git a/modules/packages/conan/conanfile_parser_test.go b/modules/packages/conan/conanfile_parser_test.go index 0ac9c87b14..5801570184 100644 --- a/modules/packages/conan/conanfile_parser_test.go +++ b/modules/packages/conan/conanfile_parser_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package conan diff --git a/modules/packages/conan/conaninfo_parser.go b/modules/packages/conan/conaninfo_parser.go index bb228e0207..5bb3fb8930 100644 --- a/modules/packages/conan/conaninfo_parser.go +++ b/modules/packages/conan/conaninfo_parser.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package conan diff --git a/modules/packages/conan/conaninfo_parser_test.go b/modules/packages/conan/conaninfo_parser_test.go index 3e28191b06..556a4b939e 100644 --- a/modules/packages/conan/conaninfo_parser_test.go +++ b/modules/packages/conan/conaninfo_parser_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package conan diff --git a/modules/packages/conan/metadata.go b/modules/packages/conan/metadata.go index a7d6a9df0b..256a376cf7 100644 --- a/modules/packages/conan/metadata.go +++ b/modules/packages/conan/metadata.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package conan diff --git a/modules/packages/conan/reference.go b/modules/packages/conan/reference.go index 49236981b6..37a5170dd3 100644 --- a/modules/packages/conan/reference.go +++ b/modules/packages/conan/reference.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package conan diff --git a/modules/packages/conan/reference_test.go b/modules/packages/conan/reference_test.go index 98eb2c8478..6ea86eb0dd 100644 --- a/modules/packages/conan/reference_test.go +++ b/modules/packages/conan/reference_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package conan diff --git a/modules/packages/container/helm/helm.go b/modules/packages/container/helm/helm.go index 98d3824a85..6981d430ad 100644 --- a/modules/packages/container/helm/helm.go +++ b/modules/packages/container/helm/helm.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package helm diff --git a/modules/packages/container/metadata.go b/modules/packages/container/metadata.go index fd38e67859..c3946f38f1 100644 --- a/modules/packages/container/metadata.go +++ b/modules/packages/container/metadata.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package container diff --git a/modules/packages/container/metadata_test.go b/modules/packages/container/metadata_test.go index 9400cf6954..f9ee478d63 100644 --- a/modules/packages/container/metadata_test.go +++ b/modules/packages/container/metadata_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package container diff --git a/modules/packages/container/oci/digest.go b/modules/packages/container/oci/digest.go index 5234814cfe..dd9cc0095c 100644 --- a/modules/packages/container/oci/digest.go +++ b/modules/packages/container/oci/digest.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package oci diff --git a/modules/packages/container/oci/mediatype.go b/modules/packages/container/oci/mediatype.go index 2636fbe288..f9c3907e17 100644 --- a/modules/packages/container/oci/mediatype.go +++ b/modules/packages/container/oci/mediatype.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package oci diff --git a/modules/packages/container/oci/oci.go b/modules/packages/container/oci/oci.go index 01cca8fe69..570d2e92c2 100644 --- a/modules/packages/container/oci/oci.go +++ b/modules/packages/container/oci/oci.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package oci diff --git a/modules/packages/container/oci/reference.go b/modules/packages/container/oci/reference.go index 120ff122d4..7ec399255d 100644 --- a/modules/packages/container/oci/reference.go +++ b/modules/packages/container/oci/reference.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package oci diff --git a/modules/packages/content_store.go b/modules/packages/content_store.go index a3a5d1a666..1181fa4d52 100644 --- a/modules/packages/content_store.go +++ b/modules/packages/content_store.go @@ -1,14 +1,15 @@ // 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. +// SPDX-License-Identifier: MIT package packages import ( "io" "path" + "strings" "code.gitea.io/gitea/modules/storage" + "code.gitea.io/gitea/modules/util" ) // BlobHash256Key is the key to address a blob content @@ -30,6 +31,13 @@ func (s *ContentStore) Get(key BlobHash256Key) (storage.Object, error) { return s.store.Open(KeyToRelativePath(key)) } +// FIXME: Workaround to be removed in v1.20 +// https://github.com/go-gitea/gitea/issues/19586 +func (s *ContentStore) Has(key BlobHash256Key) error { + _, err := s.store.Stat(KeyToRelativePath(key)) + return err +} + // Save stores a package blob func (s *ContentStore) Save(key BlobHash256Key, r io.Reader, size int64) error { _, err := s.store.Save(KeyToRelativePath(key), r, size) @@ -45,3 +53,13 @@ func (s *ContentStore) Delete(key BlobHash256Key) error { func KeyToRelativePath(key BlobHash256Key) string { return path.Join(string(key)[0:2], string(key)[2:4], string(key)) } + +// RelativePathToKey converts a relative path aa/bb/aabb000000... to the sha256 key aabb000000... +func RelativePathToKey(relativePath string) (BlobHash256Key, error) { + parts := strings.SplitN(relativePath, "/", 3) + if len(parts) != 3 || len(parts[0]) != 2 || len(parts[1]) != 2 || len(parts[2]) < 4 || parts[0]+parts[1] != parts[2][0:4] { + return "", util.ErrInvalidArgument + } + + return BlobHash256Key(parts[2]), nil +} diff --git a/modules/packages/hashed_buffer.go b/modules/packages/hashed_buffer.go index 3f8cafcfb5..ef00a45057 100644 --- a/modules/packages/hashed_buffer.go +++ b/modules/packages/hashed_buffer.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package packages diff --git a/modules/packages/hashed_buffer_test.go b/modules/packages/hashed_buffer_test.go index e21ec67e1f..e907aa0605 100644 --- a/modules/packages/hashed_buffer_test.go +++ b/modules/packages/hashed_buffer_test.go @@ -1,11 +1,10 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package packages import ( - "fmt" + "encoding/hex" "io" "strings" "testing" @@ -37,10 +36,10 @@ func TestHashedBuffer(t *testing.T) { assert.Equal(t, c.Data, string(data)) hashMD5, hashSHA1, hashSHA256, hashSHA512 := buf.Sums() - assert.Equal(t, c.HashMD5, fmt.Sprintf("%x", hashMD5)) - assert.Equal(t, c.HashSHA1, fmt.Sprintf("%x", hashSHA1)) - assert.Equal(t, c.HashSHA256, fmt.Sprintf("%x", hashSHA256)) - assert.Equal(t, c.HashSHA512, fmt.Sprintf("%x", hashSHA512)) + assert.Equal(t, c.HashMD5, hex.EncodeToString(hashMD5)) + assert.Equal(t, c.HashSHA1, hex.EncodeToString(hashSHA1)) + assert.Equal(t, c.HashSHA256, hex.EncodeToString(hashSHA256)) + assert.Equal(t, c.HashSHA512, hex.EncodeToString(hashSHA512)) assert.NoError(t, buf.Close()) } diff --git a/modules/packages/helm/metadata.go b/modules/packages/helm/metadata.go index 9517448ca6..98b5919a73 100644 --- a/modules/packages/helm/metadata.go +++ b/modules/packages/helm/metadata.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package helm @@ -14,7 +13,7 @@ import ( "code.gitea.io/gitea/modules/validation" "github.com/hashicorp/go-version" - "gopkg.in/yaml.v2" + "gopkg.in/yaml.v3" ) var ( diff --git a/modules/packages/maven/metadata.go b/modules/packages/maven/metadata.go index 6ee9d69687..be057c8c07 100644 --- a/modules/packages/maven/metadata.go +++ b/modules/packages/maven/metadata.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package maven diff --git a/modules/packages/maven/metadata_test.go b/modules/packages/maven/metadata_test.go index a17d456560..f4bc84268e 100644 --- a/modules/packages/maven/metadata_test.go +++ b/modules/packages/maven/metadata_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package maven diff --git a/modules/packages/multi_hasher.go b/modules/packages/multi_hasher.go index 4d17441d8c..83a4b5b7af 100644 --- a/modules/packages/multi_hasher.go +++ b/modules/packages/multi_hasher.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package packages diff --git a/modules/packages/multi_hasher_test.go b/modules/packages/multi_hasher_test.go index 6c895ce120..a37debbc95 100644 --- a/modules/packages/multi_hasher_test.go +++ b/modules/packages/multi_hasher_test.go @@ -1,11 +1,10 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package packages import ( - "fmt" + "encoding/hex" "testing" "github.com/stretchr/testify/assert" @@ -25,10 +24,10 @@ func TestMultiHasherSums(t *testing.T) { hashMD5, hashSHA1, hashSHA256, hashSHA512 := h.Sums() - assert.Equal(t, expectedMD5, fmt.Sprintf("%x", hashMD5)) - assert.Equal(t, expectedSHA1, fmt.Sprintf("%x", hashSHA1)) - assert.Equal(t, expectedSHA256, fmt.Sprintf("%x", hashSHA256)) - assert.Equal(t, expectedSHA512, fmt.Sprintf("%x", hashSHA512)) + assert.Equal(t, expectedMD5, hex.EncodeToString(hashMD5)) + assert.Equal(t, expectedSHA1, hex.EncodeToString(hashSHA1)) + assert.Equal(t, expectedSHA256, hex.EncodeToString(hashSHA256)) + assert.Equal(t, expectedSHA512, hex.EncodeToString(hashSHA512)) }) t.Run("State", func(t *testing.T) { @@ -46,9 +45,9 @@ func TestMultiHasherSums(t *testing.T) { hashMD5, hashSHA1, hashSHA256, hashSHA512 := h2.Sums() - assert.Equal(t, expectedMD5, fmt.Sprintf("%x", hashMD5)) - assert.Equal(t, expectedSHA1, fmt.Sprintf("%x", hashSHA1)) - assert.Equal(t, expectedSHA256, fmt.Sprintf("%x", hashSHA256)) - assert.Equal(t, expectedSHA512, fmt.Sprintf("%x", hashSHA512)) + assert.Equal(t, expectedMD5, hex.EncodeToString(hashMD5)) + assert.Equal(t, expectedSHA1, hex.EncodeToString(hashSHA1)) + assert.Equal(t, expectedSHA256, hex.EncodeToString(hashSHA256)) + assert.Equal(t, expectedSHA512, hex.EncodeToString(hashSHA512)) }) } diff --git a/modules/packages/npm/creator.go b/modules/packages/npm/creator.go index 16cadefb89..02f6724812 100644 --- a/modules/packages/npm/creator.go +++ b/modules/packages/npm/creator.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package npm diff --git a/modules/packages/npm/creator_test.go b/modules/packages/npm/creator_test.go index 2b844f4b0e..9a2b1e10b2 100644 --- a/modules/packages/npm/creator_test.go +++ b/modules/packages/npm/creator_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package npm diff --git a/modules/packages/npm/metadata.go b/modules/packages/npm/metadata.go index 44714cd6ea..aafbdf779c 100644 --- a/modules/packages/npm/metadata.go +++ b/modules/packages/npm/metadata.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package npm diff --git a/modules/packages/nuget/metadata.go b/modules/packages/nuget/metadata.go index 2b555e47e9..dc72d0982a 100644 --- a/modules/packages/nuget/metadata.go +++ b/modules/packages/nuget/metadata.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package nuget diff --git a/modules/packages/nuget/metadata_test.go b/modules/packages/nuget/metadata_test.go index e8c7773e97..74c3e7dfaa 100644 --- a/modules/packages/nuget/metadata_test.go +++ b/modules/packages/nuget/metadata_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package nuget diff --git a/modules/packages/nuget/symbol_extractor.go b/modules/packages/nuget/symbol_extractor.go index 9c04d7bfb4..634bbb17e6 100644 --- a/modules/packages/nuget/symbol_extractor.go +++ b/modules/packages/nuget/symbol_extractor.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package nuget diff --git a/modules/packages/nuget/symbol_extractor_test.go b/modules/packages/nuget/symbol_extractor_test.go index 892d718caa..fa1b80ee82 100644 --- a/modules/packages/nuget/symbol_extractor_test.go +++ b/modules/packages/nuget/symbol_extractor_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package nuget diff --git a/modules/packages/pub/metadata.go b/modules/packages/pub/metadata.go index 1fc4908b91..36fe665707 100644 --- a/modules/packages/pub/metadata.go +++ b/modules/packages/pub/metadata.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package pub @@ -15,7 +14,7 @@ import ( "code.gitea.io/gitea/modules/validation" "github.com/hashicorp/go-version" - "gopkg.in/yaml.v2" + "gopkg.in/yaml.v3" ) var ( diff --git a/modules/packages/pub/metadata_test.go b/modules/packages/pub/metadata_test.go index e43ed64fc6..4c0c3f0ec6 100644 --- a/modules/packages/pub/metadata_test.go +++ b/modules/packages/pub/metadata_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package pub diff --git a/modules/packages/pypi/metadata.go b/modules/packages/pypi/metadata.go index df367d10e2..125728c4f1 100644 --- a/modules/packages/pypi/metadata.go +++ b/modules/packages/pypi/metadata.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package pypi diff --git a/modules/packages/rubygems/marshal.go b/modules/packages/rubygems/marshal.go index 2c45042fa8..14fb755606 100644 --- a/modules/packages/rubygems/marshal.go +++ b/modules/packages/rubygems/marshal.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package rubygems diff --git a/modules/packages/rubygems/marshal_test.go b/modules/packages/rubygems/marshal_test.go index e5963ebcd6..501757bfed 100644 --- a/modules/packages/rubygems/marshal_test.go +++ b/modules/packages/rubygems/marshal_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package rubygems diff --git a/modules/packages/rubygems/metadata.go b/modules/packages/rubygems/metadata.go index 05c1a8a719..e2c73c8f3a 100644 --- a/modules/packages/rubygems/metadata.go +++ b/modules/packages/rubygems/metadata.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package rubygems @@ -14,7 +13,7 @@ import ( "code.gitea.io/gitea/modules/validation" - "gopkg.in/yaml.v2" + "gopkg.in/yaml.v3" ) var ( @@ -120,7 +119,7 @@ func (r requirement) AsVersionRequirement() []VersionRequirement { if !ok { continue } - vm, ok := req[1].(map[interface{}]interface{}) + vm, ok := req[1].(map[string]interface{}) if !ok { continue } diff --git a/modules/packages/rubygems/metadata_test.go b/modules/packages/rubygems/metadata_test.go index dbefa9c236..ec2fa08b6b 100644 --- a/modules/packages/rubygems/metadata_test.go +++ b/modules/packages/rubygems/metadata_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package rubygems diff --git a/modules/packages/vagrant/metadata.go b/modules/packages/vagrant/metadata.go index f52989b2e2..6789533339 100644 --- a/modules/packages/vagrant/metadata.go +++ b/modules/packages/vagrant/metadata.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package vagrant diff --git a/modules/packages/vagrant/metadata_test.go b/modules/packages/vagrant/metadata_test.go index 9720c945ae..d616ffe3d3 100644 --- a/modules/packages/vagrant/metadata_test.go +++ b/modules/packages/vagrant/metadata_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package vagrant diff --git a/modules/paginator/paginator.go b/modules/paginator/paginator.go index 342ee8929c..8258d194c2 100644 --- a/modules/paginator/paginator.go +++ b/modules/paginator/paginator.go @@ -1,5 +1,6 @@ // Copyright 2022 The Gitea Authors. // Copyright 2015 https://github.com/unknwon. Licensed under the Apache License, Version 2.0 +// SPDX-License-Identifier: Apache-2.0 package paginator diff --git a/modules/paginator/paginator_test.go b/modules/paginator/paginator_test.go index 404f76f6c4..41bb305337 100644 --- a/modules/paginator/paginator_test.go +++ b/modules/paginator/paginator_test.go @@ -1,5 +1,6 @@ // Copyright 2022 The Gitea Authors. // Copyright 2015 https://github.com/unknwon. Licensed under the Apache License, Version 2.0 +// SPDX-License-Identifier: Apache-2.0 package paginator diff --git a/modules/password/password.go b/modules/password/password.go index e1f1f769ec..fe2a2a7bd5 100644 --- a/modules/password/password.go +++ b/modules/password/password.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package password diff --git a/modules/password/password_test.go b/modules/password/password_test.go index 63f98aa9c3..6c35dc86bd 100644 --- a/modules/password/password_test.go +++ b/modules/password/password_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package password diff --git a/modules/password/pwn.go b/modules/password/pwn.go index 938524e6de..e8565e5bb1 100644 --- a/modules/password/pwn.go +++ b/modules/password/pwn.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package password diff --git a/modules/pprof/pprof.go b/modules/pprof/pprof.go index 8ce0ad484e..c611c14270 100644 --- a/modules/pprof/pprof.go +++ b/modules/pprof/pprof.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package pprof diff --git a/modules/private/hook.go b/modules/private/hook.go index e208c14378..027014270a 100644 --- a/modules/private/hook.go +++ b/modules/private/hook.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package private diff --git a/modules/private/internal.go b/modules/private/internal.go index 21e5c9a279..a8b62fdde7 100644 --- a/modules/private/internal.go +++ b/modules/private/internal.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package private diff --git a/modules/private/key.go b/modules/private/key.go index 8dfd82a6d6..f09d6de2bf 100644 --- a/modules/private/key.go +++ b/modules/private/key.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package private diff --git a/modules/private/mail.go b/modules/private/mail.go index 3efef3bece..6eb7c2acd0 100644 --- a/modules/private/mail.go +++ b/modules/private/mail.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package private diff --git a/modules/private/manager.go b/modules/private/manager.go index ba51260ebb..bbf470cd7a 100644 --- a/modules/private/manager.go +++ b/modules/private/manager.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package private diff --git a/modules/private/restore_repo.go b/modules/private/restore_repo.go index b1561f392b..f40d914a7b 100644 --- a/modules/private/restore_repo.go +++ b/modules/private/restore_repo.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package private diff --git a/modules/private/serv.go b/modules/private/serv.go index 2e1367e4c4..c176e1ddfc 100644 --- a/modules/private/serv.go +++ b/modules/private/serv.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package private diff --git a/modules/process/context.go b/modules/process/context.go index 6df5bc1513..f1bc582ff0 100644 --- a/modules/process/context.go +++ b/modules/process/context.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package process diff --git a/modules/process/error.go b/modules/process/error.go index 7a72bda40e..8f02f65258 100644 --- a/modules/process/error.go +++ b/modules/process/error.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package process diff --git a/modules/process/manager.go b/modules/process/manager.go index 7f14287de5..1272510067 100644 --- a/modules/process/manager.go +++ b/modules/process/manager.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package process diff --git a/modules/process/manager_exec.go b/modules/process/manager_exec.go index 77e3d3193a..c983173748 100644 --- a/modules/process/manager_exec.go +++ b/modules/process/manager_exec.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package process diff --git a/modules/process/manager_stacktraces.go b/modules/process/manager_stacktraces.go index 628d9cebcd..49bd5071f6 100644 --- a/modules/process/manager_stacktraces.go +++ b/modules/process/manager_stacktraces.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package process diff --git a/modules/process/manager_test.go b/modules/process/manager_test.go index 30eabeb37a..527072713f 100644 --- a/modules/process/manager_test.go +++ b/modules/process/manager_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package process diff --git a/modules/process/manager_unix.go b/modules/process/manager_unix.go index 1e7c77fdbf..c5be906b35 100644 --- a/modules/process/manager_unix.go +++ b/modules/process/manager_unix.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT //go:build !windows diff --git a/modules/process/manager_windows.go b/modules/process/manager_windows.go index 35f66d9fa5..44a84f2203 100644 --- a/modules/process/manager_windows.go +++ b/modules/process/manager_windows.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT //go:build windows diff --git a/modules/process/process.go b/modules/process/process.go index 2f7ea18373..06a28c4a60 100644 --- a/modules/process/process.go +++ b/modules/process/process.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package process diff --git a/modules/proxy/proxy.go b/modules/proxy/proxy.go index 61730544b0..f0cd366c12 100644 --- a/modules/proxy/proxy.go +++ b/modules/proxy/proxy.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package proxy diff --git a/modules/proxyprotocol/conn.go b/modules/proxyprotocol/conn.go index 10333b204d..f437f13683 100644 --- a/modules/proxyprotocol/conn.go +++ b/modules/proxyprotocol/conn.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package proxyprotocol diff --git a/modules/proxyprotocol/errors.go b/modules/proxyprotocol/errors.go index 2acf9d84b0..5439a86bd8 100644 --- a/modules/proxyprotocol/errors.go +++ b/modules/proxyprotocol/errors.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package proxyprotocol diff --git a/modules/proxyprotocol/listener.go b/modules/proxyprotocol/listener.go index 64d9b323e5..ec85c425d3 100644 --- a/modules/proxyprotocol/listener.go +++ b/modules/proxyprotocol/listener.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package proxyprotocol diff --git a/modules/proxyprotocol/util.go b/modules/proxyprotocol/util.go index b12771b686..a280663b27 100644 --- a/modules/proxyprotocol/util.go +++ b/modules/proxyprotocol/util.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package proxyprotocol diff --git a/modules/public/mime_types.go b/modules/public/mime_types.go index f8c92e824f..32bdf3bfa2 100644 --- a/modules/public/mime_types.go +++ b/modules/public/mime_types.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package public diff --git a/modules/public/public.go b/modules/public/public.go index ac1d80c860..42026f9b10 100644 --- a/modules/public/public.go +++ b/modules/public/public.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package public diff --git a/modules/public/public_bindata.go b/modules/public/public_bindata.go index fe250c6454..4878f88ad1 100644 --- a/modules/public/public_bindata.go +++ b/modules/public/public_bindata.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build bindata diff --git a/modules/public/public_test.go b/modules/public/public_test.go index 8b58d6af33..5e4bf5d671 100644 --- a/modules/public/public_test.go +++ b/modules/public/public_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package public diff --git a/modules/public/serve_dynamic.go b/modules/public/serve_dynamic.go index 672924a636..cd74ee5743 100644 --- a/modules/public/serve_dynamic.go +++ b/modules/public/serve_dynamic.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT //go:build !bindata diff --git a/modules/public/serve_static.go b/modules/public/serve_static.go index 10120bf85d..e85ca79253 100644 --- a/modules/public/serve_static.go +++ b/modules/public/serve_static.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT //go:build bindata diff --git a/modules/queue/bytefifo.go b/modules/queue/bytefifo.go index bb98d468fb..c33b79426e 100644 --- a/modules/queue/bytefifo.go +++ b/modules/queue/bytefifo.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/helper.go b/modules/queue/helper.go index 9ad95badeb..c6fb9447b7 100644 --- a/modules/queue/helper.go +++ b/modules/queue/helper.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/manager.go b/modules/queue/manager.go index bba2c54ad2..6975e02907 100644 --- a/modules/queue/manager.go +++ b/modules/queue/manager.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/queue.go b/modules/queue/queue.go index a166a935a6..22ee64f8e2 100644 --- a/modules/queue/queue.go +++ b/modules/queue/queue.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/queue_bytefifo.go b/modules/queue/queue_bytefifo.go index 79f69f07ce..ee00a5428a 100644 --- a/modules/queue/queue_bytefifo.go +++ b/modules/queue/queue_bytefifo.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/queue_channel.go b/modules/queue/queue_channel.go index 028023d500..431f48390c 100644 --- a/modules/queue/queue_channel.go +++ b/modules/queue/queue_channel.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/queue_channel_test.go b/modules/queue/queue_channel_test.go index 949c452893..9b92398bac 100644 --- a/modules/queue/queue_channel_test.go +++ b/modules/queue/queue_channel_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/queue_disk.go b/modules/queue/queue_disk.go index 2691ab02f5..fbedb8e5b9 100644 --- a/modules/queue/queue_disk.go +++ b/modules/queue/queue_disk.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/queue_disk_channel.go b/modules/queue/queue_disk_channel.go index c00f620276..c7526714c6 100644 --- a/modules/queue/queue_disk_channel.go +++ b/modules/queue/queue_disk_channel.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/queue_disk_channel_test.go b/modules/queue/queue_disk_channel_test.go index b1820e73ac..318610355e 100644 --- a/modules/queue/queue_disk_channel_test.go +++ b/modules/queue/queue_disk_channel_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/queue_disk_test.go b/modules/queue/queue_disk_test.go index b0835c896f..8f83abf42c 100644 --- a/modules/queue/queue_disk_test.go +++ b/modules/queue/queue_disk_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/queue_redis.go b/modules/queue/queue_redis.go index 84ab235d5e..039e95241c 100644 --- a/modules/queue/queue_redis.go +++ b/modules/queue/queue_redis.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/queue_test.go b/modules/queue/queue_test.go index 65fb816537..42d34c806c 100644 --- a/modules/queue/queue_test.go +++ b/modules/queue/queue_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/queue_wrapped.go b/modules/queue/queue_wrapped.go index e581ba75f3..84d6dd98a5 100644 --- a/modules/queue/queue_wrapped.go +++ b/modules/queue/queue_wrapped.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/setting.go b/modules/queue/setting.go index 880770f073..1e5259fcfb 100644 --- a/modules/queue/setting.go +++ b/modules/queue/setting.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/unique_queue.go b/modules/queue/unique_queue.go index 87e0594ecf..8f8215c71d 100644 --- a/modules/queue/unique_queue.go +++ b/modules/queue/unique_queue.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/unique_queue_channel.go b/modules/queue/unique_queue_channel.go index d1bf7239eb..f2d3dbdc97 100644 --- a/modules/queue/unique_queue_channel.go +++ b/modules/queue/unique_queue_channel.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/unique_queue_channel_test.go b/modules/queue/unique_queue_channel_test.go index 6daf3fc96e..9372694b87 100644 --- a/modules/queue/unique_queue_channel_test.go +++ b/modules/queue/unique_queue_channel_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/unique_queue_disk.go b/modules/queue/unique_queue_disk.go index dae32f75a8..406f64784c 100644 --- a/modules/queue/unique_queue_disk.go +++ b/modules/queue/unique_queue_disk.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/unique_queue_disk_channel.go b/modules/queue/unique_queue_disk_channel.go index 8e0322bb90..405726182d 100644 --- a/modules/queue/unique_queue_disk_channel.go +++ b/modules/queue/unique_queue_disk_channel.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/unique_queue_redis.go b/modules/queue/unique_queue_redis.go index 477d5dd81f..491ae5d15e 100644 --- a/modules/queue/unique_queue_redis.go +++ b/modules/queue/unique_queue_redis.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/unique_queue_wrapped.go b/modules/queue/unique_queue_wrapped.go index 5245a35f77..22eeb75c40 100644 --- a/modules/queue/unique_queue_wrapped.go +++ b/modules/queue/unique_queue_wrapped.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/queue/workerpool.go b/modules/queue/workerpool.go index bdf04a363b..244927880e 100644 --- a/modules/queue/workerpool.go +++ b/modules/queue/workerpool.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package queue diff --git a/modules/recaptcha/recaptcha.go b/modules/recaptcha/recaptcha.go index 91b70dc588..1777d169c1 100644 --- a/modules/recaptcha/recaptcha.go +++ b/modules/recaptcha/recaptcha.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package recaptcha diff --git a/modules/references/references.go b/modules/references/references.go index 8fd0c8f055..5cbbf8313c 100644 --- a/modules/references/references.go +++ b/modules/references/references.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package references diff --git a/modules/references/references_test.go b/modules/references/references_test.go index 507adadb1f..835cee3a36 100644 --- a/modules/references/references_test.go +++ b/modules/references/references_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package references diff --git a/modules/regexplru/regexplru.go b/modules/regexplru/regexplru.go index 97c7cff4c1..dd3c5df82d 100644 --- a/modules/regexplru/regexplru.go +++ b/modules/regexplru/regexplru.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package regexplru diff --git a/modules/regexplru/regexplru_test.go b/modules/regexplru/regexplru_test.go index 041f0dcfb9..9c24b23fa9 100644 --- a/modules/regexplru/regexplru_test.go +++ b/modules/regexplru/regexplru_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package regexplru diff --git a/modules/repository/collaborator.go b/modules/repository/collaborator.go index 9d20a25890..f2b9515187 100644 --- a/modules/repository/collaborator.go +++ b/modules/repository/collaborator.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package repository @@ -14,30 +13,25 @@ import ( user_model "code.gitea.io/gitea/models/user" ) -func addCollaborator(ctx context.Context, repo *repo_model.Repository, u *user_model.User) error { - collaboration := &repo_model.Collaboration{ - RepoID: repo.ID, - UserID: u.ID, - } +func AddCollaborator(ctx context.Context, repo *repo_model.Repository, u *user_model.User) error { + return db.AutoTx(ctx, func(ctx context.Context) error { + collaboration := &repo_model.Collaboration{ + RepoID: repo.ID, + UserID: u.ID, + } - has, err := db.GetByBean(ctx, collaboration) - if err != nil { - return err - } else if has { - return nil - } - collaboration.Mode = perm.AccessModeWrite + has, err := db.GetByBean(ctx, collaboration) + if err != nil { + return err + } else if has { + return nil + } + collaboration.Mode = perm.AccessModeWrite - if err = db.Insert(ctx, collaboration); err != nil { - return err - } + if err = db.Insert(ctx, collaboration); err != nil { + return err + } - return access_model.RecalculateUserAccess(ctx, repo, u.ID) -} - -// AddCollaborator adds new collaboration to a repository with default access mode. -func AddCollaborator(repo *repo_model.Repository, u *user_model.User) error { - return db.WithTx(func(ctx context.Context) error { - return addCollaborator(ctx, repo, u) + return access_model.RecalculateUserAccess(ctx, repo, u.ID) }) } diff --git a/modules/repository/collaborator_test.go b/modules/repository/collaborator_test.go index 1b927aa3b6..6cf239d0ea 100644 --- a/modules/repository/collaborator_test.go +++ b/modules/repository/collaborator_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository @@ -26,7 +25,7 @@ func TestRepository_AddCollaborator(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) assert.NoError(t, repo.GetOwner(db.DefaultContext)) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userID}) - assert.NoError(t, AddCollaborator(repo, user)) + assert.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID}, &user_model.User{ID: userID}) } testSuccess(1, 4) @@ -51,7 +50,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { } // change to collaborator - assert.NoError(t, AddCollaborator(repo, user)) + assert.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -104,7 +103,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { } // change to collaborator to default write access - assert.NoError(t, AddCollaborator(repo, user)) + assert.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -112,7 +111,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { assert.True(t, perm.CanWrite(unit.Type)) } - assert.NoError(t, repo_model.ChangeCollaborationAccessMode(repo, user.ID, perm_model.AccessModeRead)) + assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, user.ID, perm_model.AccessModeRead)) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -156,7 +155,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { } // change to collaborator to default write access - assert.NoError(t, AddCollaborator(repo, user)) + assert.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -164,7 +163,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { assert.True(t, perm.CanWrite(unit.Type)) } - assert.NoError(t, repo_model.ChangeCollaborationAccessMode(repo, user.ID, perm_model.AccessModeRead)) + assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, user.ID, perm_model.AccessModeRead)) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -218,7 +217,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { } // change to collaborator to default write access - assert.NoError(t, AddCollaborator(repo, user)) + assert.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -226,7 +225,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { assert.True(t, perm.CanWrite(unit.Type)) } - assert.NoError(t, repo_model.ChangeCollaborationAccessMode(repo, user.ID, perm_model.AccessModeRead)) + assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, user.ID, perm_model.AccessModeRead)) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, user) assert.NoError(t, err) for _, unit := range repo.Units { diff --git a/modules/repository/commits.go b/modules/repository/commits.go index 7d6eec151f..a47f9b2dc8 100644 --- a/modules/repository/commits.go +++ b/modules/repository/commits.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository diff --git a/modules/repository/commits_test.go b/modules/repository/commits_test.go index 7bd741d0c8..2ae4bc73d2 100644 --- a/modules/repository/commits_test.go +++ b/modules/repository/commits_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository diff --git a/modules/repository/create.go b/modules/repository/create.go index 1fec0335a2..1e157ec85e 100644 --- a/modules/repository/create.go +++ b/modules/repository/create.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository @@ -126,10 +125,10 @@ func CreateRepositoryByExample(ctx context.Context, doer, u *user_model.User, re return fmt.Errorf("IsUserRepoAdmin: %w", err) } else if !isAdmin { // Make creator repo admin if it wasn't assigned automatically - if err = addCollaborator(ctx, repo, doer); err != nil { - return fmt.Errorf("addCollaborator: %w", err) + if err = AddCollaborator(ctx, repo, doer); err != nil { + return fmt.Errorf("AddCollaborator: %w", err) } - if err = repo_model.ChangeCollaborationAccessModeCtx(ctx, repo, doer.ID, perm.AccessModeAdmin); err != nil { + if err = repo_model.ChangeCollaborationAccessMode(ctx, repo, doer.ID, perm.AccessModeAdmin); err != nil { return fmt.Errorf("ChangeCollaborationAccessModeCtx: %w", err) } } @@ -211,7 +210,7 @@ func CreateRepository(doer, u *user_model.User, opts CreateRepoOptions) (*repo_m var rollbackRepo *repo_model.Repository - if err := db.WithTx(func(ctx context.Context) error { + if err := db.WithTx(db.DefaultContext, func(ctx context.Context) error { if err := CreateRepositoryByExample(ctx, doer, u, repo, false); err != nil { return err } diff --git a/modules/repository/create_test.go b/modules/repository/create_test.go index 3040782845..da4a738b64 100644 --- a/modules/repository/create_test.go +++ b/modules/repository/create_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository @@ -26,7 +25,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { testTeamRepositories := func(teamID int64, repoIds []int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, team.GetRepositoriesCtx(db.DefaultContext), "%s: GetRepositories", team.Name) + assert.NoError(t, team.LoadRepositories(db.DefaultContext), "%s: GetRepositories", team.Name) assert.Len(t, team.Repos, team.NumRepos, "%s: len repo", team.Name) assert.Len(t, team.Repos, len(repoIds), "%s: repo count", team.Name) for i, rid := range repoIds { @@ -37,7 +36,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { } // Get an admin user. - user, err := user_model.GetUserByID(1) + user, err := user_model.GetUserByID(db.DefaultContext, 1) assert.NoError(t, err, "GetUserByID") // Create org. @@ -154,7 +153,7 @@ func TestUpdateRepositoryVisibilityChanged(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // Get sample repo and change visibility - repo, err := repo_model.GetRepositoryByID(9) + repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 9) assert.NoError(t, err) repo.IsPrivate = true diff --git a/modules/repository/delete.go b/modules/repository/delete.go index 25fb15e300..c7e05e6669 100644 --- a/modules/repository/delete.go +++ b/modules/repository/delete.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package repository diff --git a/modules/repository/env.go b/modules/repository/env.go index e86e0d4535..646bf35cc6 100644 --- a/modules/repository/env.go +++ b/modules/repository/env.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository diff --git a/modules/repository/fork.go b/modules/repository/fork.go index c967d3b741..8e9f3a8976 100644 --- a/modules/repository/fork.go +++ b/modules/repository/fork.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository diff --git a/modules/repository/generate.go b/modules/repository/generate.go index c5fd7d60bf..d72934729c 100644 --- a/modules/repository/generate.go +++ b/modules/repository/generate.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository @@ -244,7 +243,7 @@ func generateGitContent(ctx context.Context, repo, templateRepo, generateRepo *r } // re-fetch repo - if repo, err = repo_model.GetRepositoryByIDCtx(ctx, repo.ID); err != nil { + if repo, err = repo_model.GetRepositoryByID(ctx, repo.ID); err != nil { return fmt.Errorf("getRepositoryByID: %w", err) } diff --git a/modules/repository/generate_test.go b/modules/repository/generate_test.go index 139fa4c918..1cb9a50f67 100644 --- a/modules/repository/generate_test.go +++ b/modules/repository/generate_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository diff --git a/modules/repository/hooks.go b/modules/repository/hooks.go index 4d7d294a92..a95b9c2e99 100644 --- a/modules/repository/hooks.go +++ b/modules/repository/hooks.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repository diff --git a/modules/repository/init.go b/modules/repository/init.go index 65072a9599..59284a5baf 100644 --- a/modules/repository/init.go +++ b/modules/repository/init.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository @@ -415,7 +414,7 @@ func initRepository(ctx context.Context, repoPath string, u *user_model.User, re // Re-fetch the repository from database before updating it (else it would // override changes that were done earlier with sql) - if repo, err = repo_model.GetRepositoryByIDCtx(ctx, repo.ID); err != nil { + if repo, err = repo_model.GetRepositoryByID(ctx, repo.ID); err != nil { return fmt.Errorf("getRepositoryByID: %w", err) } diff --git a/modules/repository/main_test.go b/modules/repository/main_test.go index 42134fa7ad..007790f2a9 100644 --- a/modules/repository/main_test.go +++ b/modules/repository/main_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository diff --git a/modules/repository/push.go b/modules/repository/push.go index 4e4b4000b1..1fa711b359 100644 --- a/modules/repository/push.go +++ b/modules/repository/push.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repository diff --git a/modules/repository/repo.go b/modules/repository/repo.go index de6de3bda4..a90eb8a764 100644 --- a/modules/repository/repo.go +++ b/modules/repository/repo.go @@ -1,11 +1,11 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository import ( "context" + "errors" "fmt" "io" "net/http" @@ -79,6 +79,9 @@ func MigrateRepositoryGitData(ctx context.Context, u *user_model.User, Timeout: migrateTimeout, SkipTLSVerify: setting.Migrations.SkipTLSVerify, }); err != nil { + if errors.Is(err, context.DeadlineExceeded) { + return repo, fmt.Errorf("Clone timed out. Consider increasing [git.timeout] MIGRATE in app.ini. Underlying Error: %w", err) + } return repo, fmt.Errorf("Clone: %w", err) } @@ -169,7 +172,7 @@ func MigrateRepositoryGitData(ctx context.Context, u *user_model.User, } } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } @@ -284,7 +287,7 @@ func SyncReleasesWithTags(repo *repo_model.Repository, gitRepo *git.Repository) } for page := 1; ; page++ { opts.Page = page - rels, err := repo_model.GetReleasesByRepoID(repo.ID, opts) + rels, err := repo_model.GetReleasesByRepoID(gitRepo.Ctx, repo.ID, opts) if err != nil { return fmt.Errorf("unable to GetReleasesByRepoID in Repo[%d:%s/%s]: %w", repo.ID, repo.OwnerName, repo.Name, err) } @@ -485,7 +488,7 @@ func pullMirrorReleaseSync(repo *repo_model.Repository, gitRepo *git.Repository) if err != nil { return fmt.Errorf("unable to GetTagInfos in pull-mirror Repo[%d:%s/%s]: %w", repo.ID, repo.OwnerName, repo.Name, err) } - err = db.WithTx(func(ctx context.Context) error { + err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { // // clear out existing releases // diff --git a/modules/repository/temp.go b/modules/repository/temp.go index 21af039469..53646718e0 100644 --- a/modules/repository/temp.go +++ b/modules/repository/temp.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository diff --git a/modules/secret/secret.go b/modules/secret/secret.go index e7edc7a95e..b84d1cfea8 100644 --- a/modules/secret/secret.go +++ b/modules/secret/secret.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package secret diff --git a/modules/secret/secret_test.go b/modules/secret/secret_test.go index b1c99d8513..0a189ecebf 100644 --- a/modules/secret/secret_test.go +++ b/modules/secret/secret_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package secret diff --git a/modules/session/db.go b/modules/session/db.go index f9de37210f..6fdfb81e03 100644 --- a/modules/session/db.go +++ b/modules/session/db.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package session diff --git a/modules/session/redis.go b/modules/session/redis.go index 334418bd7e..5fb59e4804 100644 --- a/modules/session/redis.go +++ b/modules/session/redis.go @@ -13,6 +13,7 @@ // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. +// SPDX-License-Identifier: Apache-2.0 package session diff --git a/modules/session/store.go b/modules/session/store.go index 8c5d7d82eb..7b0c550ace 100644 --- a/modules/session/store.go +++ b/modules/session/store.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package session diff --git a/modules/session/virtual.go b/modules/session/virtual.go index 928dd49740..fcbc44249d 100644 --- a/modules/session/virtual.go +++ b/modules/session/virtual.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package session diff --git a/modules/setting/attachment.go b/modules/setting/attachment.go index 474b73293c..68a2e87204 100644 --- a/modules/setting/attachment.go +++ b/modules/setting/attachment.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/cache.go b/modules/setting/cache.go index 9a44965124..2da79adb3b 100644 --- a/modules/setting/cache.go +++ b/modules/setting/cache.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/cors.go b/modules/setting/cors.go index a843194ff9..ae0736e830 100644 --- a/modules/setting/cors.go +++ b/modules/setting/cors.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting @@ -19,10 +18,12 @@ var CORSConfig = struct { Methods []string MaxAge time.Duration AllowCredentials bool + Headers []string XFrameOptions string }{ Enabled: false, MaxAge: 10 * time.Minute, + Headers: []string{"Content-Type", "User-Agent"}, XFrameOptions: "SAMEORIGIN", } diff --git a/modules/setting/cron.go b/modules/setting/cron.go index 9475887ecc..a76de2797f 100644 --- a/modules/setting/cron.go +++ b/modules/setting/cron.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/cron_test.go b/modules/setting/cron_test.go index cb397d81c4..29cdca8fbf 100644 --- a/modules/setting/cron_test.go +++ b/modules/setting/cron_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/database.go b/modules/setting/database.go index 4e55457395..5480f9dffd 100644 --- a/modules/setting/database.go +++ b/modules/setting/database.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting @@ -50,6 +49,7 @@ var ( MaxOpenConns int ConnMaxLifetime time.Duration IterateBufferSize int + AutoMigration bool }{ Timeout: 500, IterateBufferSize: 50, @@ -106,6 +106,7 @@ func InitDBConfig() { Database.LogSQL = sec.Key("LOG_SQL").MustBool(true) Database.DBConnectRetries = sec.Key("DB_RETRIES").MustInt(10) Database.DBConnectBackoff = sec.Key("DB_RETRY_BACKOFF").MustDuration(3 * time.Second) + Database.AutoMigration = sec.Key("AUTO_MIGRATION").MustBool(true) } // DBConnStr returns database connection string diff --git a/modules/setting/database_sqlite.go b/modules/setting/database_sqlite.go index 1f18868d8e..c1037cfb27 100644 --- a/modules/setting/database_sqlite.go +++ b/modules/setting/database_sqlite.go @@ -1,8 +1,7 @@ //go:build sqlite // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/database_test.go b/modules/setting/database_test.go index a90be2a687..481ca969b1 100644 --- a/modules/setting/database_test.go +++ b/modules/setting/database_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/directory.go b/modules/setting/directory.go index 2641510286..a80df47ab4 100644 --- a/modules/setting/directory.go +++ b/modules/setting/directory.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/federation.go b/modules/setting/federation.go index 89bbc1cf0b..0ff0614b0d 100644 --- a/modules/setting/federation.go +++ b/modules/setting/federation.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/git.go b/modules/setting/git.go index 266bbc3c5a..a05f77a97e 100644 --- a/modules/setting/git.go +++ b/modules/setting/git.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/i18n.go b/modules/setting/i18n.go index 8b8587e09b..0e67b18a3e 100644 --- a/modules/setting/i18n.go +++ b/modules/setting/i18n.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/indexer.go b/modules/setting/indexer.go index 46d4027d14..1b1c8f7e7f 100644 --- a/modules/setting/indexer.go +++ b/modules/setting/indexer.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/indexer_test.go b/modules/setting/indexer_test.go index 0ff1d814ab..8f0437be8a 100644 --- a/modules/setting/indexer_test.go +++ b/modules/setting/indexer_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/lfs.go b/modules/setting/lfs.go index 686b043657..6f8e875c1d 100644 --- a/modules/setting/lfs.go +++ b/modules/setting/lfs.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/log.go b/modules/setting/log.go index 1d9535360a..7372fc998d 100644 --- a/modules/setting/log.go +++ b/modules/setting/log.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/mailer.go b/modules/setting/mailer.go index d6f1dae0f7..7324328ee3 100644 --- a/modules/setting/mailer.go +++ b/modules/setting/mailer.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting @@ -18,32 +17,33 @@ import ( // Mailer represents mail service. type Mailer struct { // Mailer - Name string - From string - EnvelopeFrom string - OverrideEnvelopeFrom bool `ini:"-"` - FromName string - FromEmail string - SendAsPlainText bool - SubjectPrefix string + Name string `ini:"NAME"` + From string `ini:"FROM"` + EnvelopeFrom string `ini:"ENVELOPE_FROM"` + OverrideEnvelopeFrom bool `ini:"-"` + FromName string `ini:"-"` + FromEmail string `ini:"-"` + SendAsPlainText bool `ini:"SEND_AS_PLAIN_TEXT"` + SubjectPrefix string `ini:"SUBJECT_PREFIX"` // SMTP sender - Protocol string - SMTPAddr string - SMTPPort string - User, Passwd string - EnableHelo bool - HeloHostname string - ForceTrustServerCert bool - UseClientCert bool - ClientCertFile string - ClientKeyFile string + Protocol string `ini:"PROTOCOL"` + SMTPAddr string `ini:"SMTP_ADDR"` + SMTPPort string `ini:"SMTP_PORT"` + User string `ini:"USER"` + Passwd string `ini:"PASSWD"` + EnableHelo bool `ini:"ENABLE_HELO"` + HeloHostname string `ini:"HELO_HOSTNAME"` + ForceTrustServerCert bool `ini:"FORCE_TRUST_SERVER_CERT"` + UseClientCert bool `ini:"USE_CLIENT_CERT"` + ClientCertFile string `ini:"CLIENT_CERT_FILE"` + ClientKeyFile string `ini:"CLIENT_KEY_FILE"` // Sendmail sender - SendmailPath string - SendmailArgs []string - SendmailTimeout time.Duration - SendmailConvertCRLF bool + SendmailPath string `ini:"SENDMAIL_PATH"` + SendmailArgs []string `ini:"-"` + SendmailTimeout time.Duration `ini:"SENDMAIL_TIMEOUT"` + SendmailConvertCRLF bool `ini:"SENDMAIL_CONVERT_CRLF"` } // MailService the global mailer @@ -56,35 +56,12 @@ func newMailService() { return } - MailService = &Mailer{ - Name: sec.Key("NAME").MustString(AppName), - SendAsPlainText: sec.Key("SEND_AS_PLAIN_TEXT").MustBool(false), - - Protocol: sec.Key("PROTOCOL").In("", []string{"smtp", "smtps", "smtp+startls", "smtp+unix", "sendmail", "dummy"}), - SMTPAddr: sec.Key("SMTP_ADDR").String(), - SMTPPort: sec.Key("SMTP_PORT").String(), - User: sec.Key("USER").String(), - Passwd: sec.Key("PASSWD").String(), - EnableHelo: sec.Key("ENABLE_HELO").MustBool(true), - HeloHostname: sec.Key("HELO_HOSTNAME").String(), - ForceTrustServerCert: sec.Key("FORCE_TRUST_SERVER_CERT").MustBool(false), - UseClientCert: sec.Key("USE_CLIENT_CERT").MustBool(false), - ClientCertFile: sec.Key("CLIENT_CERT_FILE").String(), - ClientKeyFile: sec.Key("CLIENT_KEY_FILE").String(), - SubjectPrefix: sec.Key("SUBJECT_PREFIX").MustString(""), - - SendmailPath: sec.Key("SENDMAIL_PATH").MustString("sendmail"), - SendmailTimeout: sec.Key("SENDMAIL_TIMEOUT").MustDuration(5 * time.Minute), - SendmailConvertCRLF: sec.Key("SENDMAIL_CONVERT_CRLF").MustBool(true), - } - MailService.From = sec.Key("FROM").MustString(MailService.User) - MailService.EnvelopeFrom = sec.Key("ENVELOPE_FROM").MustString("") - + // Handle Deprecations and map on to new configuration // FIXME: DEPRECATED to be removed in v1.19.0 deprecatedSetting("mailer", "MAILER_TYPE", "mailer", "PROTOCOL") if sec.HasKey("MAILER_TYPE") && !sec.HasKey("PROTOCOL") { if sec.Key("MAILER_TYPE").String() == "sendmail" { - MailService.Protocol = "sendmail" + sec.Key("PROTOCOL").MustString("sendmail") } } @@ -96,31 +73,91 @@ func newMailService() { if err != nil { log.Fatal("Invalid mailer.HOST (%s): %v", givenHost, err) } - MailService.SMTPAddr = addr - MailService.SMTPPort = port + sec.Key("SMTP_ADDR").MustString(addr) + sec.Key("SMTP_PORT").MustString(port) } // FIXME: DEPRECATED to be removed in v1.19.0 deprecatedSetting("mailer", "IS_TLS_ENABLED", "mailer", "PROTOCOL") if sec.HasKey("IS_TLS_ENABLED") && !sec.HasKey("PROTOCOL") { if sec.Key("IS_TLS_ENABLED").MustBool() { - MailService.Protocol = "smtps" + sec.Key("PROTOCOL").MustString("smtps") } else { - MailService.Protocol = "smtp+startls" + sec.Key("PROTOCOL").MustString("smtp+starttls") } } + // FIXME: DEPRECATED to be removed in v1.19.0 + deprecatedSetting("mailer", "DISABLE_HELO", "mailer", "ENABLE_HELO") + if sec.HasKey("DISABLE_HELO") && !sec.HasKey("ENABLE_HELO") { + sec.Key("ENABLE_HELO").MustBool(!sec.Key("DISABLE_HELO").MustBool()) + } + + // FIXME: DEPRECATED to be removed in v1.19.0 + deprecatedSetting("mailer", "SKIP_VERIFY", "mailer", "FORCE_TRUST_SERVER_CERT") + if sec.HasKey("SKIP_VERIFY") && !sec.HasKey("FORCE_TRUST_SERVER_CERT") { + sec.Key("FORCE_TRUST_SERVER_CERT").MustBool(sec.Key("SKIP_VERIFY").MustBool()) + } + + // FIXME: DEPRECATED to be removed in v1.19.0 + deprecatedSetting("mailer", "USE_CERTIFICATE", "mailer", "USE_CLIENT_CERT") + if sec.HasKey("USE_CERTIFICATE") && !sec.HasKey("USE_CLIENT_CERT") { + sec.Key("USE_CLIENT_CERT").MustBool(sec.Key("USE_CERTIFICATE").MustBool()) + } + + // FIXME: DEPRECATED to be removed in v1.19.0 + deprecatedSetting("mailer", "CERT_FILE", "mailer", "CLIENT_CERT_FILE") + if sec.HasKey("CERT_FILE") && !sec.HasKey("CLIENT_CERT_FILE") { + sec.Key("CERT_FILE").MustString(sec.Key("CERT_FILE").String()) + } + + // FIXME: DEPRECATED to be removed in v1.19.0 + deprecatedSetting("mailer", "KEY_FILE", "mailer", "CLIENT_KEY_FILE") + if sec.HasKey("KEY_FILE") && !sec.HasKey("CLIENT_KEY_FILE") { + sec.Key("KEY_FILE").MustString(sec.Key("KEY_FILE").String()) + } + + // FIXME: DEPRECATED to be removed in v1.19.0 + deprecatedSetting("mailer", "ENABLE_HTML_ALTERNATIVE", "mailer", "SEND_AS_PLAIN_TEXT") + if sec.HasKey("ENABLE_HTML_ALTERNATIVE") && !sec.HasKey("SEND_AS_PLAIN_TEXT") { + sec.Key("SEND_AS_PLAIN_TEXT").MustBool(!sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(false)) + } + + if sec.HasKey("PROTOCOL") && sec.Key("PROTOCOL").String() == "smtp+startls" { + log.Error("Deprecated fallback `[mailer]` `PROTOCOL = smtp+startls` present. Use `[mailer]` `PROTOCOL = smtp+starttls`` instead. This fallback will be removed in v1.19.0") + sec.Key("PROTOCOL").SetValue("smtp+starttls") + } + + // Set default values & validate + sec.Key("NAME").MustString(AppName) + sec.Key("PROTOCOL").In("", []string{"smtp", "smtps", "smtp+starttls", "smtp+unix", "sendmail", "dummy"}) + sec.Key("ENABLE_HELO").MustBool(true) + sec.Key("FORCE_TRUST_SERVER_CERT").MustBool(false) + sec.Key("USE_CLIENT_CERT").MustBool(false) + sec.Key("SENDMAIL_PATH").MustString("sendmail") + sec.Key("SENDMAIL_TIMEOUT").MustDuration(5 * time.Minute) + sec.Key("SENDMAIL_CONVERT_CRLF").MustBool(true) + sec.Key("FROM").MustString(sec.Key("USER").String()) + + // Now map the values on to the MailService + MailService = &Mailer{} + if err := sec.MapTo(MailService); err != nil { + log.Fatal("Unable to map [mailer] section on to MailService. Error: %v", err) + } + + // Infer SMTPPort if not set if MailService.SMTPPort == "" { switch MailService.Protocol { case "smtp": MailService.SMTPPort = "25" case "smtps": MailService.SMTPPort = "465" - case "smtp+startls": + case "smtp+starttls": MailService.SMTPPort = "587" } } + // Infer Protocol if MailService.Protocol == "" { if strings.ContainsAny(MailService.SMTPAddr, "/\\") { MailService.Protocol = "smtp+unix" @@ -131,7 +168,7 @@ func newMailService() { case "465": MailService.Protocol = "smtps" case "587": - MailService.Protocol = "smtp+startls" + MailService.Protocol = "smtp+starttls" default: log.Error("unable to infer unspecified mailer.PROTOCOL from mailer.SMTP_PORT = %q, assume using smtps", MailService.SMTPPort) MailService.Protocol = "smtps" @@ -151,42 +188,6 @@ func newMailService() { } } - // FIXME: DEPRECATED to be removed in v1.19.0 - deprecatedSetting("mailer", "DISABLE_HELO", "mailer", "ENABLE_HELO") - if sec.HasKey("DISABLE_HELO") && !sec.HasKey("ENABLE_HELO") { - MailService.EnableHelo = !sec.Key("DISABLE_HELO").MustBool() - } - - // FIXME: DEPRECATED to be removed in v1.19.0 - deprecatedSetting("mailer", "SKIP_VERIFY", "mailer", "FORCE_TRUST_SERVER_CERT") - if sec.HasKey("SKIP_VERIFY") && !sec.HasKey("FORCE_TRUST_SERVER_CERT") { - MailService.ForceTrustServerCert = sec.Key("SKIP_VERIFY").MustBool() - } - - // FIXME: DEPRECATED to be removed in v1.19.0 - deprecatedSetting("mailer", "USE_CERTIFICATE", "mailer", "USE_CLIENT_CERT") - if sec.HasKey("USE_CERTIFICATE") && !sec.HasKey("USE_CLIENT_CERT") { - MailService.UseClientCert = sec.Key("USE_CLIENT_CERT").MustBool() - } - - // FIXME: DEPRECATED to be removed in v1.19.0 - deprecatedSetting("mailer", "CERT_FILE", "mailer", "CLIENT_CERT_FILE") - if sec.HasKey("CERT_FILE") && !sec.HasKey("CLIENT_CERT_FILE") { - MailService.ClientCertFile = sec.Key("CERT_FILE").String() - } - - // FIXME: DEPRECATED to be removed in v1.19.0 - deprecatedSetting("mailer", "KEY_FILE", "mailer", "CLIENT_KEY_FILE") - if sec.HasKey("KEY_FILE") && !sec.HasKey("CLIENT_KEY_FILE") { - MailService.ClientKeyFile = sec.Key("KEY_FILE").String() - } - - // FIXME: DEPRECATED to be removed in v1.19.0 - deprecatedSetting("mailer", "ENABLE_HTML_ALTERNATIVE", "mailer", "SEND_AS_PLAIN_TEXT") - if sec.HasKey("ENABLE_HTML_ALTERNATIVE") && !sec.HasKey("SEND_AS_PLAIN_TEXT") { - MailService.SendAsPlainText = !sec.Key("ENABLE_HTML_ALTERNATIVE").MustBool(false) - } - if MailService.From != "" { parsed, err := mail.ParseAddress(MailService.From) if err != nil { diff --git a/modules/setting/markup.go b/modules/setting/markup.go index fd41bdd7cc..c262234b6a 100644 --- a/modules/setting/markup.go +++ b/modules/setting/markup.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/migrations.go b/modules/setting/migrations.go index 4b10f3dc6e..2f6d08b6b8 100644 --- a/modules/setting/migrations.go +++ b/modules/setting/migrations.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/mime_type_map.go b/modules/setting/mime_type_map.go index 8e5b864e24..6a0847bd7e 100644 --- a/modules/setting/mime_type_map.go +++ b/modules/setting/mime_type_map.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/mirror.go b/modules/setting/mirror.go index 2bd0322d06..9ddce97daf 100644 --- a/modules/setting/mirror.go +++ b/modules/setting/mirror.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/oauth2_client.go b/modules/setting/oauth2_client.go index 6cfd99156f..6492af82d2 100644 --- a/modules/setting/oauth2_client.go +++ b/modules/setting/oauth2_client.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/packages.go b/modules/setting/packages.go index 5e0f2a3b03..120fbb5bda 100644 --- a/modules/setting/packages.go +++ b/modules/setting/packages.go @@ -1,15 +1,18 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package setting import ( + "math" "net/url" "os" "path/filepath" "code.gitea.io/gitea/modules/log" + + "github.com/dustin/go-humanize" + ini "gopkg.in/ini.v1" ) // Package registry settings @@ -19,8 +22,24 @@ var ( Enabled bool ChunkedUploadPath string RegistryHost string + + LimitTotalOwnerCount int64 + LimitTotalOwnerSize int64 + LimitSizeComposer int64 + LimitSizeConan int64 + LimitSizeContainer int64 + LimitSizeGeneric int64 + LimitSizeHelm int64 + LimitSizeMaven int64 + LimitSizeNpm int64 + LimitSizeNuGet int64 + LimitSizePub int64 + LimitSizePyPI int64 + LimitSizeRubyGems int64 + LimitSizeVagrant int64 }{ - Enabled: true, + Enabled: true, + LimitTotalOwnerCount: -1, } ) @@ -43,4 +62,32 @@ func newPackages() { if err := os.MkdirAll(Packages.ChunkedUploadPath, os.ModePerm); err != nil { log.Error("Unable to create chunked upload directory: %s (%v)", Packages.ChunkedUploadPath, err) } + + Packages.LimitTotalOwnerSize = mustBytes(sec, "LIMIT_TOTAL_OWNER_SIZE") + Packages.LimitSizeComposer = mustBytes(sec, "LIMIT_SIZE_COMPOSER") + Packages.LimitSizeConan = mustBytes(sec, "LIMIT_SIZE_CONAN") + Packages.LimitSizeContainer = mustBytes(sec, "LIMIT_SIZE_CONTAINER") + Packages.LimitSizeGeneric = mustBytes(sec, "LIMIT_SIZE_GENERIC") + Packages.LimitSizeHelm = mustBytes(sec, "LIMIT_SIZE_HELM") + Packages.LimitSizeMaven = mustBytes(sec, "LIMIT_SIZE_MAVEN") + Packages.LimitSizeNpm = mustBytes(sec, "LIMIT_SIZE_NPM") + Packages.LimitSizeNuGet = mustBytes(sec, "LIMIT_SIZE_NUGET") + Packages.LimitSizePub = mustBytes(sec, "LIMIT_SIZE_PUB") + Packages.LimitSizePyPI = mustBytes(sec, "LIMIT_SIZE_PYPI") + Packages.LimitSizeRubyGems = mustBytes(sec, "LIMIT_SIZE_RUBYGEMS") + Packages.LimitSizeVagrant = mustBytes(sec, "LIMIT_SIZE_VAGRANT") +} + +func mustBytes(section *ini.Section, key string) int64 { + const noLimit = "-1" + + value := section.Key(key).MustString(noLimit) + if value == noLimit { + return -1 + } + bytes, err := humanize.ParseBytes(value) + if err != nil || bytes > math.MaxInt64 { + return -1 + } + return int64(bytes) } diff --git a/modules/setting/packages_test.go b/modules/setting/packages_test.go new file mode 100644 index 0000000000..04d6e55834 --- /dev/null +++ b/modules/setting/packages_test.go @@ -0,0 +1,30 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package setting + +import ( + "testing" + + "github.com/stretchr/testify/assert" + ini "gopkg.in/ini.v1" +) + +func TestMustBytes(t *testing.T) { + test := func(value string) int64 { + sec, _ := ini.Empty().NewSection("test") + sec.NewKey("VALUE", value) + + return mustBytes(sec, "VALUE") + } + + assert.EqualValues(t, -1, test("")) + assert.EqualValues(t, -1, test("-1")) + assert.EqualValues(t, 0, test("0")) + assert.EqualValues(t, 1, test("1")) + assert.EqualValues(t, 10000, test("10000")) + assert.EqualValues(t, 1000000, test("1 mb")) + assert.EqualValues(t, 1048576, test("1mib")) + assert.EqualValues(t, 1782579, test("1.7mib")) + assert.EqualValues(t, -1, test("1 yib")) // too large +} diff --git a/modules/setting/picture.go b/modules/setting/picture.go index af9041ade3..9d16a2360b 100644 --- a/modules/setting/picture.go +++ b/modules/setting/picture.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/project.go b/modules/setting/project.go index 56505b0ca4..53e09e8dad 100644 --- a/modules/setting/project.go +++ b/modules/setting/project.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/proxy.go b/modules/setting/proxy.go index 53fb0066d9..fed33395ed 100644 --- a/modules/setting/proxy.go +++ b/modules/setting/proxy.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/queue.go b/modules/setting/queue.go index d3bb33b248..a67d0d849a 100644 --- a/modules/setting/queue.go +++ b/modules/setting/queue.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/repository.go b/modules/setting/repository.go index d0406dbf90..19594369be 100644 --- a/modules/setting/repository.go +++ b/modules/setting/repository.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/service.go b/modules/setting/service.go index 10e3899950..7b4bfc5c7b 100644 --- a/modules/setting/service.go +++ b/modules/setting/service.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting @@ -40,6 +39,7 @@ var Service = struct { EnableReverseProxyEmail bool EnableReverseProxyFullName bool EnableCaptcha bool + RequireCaptchaForLogin bool RequireExternalRegistrationCaptcha bool RequireExternalRegistrationPassword bool CaptchaType string @@ -130,6 +130,7 @@ func newService() { Service.EnableReverseProxyEmail = sec.Key("ENABLE_REVERSE_PROXY_EMAIL").MustBool() Service.EnableReverseProxyFullName = sec.Key("ENABLE_REVERSE_PROXY_FULL_NAME").MustBool() Service.EnableCaptcha = sec.Key("ENABLE_CAPTCHA").MustBool(false) + Service.RequireCaptchaForLogin = sec.Key("REQUIRE_CAPTCHA_FOR_LOGIN").MustBool(false) Service.RequireExternalRegistrationCaptcha = sec.Key("REQUIRE_EXTERNAL_REGISTRATION_CAPTCHA").MustBool(Service.EnableCaptcha) Service.RequireExternalRegistrationPassword = sec.Key("REQUIRE_EXTERNAL_REGISTRATION_PASSWORD").MustBool() Service.CaptchaType = sec.Key("CAPTCHA_TYPE").MustString(ImageCaptcha) diff --git a/modules/setting/session.go b/modules/setting/session.go index 62ca1d82e8..082538c385 100644 --- a/modules/setting/session.go +++ b/modules/setting/session.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/setting.go b/modules/setting/setting.go index 2e5bb17b6a..47e0ae2cda 100644 --- a/modules/setting/setting.go +++ b/modules/setting/setting.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2017 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. +// SPDX-License-Identifier: MIT package setting @@ -88,10 +87,10 @@ var ( // AppWorkPath is used as the base path for several other paths. AppWorkPath string // AppDataPath is the default path for storing data. - // It maps to ini:"APP_DATA_PATH" and defaults to AppWorkPath + "/data" + // It maps to ini:"APP_DATA_PATH" in [server] and defaults to AppWorkPath + "/data" AppDataPath string // LocalURL is the url for locally running applications to contact Gitea. It always has a '/' suffix - // It maps to ini:"LOCAL_ROOT_URL" + // It maps to ini:"LOCAL_ROOT_URL" in [server] LocalURL string // AssetVersion holds a opaque value that is used for cache-busting assets AssetVersion string @@ -440,6 +439,7 @@ var ( ShowFooterBranding bool ShowFooterVersion bool ShowFooterTemplateLoadTime bool + EnableFeed bool // Global setting objects Cfg *ini.File @@ -465,6 +465,13 @@ func getAppPath() (string, error) { appPath, err = exec.LookPath(os.Args[0]) } + if err != nil { + // FIXME: Once we switch to go 1.19 use !errors.Is(err, exec.ErrDot) + if !strings.Contains(err.Error(), "cannot run executable found relative to current directory") { + return "", err + } + appPath, err = filepath.Abs(os.Args[0]) + } if err != nil { return "", err } @@ -604,7 +611,7 @@ 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) + log.Error("Deprecated fallback `[%s]` `%s` present. Use `[%s]` `%s` instead. This fallback will be removed in v1.19.0", oldSection, oldKey, newSection, newKey) } } @@ -748,19 +755,22 @@ func loadFromConf(allowEmpty bool, extraConfig string) { PerWriteTimeout = sec.Key("PER_WRITE_TIMEOUT").MustDuration(PerWriteTimeout) PerWritePerKbTimeout = sec.Key("PER_WRITE_PER_KB_TIMEOUT").MustDuration(PerWritePerKbTimeout) - defaultAppURL := string(Protocol) + "://" + Domain - if (Protocol == HTTP && HTTPPort != "80") || (Protocol == HTTPS && HTTPPort != "443") { - defaultAppURL += ":" + HTTPPort - } - AppURL = sec.Key("ROOT_URL").MustString(defaultAppURL + "/") - // This should be TrimRight to ensure that there is only a single '/' at the end of AppURL. - AppURL = strings.TrimRight(AppURL, "/") + "/" + defaultAppURL := string(Protocol) + "://" + Domain + ":" + HTTPPort + AppURL = sec.Key("ROOT_URL").MustString(defaultAppURL) - // Check if has app suburl. + // Check validity of AppURL appURL, err := url.Parse(AppURL) if err != nil { log.Fatal("Invalid ROOT_URL '%s': %s", AppURL, err) } + // Remove default ports from AppURL. + // (scheme-based URL normalization, RFC 3986 section 6.2.3) + if (appURL.Scheme == string(HTTP) && appURL.Port() == "80") || (appURL.Scheme == string(HTTPS) && appURL.Port() == "443") { + appURL.Host = appURL.Hostname() + } + // This should be TrimRight to ensure that there is only a single '/' at the end of AppURL. + AppURL = strings.TrimRight(appURL.String(), "/") + "/" + // Suburl should start with '/' and end without '/', such as '/{subpath}'. // This value is empty if site does not have sub-url. AppSubURL = strings.TrimSuffix(appURL.Path, "/") @@ -938,7 +948,7 @@ func loadFromConf(allowEmpty bool, extraConfig string) { if SecretKey == "" { // FIXME: https://github.com/go-gitea/gitea/issues/16832 // Until it supports rotating an existing secret key, we shouldn't move users off of the widely used default value - SecretKey = "!#@FDEWREWR&*(" // nolint:gosec + SecretKey = "!#@FDEWREWR&*(" //nolint:gosec } CookieRememberName = sec.Key("COOKIE_REMEMBER_NAME").MustString("gitea_incredible") @@ -1102,6 +1112,7 @@ func loadFromConf(allowEmpty bool, extraConfig string) { ShowFooterVersion = Cfg.Section("other").Key("SHOW_FOOTER_VERSION").MustBool(true) ShowFooterTemplateLoadTime = Cfg.Section("other").Key("SHOW_FOOTER_TEMPLATE_LOAD_TIME").MustBool(true) EnableSitemap = Cfg.Section("other").Key("ENABLE_SITEMAP").MustBool(true) + EnableFeed = Cfg.Section("other").Key("ENABLE_FEED").MustBool(true) UI.ShowUserEmail = Cfg.Section("ui").Key("SHOW_USER_EMAIL").MustBool(true) UI.DefaultShowFullName = Cfg.Section("ui").Key("DEFAULT_SHOW_FULL_NAME").MustBool(false) diff --git a/modules/setting/setting_test.go b/modules/setting/setting_test.go index 0e7f5a55ab..f77ee65974 100644 --- a/modules/setting/setting_test.go +++ b/modules/setting/setting_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/storage.go b/modules/setting/storage.go index 075152db59..32f74aa072 100644 --- a/modules/setting/storage.go +++ b/modules/setting/storage.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/storage_test.go b/modules/setting/storage_test.go index ffd8b7aa01..256bbb7a52 100644 --- a/modules/setting/storage_test.go +++ b/modules/setting/storage_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/task.go b/modules/setting/task.go index c39d441108..cfb0f54668 100644 --- a/modules/setting/task.go +++ b/modules/setting/task.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/setting/webhook.go b/modules/setting/webhook.go index 0bfd7dcb4d..51e36c3419 100644 --- a/modules/setting/webhook.go +++ b/modules/setting/webhook.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/modules/sitemap/sitemap.go b/modules/sitemap/sitemap.go index 14953765ab..ceb65c1c8d 100644 --- a/modules/sitemap/sitemap.go +++ b/modules/sitemap/sitemap.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package sitemap diff --git a/modules/sitemap/sitemap_test.go b/modules/sitemap/sitemap_test.go index 63007b8479..ab879b272e 100644 --- a/modules/sitemap/sitemap_test.go +++ b/modules/sitemap/sitemap_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package sitemap diff --git a/modules/ssh/init.go b/modules/ssh/init.go index 72cb6df7a4..21d4f89936 100644 --- a/modules/ssh/init.go +++ b/modules/ssh/init.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package ssh diff --git a/modules/ssh/ssh.go b/modules/ssh/ssh.go index 6b601c008f..9ec14f2caa 100644 --- a/modules/ssh/ssh.go +++ b/modules/ssh/ssh.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package ssh diff --git a/modules/ssh/ssh_graceful.go b/modules/ssh/ssh_graceful.go index 166ea0b982..cad2c685bd 100644 --- a/modules/ssh/ssh_graceful.go +++ b/modules/ssh/ssh_graceful.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package ssh diff --git a/modules/storage/helper.go b/modules/storage/helper.go index 1a25716ccb..1ab99d98b3 100644 --- a/modules/storage/helper.go +++ b/modules/storage/helper.go @@ -1,10 +1,13 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package storage import ( + "fmt" + "io" + "net/url" + "os" "reflect" "code.gitea.io/gitea/modules/json" @@ -62,3 +65,31 @@ func toConfig(exemplar, cfg interface{}) (interface{}, error) { } return newVal.Elem().Interface(), nil } + +var uninitializedStorage = discardStorage("uninitialized storage") + +type discardStorage string + +func (s discardStorage) Open(_ string) (Object, error) { + return nil, fmt.Errorf("%s", s) +} + +func (s discardStorage) Save(_ string, _ io.Reader, _ int64) (int64, error) { + return 0, fmt.Errorf("%s", s) +} + +func (s discardStorage) Stat(_ string) (os.FileInfo, error) { + return nil, fmt.Errorf("%s", s) +} + +func (s discardStorage) Delete(_ string) error { + return fmt.Errorf("%s", s) +} + +func (s discardStorage) URL(_, _ string) (*url.URL, error) { + return nil, fmt.Errorf("%s", s) +} + +func (s discardStorage) IterateObjects(_ func(string, Object) error) error { + return fmt.Errorf("%s", s) +} diff --git a/modules/storage/helper_test.go b/modules/storage/helper_test.go new file mode 100644 index 0000000000..7d74671c54 --- /dev/null +++ b/modules/storage/helper_test.go @@ -0,0 +1,50 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package storage + +import ( + "bytes" + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_discardStorage(t *testing.T) { + tests := []discardStorage{ + uninitializedStorage, + discardStorage("empty"), + } + for _, tt := range tests { + t.Run(string(tt), func(t *testing.T) { + { + got, err := tt.Open("path") + assert.Nil(t, got) + assert.Error(t, err, string(tt)) + } + { + got, err := tt.Save("path", bytes.NewReader([]byte{0}), 1) + assert.Equal(t, int64(0), got) + assert.Error(t, err, string(tt)) + } + { + got, err := tt.Stat("path") + assert.Nil(t, got) + assert.Error(t, err, string(tt)) + } + { + err := tt.Delete("path") + assert.Error(t, err, string(tt)) + } + { + got, err := tt.URL("path", "name") + assert.Nil(t, got) + assert.Errorf(t, err, string(tt)) + } + { + err := tt.IterateObjects(func(_ string, _ Object) error { return nil }) + assert.Error(t, err, string(tt)) + } + }) + } +} diff --git a/modules/storage/local.go b/modules/storage/local.go index 5d5b06b648..a439a24592 100644 --- a/modules/storage/local.go +++ b/modules/storage/local.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package storage diff --git a/modules/storage/local_test.go b/modules/storage/local_test.go index 0749036cb7..994c54e859 100644 --- a/modules/storage/local_test.go +++ b/modules/storage/local_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package storage diff --git a/modules/storage/minio.go b/modules/storage/minio.go index f7b42d674c..912f820ede 100644 --- a/modules/storage/minio.go +++ b/modules/storage/minio.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package storage diff --git a/modules/storage/storage.go b/modules/storage/storage.go index 1b83e3271f..671e0ce565 100644 --- a/modules/storage/storage.go +++ b/modules/storage/storage.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package storage @@ -111,46 +110,38 @@ func SaveFrom(objStorage ObjectStorage, p string, callback func(w io.Writer) err var ( // Attachments represents attachments storage - Attachments ObjectStorage + Attachments ObjectStorage = uninitializedStorage // LFS represents lfs storage - LFS ObjectStorage + LFS ObjectStorage = uninitializedStorage // Avatars represents user avatars storage - Avatars ObjectStorage + Avatars ObjectStorage = uninitializedStorage // RepoAvatars represents repository avatars storage - RepoAvatars ObjectStorage + RepoAvatars ObjectStorage = uninitializedStorage // RepoArchives represents repository archives storage - RepoArchives ObjectStorage + RepoArchives ObjectStorage = uninitializedStorage // Packages represents packages storage - Packages ObjectStorage + Packages ObjectStorage = uninitializedStorage ) // Init init the stoarge func Init() error { - if err := initAttachments(); err != nil { - return err + for _, f := range []func() error{ + initAttachments, + initAvatars, + initRepoAvatars, + initLFS, + initRepoArchives, + initPackages, + } { + if err := f(); err != nil { + return err + } } - - if err := initAvatars(); err != nil { - return err - } - - if err := initRepoAvatars(); err != nil { - return err - } - - if err := initLFS(); err != nil { - return err - } - - if err := initRepoArchives(); err != nil { - return err - } - - return initPackages() + return nil } // NewStorage takes a storage type and some config and returns an ObjectStorage or an error @@ -173,12 +164,20 @@ func initAvatars() (err error) { } func initAttachments() (err error) { + if !setting.Attachment.Enabled { + Attachments = discardStorage("Attachment isn't enabled") + return nil + } log.Info("Initialising Attachment storage with type: %s", setting.Attachment.Storage.Type) Attachments, err = NewStorage(setting.Attachment.Storage.Type, &setting.Attachment.Storage) return err } func initLFS() (err error) { + if !setting.LFS.StartServer { + LFS = discardStorage("LFS isn't enabled") + return nil + } log.Info("Initialising LFS storage with type: %s", setting.LFS.Storage.Type) LFS, err = NewStorage(setting.LFS.Storage.Type, &setting.LFS.Storage) return err @@ -197,6 +196,10 @@ func initRepoArchives() (err error) { } func initPackages() (err error) { + if !setting.Packages.Enabled { + Packages = discardStorage("Packages isn't enabled") + return nil + } log.Info("Initialising Packages storage with type: %s", setting.Packages.Storage.Type) Packages, err = NewStorage(setting.Packages.Storage.Type, &setting.Packages.Storage) return err diff --git a/modules/structs/activitypub.go b/modules/structs/activitypub.go index 86681bf9d7..117eb0bed2 100644 --- a/modules/structs/activitypub.go +++ b/modules/structs/activitypub.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/admin_user.go b/modules/structs/admin_user.go index 2f6f502af6..0739653eea 100644 --- a/modules/structs/admin_user.go +++ b/modules/structs/admin_user.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/attachment.go b/modules/structs/attachment.go index 7becd94335..38beca5e99 100644 --- a/modules/structs/attachment.go +++ b/modules/structs/attachment.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package structs // import "code.gitea.io/gitea/modules/structs" diff --git a/modules/structs/commit_status.go b/modules/structs/commit_status.go index 23e0c383b8..dfde79190c 100644 --- a/modules/structs/commit_status.go +++ b/modules/structs/commit_status.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/cron.go b/modules/structs/cron.go index f52a5ed3c9..39c6a06a42 100644 --- a/modules/structs/cron.go +++ b/modules/structs/cron.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/doc.go b/modules/structs/doc.go index 4c2fdbf73d..0db0a25fd4 100644 --- a/modules/structs/doc.go +++ b/modules/structs/doc.go @@ -1,5 +1,4 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/fork.go b/modules/structs/fork.go index 21afd636c7..eb7774afbc 100644 --- a/modules/structs/fork.go +++ b/modules/structs/fork.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/git_blob.go b/modules/structs/git_blob.go index 5715f2585b..96c7a271a9 100644 --- a/modules/structs/git_blob.go +++ b/modules/structs/git_blob.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/git_hook.go b/modules/structs/git_hook.go index 8a36b0b266..20230250ec 100644 --- a/modules/structs/git_hook.go +++ b/modules/structs/git_hook.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/hook.go b/modules/structs/hook.go index f0600a192d..b722e32ca0 100644 --- a/modules/structs/hook.go +++ b/modules/structs/hook.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2017 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/issue.go b/modules/structs/issue.go index 70f5e1ba8e..48e4e0e7e3 100644 --- a/modules/structs/issue.go +++ b/modules/structs/issue.go @@ -1,12 +1,15 @@ // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs import ( - "path/filepath" + "fmt" + "path" + "strings" "time" + + "gopkg.in/yaml.v3" ) // StateType issue state type @@ -38,18 +41,19 @@ type RepositoryMeta struct { // Issue represents an issue in a repository // swagger:model type Issue struct { - ID int64 `json:"id"` - URL string `json:"url"` - HTMLURL string `json:"html_url"` - Index int64 `json:"number"` - Poster *User `json:"user"` - OriginalAuthor string `json:"original_author"` - OriginalAuthorID int64 `json:"original_author_id"` - Title string `json:"title"` - Body string `json:"body"` - Ref string `json:"ref"` - Labels []*Label `json:"labels"` - Milestone *Milestone `json:"milestone"` + ID int64 `json:"id"` + URL string `json:"url"` + HTMLURL string `json:"html_url"` + Index int64 `json:"number"` + Poster *User `json:"user"` + OriginalAuthor string `json:"original_author"` + OriginalAuthorID int64 `json:"original_author_id"` + Title string `json:"title"` + Body string `json:"body"` + Ref string `json:"ref"` + Attachments []*Attachment `json:"assets"` + Labels []*Label `json:"labels"` + Milestone *Milestone `json:"milestone"` // deprecated Assignee *User `json:"assignee"` Assignees []*User `json:"assignees"` @@ -143,14 +147,47 @@ type IssueFormField struct { // IssueTemplate represents an issue template for a repository // swagger:model type IssueTemplate struct { - Name string `json:"name" yaml:"name"` - Title string `json:"title" yaml:"title"` - About string `json:"about" yaml:"about"` // Using "description" in a template file is compatible - Labels []string `json:"labels" yaml:"labels"` - Ref string `json:"ref" yaml:"ref"` - Content string `json:"content" yaml:"-"` - Fields []*IssueFormField `json:"body" yaml:"body"` - FileName string `json:"file_name" yaml:"-"` + Name string `json:"name" yaml:"name"` + Title string `json:"title" yaml:"title"` + About string `json:"about" yaml:"about"` // Using "description" in a template file is compatible + Labels IssueTemplateLabels `json:"labels" yaml:"labels"` + Ref string `json:"ref" yaml:"ref"` + Content string `json:"content" yaml:"-"` + Fields []*IssueFormField `json:"body" yaml:"body"` + FileName string `json:"file_name" yaml:"-"` +} + +type IssueTemplateLabels []string + +func (l *IssueTemplateLabels) UnmarshalYAML(value *yaml.Node) error { + var labels []string + if value.IsZero() { + *l = labels + return nil + } + switch value.Kind { + case yaml.ScalarNode: + str := "" + err := value.Decode(&str) + if err != nil { + return err + } + for _, v := range strings.Split(str, ",") { + if v = strings.TrimSpace(v); v == "" { + continue + } + labels = append(labels, v) + } + *l = labels + return nil + case yaml.SequenceNode: + if err := value.Decode(&labels); err != nil { + return err + } + *l = labels + return nil + } + return fmt.Errorf("line %d: cannot unmarshal %s into IssueTemplateLabels", value.Line, value.ShortTag()) } // IssueTemplateType defines issue template type @@ -163,11 +200,11 @@ const ( // Type returns the type of IssueTemplate, can be "md", "yaml" or empty for known func (it IssueTemplate) Type() IssueTemplateType { - if it.Name == "config.yaml" || it.Name == "config.yml" { + if base := path.Base(it.FileName); base == "config.yaml" || base == "config.yml" { // ignore config.yaml which is a special configuration file return "" } - if ext := filepath.Ext(it.FileName); ext == ".md" { + if ext := path.Ext(it.FileName); ext == ".md" { return IssueTemplateTypeMarkdown } else if ext == ".yaml" || ext == ".yml" { return IssueTemplateTypeYaml diff --git a/modules/structs/issue_comment.go b/modules/structs/issue_comment.go index e13ec05d01..9e8f5c4bf3 100644 --- a/modules/structs/issue_comment.go +++ b/modules/structs/issue_comment.go @@ -1,6 +1,5 @@ // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs @@ -10,14 +9,15 @@ import ( // Comment represents a comment on a commit or issue type Comment struct { - ID int64 `json:"id"` - HTMLURL string `json:"html_url"` - PRURL string `json:"pull_request_url"` - IssueURL string `json:"issue_url"` - Poster *User `json:"user"` - OriginalAuthor string `json:"original_author"` - OriginalAuthorID int64 `json:"original_author_id"` - Body string `json:"body"` + ID int64 `json:"id"` + HTMLURL string `json:"html_url"` + PRURL string `json:"pull_request_url"` + IssueURL string `json:"issue_url"` + Poster *User `json:"user"` + OriginalAuthor string `json:"original_author"` + OriginalAuthorID int64 `json:"original_author_id"` + Body string `json:"body"` + Attachments []*Attachment `json:"assets"` // swagger:strfmt date-time Created time.Time `json:"created_at"` // swagger:strfmt date-time diff --git a/modules/structs/issue_label.go b/modules/structs/issue_label.go index 2aadd8638e..5c622797f4 100644 --- a/modules/structs/issue_label.go +++ b/modules/structs/issue_label.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/issue_milestone.go b/modules/structs/issue_milestone.go index ace783ebbc..a840cf1820 100644 --- a/modules/structs/issue_milestone.go +++ b/modules/structs/issue_milestone.go @@ -1,6 +1,5 @@ // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/issue_reaction.go b/modules/structs/issue_reaction.go index 56408313ee..8d907a47e5 100644 --- a/modules/structs/issue_reaction.go +++ b/modules/structs/issue_reaction.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/issue_stopwatch.go b/modules/structs/issue_stopwatch.go index 15d17cdda7..ceade1ddd2 100644 --- a/modules/structs/issue_stopwatch.go +++ b/modules/structs/issue_stopwatch.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/issue_test.go b/modules/structs/issue_test.go new file mode 100644 index 0000000000..fa7a20db8b --- /dev/null +++ b/modules/structs/issue_test.go @@ -0,0 +1,105 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package structs + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "gopkg.in/yaml.v3" +) + +func TestIssueTemplate_Type(t *testing.T) { + tests := []struct { + fileName string + want IssueTemplateType + }{ + { + fileName: ".gitea/ISSUE_TEMPLATE/bug_report.yaml", + want: IssueTemplateTypeYaml, + }, + { + fileName: ".gitea/ISSUE_TEMPLATE/bug_report.md", + want: IssueTemplateTypeMarkdown, + }, + { + fileName: ".gitea/ISSUE_TEMPLATE/bug_report.txt", + want: "", + }, + { + fileName: ".gitea/ISSUE_TEMPLATE/config.yaml", + want: "", + }, + } + for _, tt := range tests { + t.Run(tt.fileName, func(t *testing.T) { + it := IssueTemplate{ + FileName: tt.fileName, + } + assert.Equal(t, tt.want, it.Type()) + }) + } +} + +func TestIssueTemplateLabels_UnmarshalYAML(t *testing.T) { + tests := []struct { + name string + content string + tmpl *IssueTemplate + want *IssueTemplate + wantErr string + }{ + { + name: "array", + content: `labels: ["a", "b", "c"]`, + tmpl: &IssueTemplate{ + Labels: []string{"should_be_overwrote"}, + }, + want: &IssueTemplate{ + Labels: []string{"a", "b", "c"}, + }, + }, + { + name: "string", + content: `labels: "a,b,c"`, + tmpl: &IssueTemplate{ + Labels: []string{"should_be_overwrote"}, + }, + want: &IssueTemplate{ + Labels: []string{"a", "b", "c"}, + }, + }, + { + name: "empty", + content: `labels:`, + tmpl: &IssueTemplate{ + Labels: []string{"should_be_overwrote"}, + }, + want: &IssueTemplate{ + Labels: nil, + }, + }, + { + name: "error", + content: ` +labels: + a: aa + b: bb +`, + tmpl: &IssueTemplate{}, + wantErr: "line 3: cannot unmarshal !!map into IssueTemplateLabels", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := yaml.Unmarshal([]byte(tt.content), tt.tmpl) + if tt.wantErr != "" { + assert.EqualError(t, err, tt.wantErr) + } else { + assert.NoError(t, err) + assert.Equal(t, tt.want, tt.tmpl) + } + }) + } +} diff --git a/modules/structs/issue_tracked_time.go b/modules/structs/issue_tracked_time.go index 7e150687ef..a3904af80e 100644 --- a/modules/structs/issue_tracked_time.go +++ b/modules/structs/issue_tracked_time.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/lfs_lock.go b/modules/structs/lfs_lock.go index 3709106315..6b4c0bc111 100644 --- a/modules/structs/lfs_lock.go +++ b/modules/structs/lfs_lock.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/mirror.go b/modules/structs/mirror.go index 8e8a8a2705..21e7751f76 100644 --- a/modules/structs/mirror.go +++ b/modules/structs/mirror.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/miscellaneous.go b/modules/structs/miscellaneous.go index c21c466cb0..596a551e0d 100644 --- a/modules/structs/miscellaneous.go +++ b/modules/structs/miscellaneous.go @@ -1,6 +1,5 @@ // Copyright 2015 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/nodeinfo.go b/modules/structs/nodeinfo.go index 6fd1eb624a..802c8d3e57 100644 --- a/modules/structs/nodeinfo.go +++ b/modules/structs/nodeinfo.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/notifications.go b/modules/structs/notifications.go index 3fd9088ce3..7fbf4cb46d 100644 --- a/modules/structs/notifications.go +++ b/modules/structs/notifications.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/org.go b/modules/structs/org.go index 1e98c59ba4..b4c58623fd 100644 --- a/modules/structs/org.go +++ b/modules/structs/org.go @@ -1,6 +1,5 @@ // Copyright 2015 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/org_member.go b/modules/structs/org_member.go index 3b2a8b599a..2df5099de9 100644 --- a/modules/structs/org_member.go +++ b/modules/structs/org_member.go @@ -1,6 +1,5 @@ // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/org_team.go b/modules/structs/org_team.go index 10bd9e62ce..95db0debad 100644 --- a/modules/structs/org_team.go +++ b/modules/structs/org_team.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/org_type.go b/modules/structs/org_type.go index 4401a2801c..69f323fa99 100644 --- a/modules/structs/org_type.go +++ b/modules/structs/org_type.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/package.go b/modules/structs/package.go index fbdd6c90aa..0059535bea 100644 --- a/modules/structs/package.go +++ b/modules/structs/package.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/pull.go b/modules/structs/pull.go index f627241b26..f64bb83af9 100644 --- a/modules/structs/pull.go +++ b/modules/structs/pull.go @@ -1,6 +1,5 @@ // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/pull_review.go b/modules/structs/pull_review.go index 7c9360a0c2..810be8f521 100644 --- a/modules/structs/pull_review.go +++ b/modules/structs/pull_review.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package structs @@ -40,6 +39,8 @@ type PullReview struct { CodeCommentsCount int `json:"comments_count"` // swagger:strfmt date-time Submitted time.Time `json:"submitted_at"` + // swagger:strfmt date-time + Updated time.Time `json:"updated_at"` HTMLURL string `json:"html_url"` HTMLPullURL string `json:"pull_request_url"` diff --git a/modules/structs/release.go b/modules/structs/release.go index 38ce60bbe2..3fe40389b1 100644 --- a/modules/structs/release.go +++ b/modules/structs/release.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/repo.go b/modules/structs/repo.go index cf6601704e..16f3d9dd26 100644 --- a/modules/structs/repo.go +++ b/modules/structs/repo.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/repo_branch.go b/modules/structs/repo_branch.go index 1f3bc04e86..864cb8f50a 100644 --- a/modules/structs/repo_branch.go +++ b/modules/structs/repo_branch.go @@ -1,6 +1,5 @@ // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/repo_collaborator.go b/modules/structs/repo_collaborator.go index 2f9c8992a1..946a6ec7e7 100644 --- a/modules/structs/repo_collaborator.go +++ b/modules/structs/repo_collaborator.go @@ -1,6 +1,5 @@ // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/repo_commit.go b/modules/structs/repo_commit.go index 55a516a975..b3e98df195 100644 --- a/modules/structs/repo_commit.go +++ b/modules/structs/repo_commit.go @@ -1,7 +1,6 @@ // Copyright 2018 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/repo_file.go b/modules/structs/repo_file.go index ce1a9fe4be..328d7e47c8 100644 --- a/modules/structs/repo_file.go +++ b/modules/structs/repo_file.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/repo_key.go b/modules/structs/repo_key.go index 29928bd97e..27b9d05a75 100644 --- a/modules/structs/repo_key.go +++ b/modules/structs/repo_key.go @@ -1,6 +1,5 @@ // Copyright 2015 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/repo_note.go b/modules/structs/repo_note.go index bddc945a5c..4eaf5a255d 100644 --- a/modules/structs/repo_note.go +++ b/modules/structs/repo_note.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/repo_refs.go b/modules/structs/repo_refs.go index 0bf4b94ae1..6ffbc74a51 100644 --- a/modules/structs/repo_refs.go +++ b/modules/structs/repo_refs.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/repo_tag.go b/modules/structs/repo_tag.go index 80ee1ccf17..4a7d895288 100644 --- a/modules/structs/repo_tag.go +++ b/modules/structs/repo_tag.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/repo_topic.go b/modules/structs/repo_topic.go index 294d56a953..fea193e86b 100644 --- a/modules/structs/repo_topic.go +++ b/modules/structs/repo_topic.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/repo_tree.go b/modules/structs/repo_tree.go index 58aa3b8339..86b221e1fe 100644 --- a/modules/structs/repo_tree.go +++ b/modules/structs/repo_tree.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/repo_watch.go b/modules/structs/repo_watch.go index 606785a4fd..2e89a9eefc 100644 --- a/modules/structs/repo_watch.go +++ b/modules/structs/repo_watch.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/repo_wiki.go b/modules/structs/repo_wiki.go index 09e21387df..3df5a0be99 100644 --- a/modules/structs/repo_wiki.go +++ b/modules/structs/repo_wiki.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/settings.go b/modules/structs/settings.go index 90c4a2107b..e48b1a493d 100644 --- a/modules/structs/settings.go +++ b/modules/structs/settings.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/status.go b/modules/structs/status.go index ed42b24be8..c1d8b902ec 100644 --- a/modules/structs/status.go +++ b/modules/structs/status.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/task.go b/modules/structs/task.go index e83d0437ce..c73e51b1ab 100644 --- a/modules/structs/task.go +++ b/modules/structs/task.go @@ -1,6 +1,5 @@ // Copyright 2019 Gitea. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/user.go b/modules/structs/user.go index 81516894a5..c5e96f3356 100644 --- a/modules/structs/user.go +++ b/modules/structs/user.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/user_app.go b/modules/structs/user_app.go index 4cfa5538c8..3a5ae34df1 100644 --- a/modules/structs/user_app.go +++ b/modules/structs/user_app.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/user_email.go b/modules/structs/user_email.go index a72b04119a..6a11e040af 100644 --- a/modules/structs/user_email.go +++ b/modules/structs/user_email.go @@ -1,6 +1,5 @@ // Copyright 2015 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/user_gpgkey.go b/modules/structs/user_gpgkey.go index a2ebf7df93..ff9b0aea1d 100644 --- a/modules/structs/user_gpgkey.go +++ b/modules/structs/user_gpgkey.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/structs/user_key.go b/modules/structs/user_key.go index ee487607c3..08eed59a89 100644 --- a/modules/structs/user_key.go +++ b/modules/structs/user_key.go @@ -1,6 +1,5 @@ // Copyright 2015 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package structs diff --git a/modules/svg/discover_bindata.go b/modules/svg/discover_bindata.go index cca1de76a7..b6abd294f1 100644 --- a/modules/svg/discover_bindata.go +++ b/modules/svg/discover_bindata.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build bindata diff --git a/modules/svg/discover_nobindata.go b/modules/svg/discover_nobindata.go index ef01fbcc3e..da7ab7b98f 100644 --- a/modules/svg/discover_nobindata.go +++ b/modules/svg/discover_nobindata.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !bindata diff --git a/modules/svg/svg.go b/modules/svg/svg.go index 1d1f8a90eb..e0f0a263f3 100644 --- a/modules/svg/svg.go +++ b/modules/svg/svg.go @@ -1,13 +1,45 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package svg -// SVGs contains discovered SVGs -var SVGs map[string]string +import ( + "fmt" + "html/template" + "regexp" + "strings" + + "code.gitea.io/gitea/modules/html" +) + +var ( + // SVGs contains discovered SVGs + SVGs map[string]string + + widthRe = regexp.MustCompile(`width="[0-9]+?"`) + heightRe = regexp.MustCompile(`height="[0-9]+?"`) +) + +const defaultSize = 16 // Init discovers SVGs and populates the `SVGs` variable func Init() { SVGs = Discover() } + +// Render render icons - arguments icon name (string), size (int), class (string) +func RenderHTML(icon string, others ...interface{}) template.HTML { + size, class := html.ParseSizeAndClass(defaultSize, "", others...) + + if svgStr, ok := SVGs[icon]; ok { + if size != defaultSize { + svgStr = widthRe.ReplaceAllString(svgStr, fmt.Sprintf(`width="%d"`, size)) + svgStr = heightRe.ReplaceAllString(svgStr, fmt.Sprintf(`height="%d"`, size)) + } + if class != "" { + svgStr = strings.Replace(svgStr, `class="`, fmt.Sprintf(`class="%s `, class), 1) + } + return template.HTML(svgStr) + } + return template.HTML("") +} diff --git a/modules/sync/exclusive_pool.go b/modules/sync/exclusive_pool.go index 7c1a8930ce..fbfc1f2292 100644 --- a/modules/sync/exclusive_pool.go +++ b/modules/sync/exclusive_pool.go @@ -1,6 +1,5 @@ // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package sync diff --git a/modules/sync/status_pool.go b/modules/sync/status_pool.go index 99e5ce9cb3..6f075d54b7 100644 --- a/modules/sync/status_pool.go +++ b/modules/sync/status_pool.go @@ -1,6 +1,5 @@ // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package sync diff --git a/modules/sync/status_pool_test.go b/modules/sync/status_pool_test.go index b388c50db2..e2e48862f5 100644 --- a/modules/sync/status_pool_test.go +++ b/modules/sync/status_pool_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package sync diff --git a/modules/system/appstate.go b/modules/system/appstate.go index deee8cd029..765501d432 100644 --- a/modules/system/appstate.go +++ b/modules/system/appstate.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package system diff --git a/modules/system/appstate_test.go b/modules/system/appstate_test.go index fb0c2aaf9f..65a6e50003 100644 --- a/modules/system/appstate_test.go +++ b/modules/system/appstate_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package system diff --git a/modules/system/db.go b/modules/system/db.go index b1c283c488..3f2e4c59bb 100644 --- a/modules/system/db.go +++ b/modules/system/db.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package system diff --git a/modules/system/item_runtime.go b/modules/system/item_runtime.go index e022a0daad..ded52c1426 100644 --- a/modules/system/item_runtime.go +++ b/modules/system/item_runtime.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package system diff --git a/modules/system/setting.go b/modules/system/setting.go deleted file mode 100644 index aebf24a501..0000000000 --- a/modules/system/setting.go +++ /dev/null @@ -1,46 +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 system - -import ( - "strconv" - - "code.gitea.io/gitea/models/system" - "code.gitea.io/gitea/modules/cache" -) - -func genKey(key string) string { - return "system.setting." + key -} - -// GetSetting returns the setting value via the key -func GetSetting(key string) (string, error) { - return cache.GetString(genKey(key), func() (string, error) { - res, err := system.GetSetting(key) - if err != nil { - return "", err - } - return res.SettingValue, nil - }) -} - -// GetSettingBool return bool value of setting, -// none existing keys and errors are ignored and result in false -func GetSettingBool(key string) bool { - s, _ := GetSetting(key) - b, _ := strconv.ParseBool(s) - return b -} - -// SetSetting sets the setting value -func SetSetting(key, value string, version int) error { - cache.Remove(genKey(key)) - - return system.SetSetting(&system.Setting{ - SettingKey: key, - SettingValue: value, - Version: version, - }) -} diff --git a/modules/system/user_setting.go b/modules/system/user_setting.go deleted file mode 100644 index eaf146c08d..0000000000 --- a/modules/system/user_setting.go +++ /dev/null @@ -1,34 +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 system - -import ( - "fmt" - - "code.gitea.io/gitea/models/user" - "code.gitea.io/gitea/modules/cache" -) - -func genUserKey(userID int64, key string) string { - return fmt.Sprintf("user_%d.setting.%s", userID, key) -} - -// GetUserSetting returns the user setting value via the key -func GetUserSetting(userID int64, key string) (string, error) { - return cache.GetString(genUserKey(userID, key), func() (string, error) { - res, err := user.GetSetting(userID, key) - if err != nil { - return "", err - } - return res.SettingValue, nil - }) -} - -// SetUserSetting sets the user setting value -func SetUserSetting(userID int64, key, value string) error { - cache.Remove(genUserKey(userID, key)) - - return user.SetUserSetting(userID, key, value) -} diff --git a/modules/templates/base.go b/modules/templates/base.go index d234d531f3..e0f8350afb 100644 --- a/modules/templates/base.go +++ b/modules/templates/base.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package templates diff --git a/modules/templates/dynamic.go b/modules/templates/dynamic.go index a86e71a8c8..7d25a61fed 100644 --- a/modules/templates/dynamic.go +++ b/modules/templates/dynamic.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT //go:build !bindata diff --git a/modules/templates/helper.go b/modules/templates/helper.go index a127b98dc2..7b997b49d9 100644 --- a/modules/templates/helper.go +++ b/modules/templates/helper.go @@ -1,7 +1,6 @@ // Copyright 2018 The Gitea Authors. All rights reserved. // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package templates @@ -26,6 +25,7 @@ import ( activities_model "code.gitea.io/gitea/models/activities" "code.gitea.io/gitea/models/avatars" + "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/organization" repo_model "code.gitea.io/gitea/models/repo" @@ -35,6 +35,7 @@ import ( "code.gitea.io/gitea/modules/emoji" "code.gitea.io/gitea/modules/git" giturl "code.gitea.io/gitea/modules/git/url" + gitea_html "code.gitea.io/gitea/modules/html" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/markup" @@ -42,7 +43,6 @@ import ( "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/svg" - system_module "code.gitea.io/gitea/modules/system" "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/services/gitdiff" @@ -87,7 +87,7 @@ func NewFuncMap() []template.FuncMap { return setting.AssetVersion }, "DisableGravatar": func() bool { - return system_module.GetSettingBool(system_model.KeyPictureDisableGravatar) + return system_model.GetSettingBool(system_model.KeyPictureDisableGravatar) }, "DefaultShowFullName": func() bool { return setting.UI.DefaultShowFullName @@ -348,7 +348,7 @@ func NewFuncMap() []template.FuncMap { } return false }, - "svg": SVG, + "svg": svg.RenderHTML, "avatar": Avatar, "avatarHTML": AvatarHTML, "avatarByAction": AvatarByAction, @@ -363,17 +363,17 @@ func NewFuncMap() []template.FuncMap { if len(urlSort) == 0 && isDefault { // if sort is sorted as default add arrow tho this table header if isDefault { - return SVG("octicon-triangle-down", 16) + return svg.RenderHTML("octicon-triangle-down", 16) } } else { // if sort arg is in url test if it correlates with column header sort arguments // the direction of the arrow should indicate the "current sort order", up means ASC(normal), down means DESC(rev) if urlSort == normSort { // the table is sorted with this header normal - return SVG("octicon-triangle-up", 16) + return svg.RenderHTML("octicon-triangle-up", 16) } else if urlSort == revSort { // the table is sorted with this header reverse - return SVG("octicon-triangle-down", 16) + return svg.RenderHTML("octicon-triangle-down", 16) } } // the table is NOT sorted with this header @@ -594,29 +594,6 @@ func NewTextFuncMap() []texttmpl.FuncMap { }} } -var ( - widthRe = regexp.MustCompile(`width="[0-9]+?"`) - heightRe = regexp.MustCompile(`height="[0-9]+?"`) -) - -func parseOthers(defaultSize int, defaultClass string, others ...interface{}) (int, string) { - size := defaultSize - if len(others) > 0 && others[0].(int) != 0 { - size = others[0].(int) - } - - class := defaultClass - if len(others) > 1 && others[1].(string) != "" { - if defaultClass == "" { - class = others[1].(string) - } else { - class = defaultClass + " " + others[1].(string) - } - } - - return size, class -} - // AvatarHTML creates the HTML for an avatar func AvatarHTML(src string, size int, class, name string) template.HTML { sizeStr := fmt.Sprintf(`%d`, size) @@ -628,26 +605,9 @@ func AvatarHTML(src string, size int, class, name string) template.HTML { return template.HTML(``) } -// SVG render icons - arguments icon name (string), size (int), class (string) -func SVG(icon string, others ...interface{}) template.HTML { - size, class := parseOthers(16, "", others...) - - if svgStr, ok := svg.SVGs[icon]; ok { - if size != 16 { - svgStr = widthRe.ReplaceAllString(svgStr, fmt.Sprintf(`width="%d"`, size)) - svgStr = heightRe.ReplaceAllString(svgStr, fmt.Sprintf(`height="%d"`, size)) - } - if class != "" { - svgStr = strings.Replace(svgStr, `class="`, fmt.Sprintf(`class="%s `, class), 1) - } - return template.HTML(svgStr) - } - return template.HTML("") -} - // Avatar renders user avatars. args: user, size (int), class (string) func Avatar(item interface{}, others ...interface{}) template.HTML { - size, class := parseOthers(avatars.DefaultAvatarPixelSize, "ui avatar vm", others...) + size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, avatars.DefaultAvatarClass, others...) switch t := item.(type) { case *user_model.User: @@ -672,13 +632,13 @@ func Avatar(item interface{}, others ...interface{}) template.HTML { // AvatarByAction renders user avatars from action. args: action, size (int), class (string) func AvatarByAction(action *activities_model.Action, others ...interface{}) template.HTML { - action.LoadActUser() + action.LoadActUser(db.DefaultContext) return Avatar(action.ActUser, others...) } // RepoAvatar renders repo avatars. args: repo, size(int), class (string) func RepoAvatar(repo *repo_model.Repository, others ...interface{}) template.HTML { - size, class := parseOthers(avatars.DefaultAvatarPixelSize, "ui avatar", others...) + size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, avatars.DefaultAvatarClass, others...) src := repo.RelAvatarLink() if src != "" { @@ -689,7 +649,7 @@ func RepoAvatar(repo *repo_model.Repository, others ...interface{}) template.HTM // AvatarByEmail renders avatars by email address. args: email, name, size (int), class (string) func AvatarByEmail(email, name string, others ...interface{}) template.HTML { - size, class := parseOthers(avatars.DefaultAvatarPixelSize, "ui avatar", others...) + size, class := gitea_html.ParseSizeAndClass(avatars.DefaultAvatarPixelSize, avatars.DefaultAvatarClass, others...) src := avatars.GenerateEmailAvatarFastLink(email, size*setting.Avatar.RenderedSizeFactor) if src != "" { diff --git a/modules/templates/helper_test.go b/modules/templates/helper_test.go index 5ebae7afef..ec83e9ac33 100644 --- a/modules/templates/helper_test.go +++ b/modules/templates/helper_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package templates diff --git a/modules/templates/htmlrenderer.go b/modules/templates/htmlrenderer.go index 81ea660161..7ab523822b 100644 --- a/modules/templates/htmlrenderer.go +++ b/modules/templates/htmlrenderer.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package templates diff --git a/modules/templates/mailer.go b/modules/templates/mailer.go index 0cac1280f3..a257e7c1da 100644 --- a/modules/templates/mailer.go +++ b/modules/templates/mailer.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package templates diff --git a/modules/templates/static.go b/modules/templates/static.go index 7f7cbe702f..7ebb327ae6 100644 --- a/modules/templates/static.go +++ b/modules/templates/static.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT //go:build bindata diff --git a/modules/templates/templates_bindata.go b/modules/templates/templates_bindata.go index bcb2cbaf3f..6f1d3cf539 100644 --- a/modules/templates/templates_bindata.go +++ b/modules/templates/templates_bindata.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT //go:build bindata diff --git a/modules/templates/vars/vars.go b/modules/templates/vars/vars.go index a22ea4d777..cc9d0e976f 100644 --- a/modules/templates/vars/vars.go +++ b/modules/templates/vars/vars.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package vars diff --git a/modules/templates/vars/vars_test.go b/modules/templates/vars/vars_test.go index 1cd7669c00..8f421d9e4b 100644 --- a/modules/templates/vars/vars_test.go +++ b/modules/templates/vars/vars_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package vars diff --git a/modules/test/context_tests.go b/modules/test/context_tests.go index 963f79c3c6..d50f8efc75 100644 --- a/modules/test/context_tests.go +++ b/modules/test/context_tests.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package test @@ -58,7 +57,7 @@ func LoadRepo(t *testing.T, ctx *context.Context, repoID int64) { ctx.Repo = &context.Repository{} ctx.Repo.Repository = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) var err error - ctx.Repo.Owner, err = user_model.GetUserByID(ctx.Repo.Repository.OwnerID) + ctx.Repo.Owner, err = user_model.GetUserByID(ctx, ctx.Repo.Repository.OwnerID) assert.NoError(t, err) ctx.Repo.RepoLink = ctx.Repo.Repository.Link() ctx.Repo.Permission, err = access_model.GetUserRepoPermission(ctx, ctx.Repo.Repository, ctx.Doer) diff --git a/modules/test/utils.go b/modules/test/utils.go index ed1628ab47..7686d3f289 100644 --- a/modules/test/utils.go +++ b/modules/test/utils.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package test diff --git a/modules/timeutil/executable.go b/modules/timeutil/executable.go index 1875b63349..57ae8b2a9d 100644 --- a/modules/timeutil/executable.go +++ b/modules/timeutil/executable.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package timeutil diff --git a/modules/timeutil/language.go b/modules/timeutil/language.go index d0380cac3d..c2f7a0e579 100644 --- a/modules/timeutil/language.go +++ b/modules/timeutil/language.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package timeutil diff --git a/modules/timeutil/since.go b/modules/timeutil/since.go index 8473d45051..295ba7c10e 100644 --- a/modules/timeutil/since.go +++ b/modules/timeutil/since.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package timeutil diff --git a/modules/timeutil/since_test.go b/modules/timeutil/since_test.go index 9350b5e96b..2e1dde00f6 100644 --- a/modules/timeutil/since_test.go +++ b/modules/timeutil/since_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package timeutil diff --git a/modules/timeutil/timestamp.go b/modules/timeutil/timestamp.go index 36b2aff575..4618db9a76 100644 --- a/modules/timeutil/timestamp.go +++ b/modules/timeutil/timestamp.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package timeutil diff --git a/modules/translation/i18n/errors.go b/modules/translation/i18n/errors.go index a81b0bc1ac..7f64ccf908 100644 --- a/modules/translation/i18n/errors.go +++ b/modules/translation/i18n/errors.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package i18n diff --git a/modules/translation/i18n/format.go b/modules/translation/i18n/format.go index 3fb9e6d6d0..637209ad80 100644 --- a/modules/translation/i18n/format.go +++ b/modules/translation/i18n/format.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package i18n diff --git a/modules/translation/i18n/i18n.go b/modules/translation/i18n/i18n.go index d8ed43a1cd..4048c9acd2 100644 --- a/modules/translation/i18n/i18n.go +++ b/modules/translation/i18n/i18n.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package i18n diff --git a/modules/translation/i18n/i18n_test.go b/modules/translation/i18n/i18n_test.go index 0f4605c1bb..76a91522ba 100644 --- a/modules/translation/i18n/i18n_test.go +++ b/modules/translation/i18n/i18n_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package i18n diff --git a/modules/translation/i18n/localestore.go b/modules/translation/i18n/localestore.go index 853519e224..90f574127d 100644 --- a/modules/translation/i18n/localestore.go +++ b/modules/translation/i18n/localestore.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package i18n diff --git a/modules/translation/translation.go b/modules/translation/translation.go index fc311aa61b..5a1009bfa3 100644 --- a/modules/translation/translation.go +++ b/modules/translation/translation.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package translation diff --git a/modules/typesniffer/typesniffer.go b/modules/typesniffer/typesniffer.go index e50928e8c2..c9fef953ce 100644 --- a/modules/typesniffer/typesniffer.go +++ b/modules/typesniffer/typesniffer.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package typesniffer diff --git a/modules/typesniffer/typesniffer_test.go b/modules/typesniffer/typesniffer_test.go index a3b47c4598..dbce94fc3b 100644 --- a/modules/typesniffer/typesniffer_test.go +++ b/modules/typesniffer/typesniffer_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package typesniffer diff --git a/modules/updatechecker/update_checker.go b/modules/updatechecker/update_checker.go index 816fb3764c..bc3f93aad7 100644 --- a/modules/updatechecker/update_checker.go +++ b/modules/updatechecker/update_checker.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package updatechecker diff --git a/modules/upload/upload.go b/modules/upload/upload.go index 734b3a6acc..cd10715864 100644 --- a/modules/upload/upload.go +++ b/modules/upload/upload.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package upload diff --git a/modules/upload/upload_test.go b/modules/upload/upload_test.go index d258b04f77..f2c3242e9a 100644 --- a/modules/upload/upload_test.go +++ b/modules/upload/upload_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package upload diff --git a/modules/uri/uri.go b/modules/uri/uri.go index 74410f43f9..768bc662ce 100644 --- a/modules/uri/uri.go +++ b/modules/uri/uri.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package uri diff --git a/modules/uri/uri_test.go b/modules/uri/uri_test.go index 8cadd6b918..11b915c261 100644 --- a/modules/uri/uri_test.go +++ b/modules/uri/uri_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package uri diff --git a/modules/user/user.go b/modules/user/user.go index af49d7b06a..eee401a23f 100644 --- a/modules/user/user.go +++ b/modules/user/user.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package user diff --git a/modules/user/user_test.go b/modules/user/user_test.go index 3b3758efc0..9129ae79a1 100644 --- a/modules/user/user_test.go +++ b/modules/user/user_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package user diff --git a/modules/util/compare.go b/modules/util/compare.go index 49891ef024..9ac778dfd3 100644 --- a/modules/util/compare.go +++ b/modules/util/compare.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/error.go b/modules/util/error.go index 08e491dbaf..63bd447bf3 100644 --- a/modules/util/error.go +++ b/modules/util/error.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/file_unix.go b/modules/util/file_unix.go index ec9d4ec167..79a29c8b3b 100644 --- a/modules/util/file_unix.go +++ b/modules/util/file_unix.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT //go:build !windows diff --git a/modules/util/file_unix_test.go b/modules/util/file_unix_test.go index 41311aa13f..87d6c2f09a 100644 --- a/modules/util/file_unix_test.go +++ b/modules/util/file_unix_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT //go:build !windows diff --git a/modules/util/file_windows.go b/modules/util/file_windows.go index 6ad3e88ba5..77a33d3c49 100644 --- a/modules/util/file_windows.go +++ b/modules/util/file_windows.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT //go:build windows diff --git a/modules/util/filebuffer/file_backed_buffer.go b/modules/util/filebuffer/file_backed_buffer.go index 8e3e138e04..bfddf90e92 100644 --- a/modules/util/filebuffer/file_backed_buffer.go +++ b/modules/util/filebuffer/file_backed_buffer.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package filebuffer diff --git a/modules/util/filebuffer/file_backed_buffer_test.go b/modules/util/filebuffer/file_backed_buffer_test.go index 83ef58561d..16d5a1965f 100644 --- a/modules/util/filebuffer/file_backed_buffer_test.go +++ b/modules/util/filebuffer/file_backed_buffer_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package filebuffer diff --git a/modules/util/io.go b/modules/util/io.go index d765e27733..e5d7561bef 100644 --- a/modules/util/io.go +++ b/modules/util/io.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/legacy.go b/modules/util/legacy.go index d319faad09..2ea293a2be 100644 --- a/modules/util/legacy.go +++ b/modules/util/legacy.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/legacy_test.go b/modules/util/legacy_test.go index c41f7a008c..e732094c29 100644 --- a/modules/util/legacy_test.go +++ b/modules/util/legacy_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/paginate.go b/modules/util/paginate.go index 2baa71664e..f2721df1ad 100644 --- a/modules/util/paginate.go +++ b/modules/util/paginate.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/paginate_test.go b/modules/util/paginate_test.go index 3657efc919..6e69dd19cc 100644 --- a/modules/util/paginate_test.go +++ b/modules/util/paginate_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/path.go b/modules/util/path.go index 3d4ddec21c..03013f7133 100644 --- a/modules/util/path.go +++ b/modules/util/path.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/path_test.go b/modules/util/path_test.go index b0ea448a1c..5794df1ebf 100644 --- a/modules/util/path_test.go +++ b/modules/util/path_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/remove.go b/modules/util/remove.go index d05ee9fe4a..d1e38faf5f 100644 --- a/modules/util/remove.go +++ b/modules/util/remove.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/sanitize.go b/modules/util/sanitize.go index 685b2699b0..f1ea2574f1 100644 --- a/modules/util/sanitize.go +++ b/modules/util/sanitize.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/sanitize_test.go b/modules/util/sanitize_test.go index 78166cfdff..0bcfd45ca4 100644 --- a/modules/util/sanitize_test.go +++ b/modules/util/sanitize_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/sec_to_time.go b/modules/util/sec_to_time.go index 13461915e6..017ed45f8c 100644 --- a/modules/util/sec_to_time.go +++ b/modules/util/sec_to_time.go @@ -1,6 +1,5 @@ // Copyright 2022 Gitea. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/sec_to_time_test.go b/modules/util/sec_to_time_test.go index 1e256aa865..4d1213a52c 100644 --- a/modules/util/sec_to_time_test.go +++ b/modules/util/sec_to_time_test.go @@ -1,6 +1,5 @@ // Copyright 2022 Gitea. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/shellquote.go b/modules/util/shellquote.go index 5a12c2e261..434dc4236e 100644 --- a/modules/util/shellquote.go +++ b/modules/util/shellquote.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/shellquote_test.go b/modules/util/shellquote_test.go index be6ba372fd..969998c592 100644 --- a/modules/util/shellquote_test.go +++ b/modules/util/shellquote_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/slice.go b/modules/util/slice.go index 552f5b866a..17345cbc49 100644 --- a/modules/util/slice.go +++ b/modules/util/slice.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/string.go b/modules/util/string.go index 2da2bc5dc4..f2def7b0ec 100644 --- a/modules/util/string.go +++ b/modules/util/string.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/string_test.go b/modules/util/string_test.go index 49de29ab67..0a4a8bbcfb 100644 --- a/modules/util/string_test.go +++ b/modules/util/string_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/timer.go b/modules/util/timer.go index b682f376d9..daf96bda7e 100644 --- a/modules/util/timer.go +++ b/modules/util/timer.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/truncate.go b/modules/util/truncate.go index 2e6f7f68b0..032a6c0872 100644 --- a/modules/util/truncate.go +++ b/modules/util/truncate.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/truncate_test.go b/modules/util/truncate_test.go index e505a6ee4a..912bfb3d5f 100644 --- a/modules/util/truncate_test.go +++ b/modules/util/truncate_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/url.go b/modules/util/url.go index 96c66df92b..75fcf634a9 100644 --- a/modules/util/url.go +++ b/modules/util/url.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/util/util.go b/modules/util/util.go index be60fe4b4b..9d3a8dcfac 100644 --- a/modules/util/util.go +++ b/modules/util/util.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package util @@ -186,13 +185,21 @@ func ToUpperASCII(s string) string { return string(b) } -var titleCaser = cases.Title(language.English) +var ( + titleCaser = cases.Title(language.English) + titleCaserNoLower = cases.Title(language.English, cases.NoLower) +) // ToTitleCase returns s with all english words capitalized func ToTitleCase(s string) string { return titleCaser.String(s) } +// ToTitleCaseNoLower returns s with all english words capitalized without lowercasing +func ToTitleCaseNoLower(s string) string { + return titleCaserNoLower.String(s) +} + var ( whitespaceOnly = regexp.MustCompile("(?m)^[ \t]+$") leadingWhitespace = regexp.MustCompile("(?m)(^[ \t]*)(?:[^ \t\n])") diff --git a/modules/util/util_test.go b/modules/util/util_test.go index 91b0ef9455..34fe070d22 100644 --- a/modules/util/util_test.go +++ b/modules/util/util_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package util diff --git a/modules/validation/binding.go b/modules/validation/binding.go index c054fbe7b6..ef0d01e80f 100644 --- a/modules/validation/binding.go +++ b/modules/validation/binding.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package validation diff --git a/modules/validation/binding_test.go b/modules/validation/binding_test.go index aa8a765524..9ca93784a8 100644 --- a/modules/validation/binding_test.go +++ b/modules/validation/binding_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package validation diff --git a/modules/validation/glob_pattern_test.go b/modules/validation/glob_pattern_test.go index cbaed7e66a..1bf622e61d 100644 --- a/modules/validation/glob_pattern_test.go +++ b/modules/validation/glob_pattern_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package validation diff --git a/modules/validation/helpers.go b/modules/validation/helpers.go index e554a629c3..4cb62db15e 100644 --- a/modules/validation/helpers.go +++ b/modules/validation/helpers.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package validation diff --git a/modules/validation/helpers_test.go b/modules/validation/helpers_test.go index 9bdbdb4a77..52f383f698 100644 --- a/modules/validation/helpers_test.go +++ b/modules/validation/helpers_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package validation diff --git a/modules/validation/refname_test.go b/modules/validation/refname_test.go index 2d6458b9b5..3af7387c47 100644 --- a/modules/validation/refname_test.go +++ b/modules/validation/refname_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package validation diff --git a/modules/validation/regex_pattern_test.go b/modules/validation/regex_pattern_test.go index afe1bcf425..efcb276734 100644 --- a/modules/validation/regex_pattern_test.go +++ b/modules/validation/regex_pattern_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package validation diff --git a/modules/validation/validurl_test.go b/modules/validation/validurl_test.go index 3cb6206602..39f7fa5d65 100644 --- a/modules/validation/validurl_test.go +++ b/modules/validation/validurl_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package validation diff --git a/modules/watcher/watcher.go b/modules/watcher/watcher.go index d737f6ccbb..75d062d7aa 100644 --- a/modules/watcher/watcher.go +++ b/modules/watcher/watcher.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package watcher diff --git a/modules/web/middleware/binding.go b/modules/web/middleware/binding.go index cced9717be..733f00a1d5 100644 --- a/modules/web/middleware/binding.go +++ b/modules/web/middleware/binding.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package middleware diff --git a/modules/web/middleware/cookie.go b/modules/web/middleware/cookie.go index b5904d6713..7c1aaf6daf 100644 --- a/modules/web/middleware/cookie.go +++ b/modules/web/middleware/cookie.go @@ -1,7 +1,6 @@ // Copyright 2020 The Macaron Authors // Copyright 2020 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. +// SPDX-License-Identifier: MIT package middleware diff --git a/modules/web/middleware/data.go b/modules/web/middleware/data.go index 7de686498a..43189940ee 100644 --- a/modules/web/middleware/data.go +++ b/modules/web/middleware/data.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package middleware diff --git a/modules/web/middleware/flash.go b/modules/web/middleware/flash.go index d1d4a864e3..f2d7cc692d 100644 --- a/modules/web/middleware/flash.go +++ b/modules/web/middleware/flash.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package middleware diff --git a/modules/web/middleware/locale.go b/modules/web/middleware/locale.go index f4018527c0..f60be4bbdb 100644 --- a/modules/web/middleware/locale.go +++ b/modules/web/middleware/locale.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package middleware diff --git a/modules/web/middleware/request.go b/modules/web/middleware/request.go index f620da5eea..34add27214 100644 --- a/modules/web/middleware/request.go +++ b/modules/web/middleware/request.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package middleware diff --git a/modules/web/route.go b/modules/web/route.go index 4341b1bf5d..0f2fdc33b5 100644 --- a/modules/web/route.go +++ b/modules/web/route.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package web @@ -8,7 +7,6 @@ import ( goctx "context" "fmt" "net/http" - "reflect" "strings" "code.gitea.io/gitea/modules/context" @@ -19,16 +17,9 @@ import ( ) // Bind binding an obj to a handler -func Bind(obj interface{}) http.HandlerFunc { - tp := reflect.TypeOf(obj) - if tp.Kind() == reflect.Ptr { - tp = tp.Elem() - } - if tp.Kind() != reflect.Struct { - panic("Only structs are allowed to bind") - } +func Bind[T any](obj T) http.HandlerFunc { return Wrap(func(ctx *context.Context) { - theObj := reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly + theObj := new(T) // create a new form obj for every request but not use obj directly binding.Bind(ctx.Req, theObj) SetForm(ctx, theObj) middleware.AssignForm(theObj, ctx.Data) diff --git a/modules/web/route_test.go b/modules/web/route_test.go index 801afe92c9..232444cb83 100644 --- a/modules/web/route_test.go +++ b/modules/web/route_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package web diff --git a/modules/web/routing/context.go b/modules/web/routing/context.go index 7e263db5a2..0d5e765543 100644 --- a/modules/web/routing/context.go +++ b/modules/web/routing/context.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package routing diff --git a/modules/web/routing/funcinfo.go b/modules/web/routing/funcinfo.go index 9bb38af1c8..499bc2c7aa 100644 --- a/modules/web/routing/funcinfo.go +++ b/modules/web/routing/funcinfo.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package routing diff --git a/modules/web/routing/funcinfo_test.go b/modules/web/routing/funcinfo_test.go index 9cea7e2817..2ab5960373 100644 --- a/modules/web/routing/funcinfo_test.go +++ b/modules/web/routing/funcinfo_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package routing diff --git a/modules/web/routing/logger.go b/modules/web/routing/logger.go index cf3b50725d..d1b0ff0cda 100644 --- a/modules/web/routing/logger.go +++ b/modules/web/routing/logger.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package routing diff --git a/modules/web/routing/logger_manager.go b/modules/web/routing/logger_manager.go index 7715b0b5d3..aa25ec3a27 100644 --- a/modules/web/routing/logger_manager.go +++ b/modules/web/routing/logger_manager.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package routing diff --git a/modules/web/routing/requestrecord.go b/modules/web/routing/requestrecord.go index 5e225f32e4..34a2d33893 100644 --- a/modules/web/routing/requestrecord.go +++ b/modules/web/routing/requestrecord.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package routing diff --git a/modules/web/wrap.go b/modules/web/wrap.go index b55b876069..0ff9529fae 100644 --- a/modules/web/wrap.go +++ b/modules/web/wrap.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package web diff --git a/modules/web/wrap_convert.go b/modules/web/wrap_convert.go index 9084cfa074..6778e208cf 100644 --- a/modules/web/wrap_convert.go +++ b/modules/web/wrap_convert.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package web diff --git a/options/license/Knuth-CTAN b/options/license/Knuth-CTAN new file mode 100644 index 0000000000..cd91789fd0 --- /dev/null +++ b/options/license/Knuth-CTAN @@ -0,0 +1,5 @@ +This software is copyrighted. Unlimited copying and redistribution +of this package and/or its individual files are permitted +as long as there are no modifications. Modifications, and +redistribution of modifications, are also permitted, but +only if the resulting package and/or files are renamed. diff --git a/options/license/Symlinks b/options/license/Symlinks new file mode 100644 index 0000000000..35420d2ba9 --- /dev/null +++ b/options/license/Symlinks @@ -0,0 +1,10 @@ + My "symlinks" utility pre-dates the "open source licensing" +fad by a number of years. Just to clarify, this is 100% +freeware, written entirely by myself. The intent is to use +it to detect missing/obsolete symlink targets on an installed +distro, before creating the "gold" (or "final") release discs. + +Use and distribute and modify as you (or anyone +else) sees fit. There have no formal restrictions or +requirements whatsoever regarding distribution of either +binaries or source code, whether modified or original. diff --git a/options/license/libutil-David-Nugent b/options/license/libutil-David-Nugent new file mode 100644 index 0000000000..e04b03e340 --- /dev/null +++ b/options/license/libutil-David-Nugent @@ -0,0 +1,15 @@ +Copyright (c) 1995 David Nugent +All rights reserved. + + +Redistribution and use in source and binary forms, with or without modification, is permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice immediately at the beginning of the file, without modification, this list of conditions, and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. This work was done expressly for inclusion into FreeBSD. Other use is permitted provided this notation is included. + +4. Absolutely no warranty of function or purpose is made by the author David Nugent. + +5. Modifications may be freely made to this file providing the above conditions are met. diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index e610bc6b28..70f982b8dc 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -86,12 +86,16 @@ remove = Remove remove_all = Remove All edit = Edit +enabled = Enabled +disabled = Disabled + copy = Copy copy_url = Copy URL copy_content = Copy content copy_branch = Copy branch name copy_success = Copied! copy_error = Copy failed +copy_type_unsupported = This file type can not be copied write = Write preview = Preview @@ -501,6 +505,7 @@ team_not_exist = The team does not exist. last_org_owner = You cannot remove the last user from the 'owners' team. There must be at least one owner for an organization. cannot_add_org_to_team = An organization cannot be added as a team member. duplicate_invite_to_team = The user was already invited as a team member. +organization_leave_success = You have successfully left the organization %s. invalid_ssh_key = Can not verify your SSH key: %s invalid_gpg_key = Can not verify your GPG key: %s @@ -944,8 +949,8 @@ archive.title = This repo is archived. You can view files and clone it, but cann archive.issue.nocomment = This repo is archived. You cannot comment on issues. archive.pull.nocomment = This repo is archived. You cannot comment on pull requests. -form.reach_limit_of_creation_1 = You have already reached your limit of %d repository. -form.reach_limit_of_creation_n = You have already reached your limit of %d repositories. +form.reach_limit_of_creation_1 = The owner has already reached the limit of %d repository. +form.reach_limit_of_creation_n = The owner has already reached the limit of %d repositories. form.name_reserved = The repository name '%s' is reserved. form.name_pattern_not_allowed = The pattern '%s' is not allowed in a repository name. @@ -1013,10 +1018,12 @@ unstar = Unstar star = Star fork = Fork download_archive = Download Repository +more_operations = More Operations no_desc = No Description quick_guide = Quick Guide clone_this_repo = Clone this repository +cite_this_repo = Cite this repository create_new_repo_command = Creating a new repository on the command line push_exist_repo = Pushing an existing repository from the command line empty_message = This repository does not contain any content. @@ -1091,7 +1098,6 @@ editor.cannot_edit_non_text_files = Binary files cannot be edited in the web int editor.edit_this_file = Edit File editor.this_file_locked = File is locked editor.must_be_on_a_branch = You must be on a branch to make or propose changes to this file. -editor.only_copy_raw = You may only copy raw text files. editor.fork_before_edit = You must fork this repository to make or propose changes to this file. editor.delete_this_file = Delete File editor.must_have_write_access = You must have write access to make or propose changes to this file. @@ -1167,7 +1173,7 @@ commits.signed_by_untrusted_user_unmatched = Signed by untrusted user who does n commits.gpg_key_id = GPG Key ID commits.ssh_key_fingerprint = SSH Key Fingerprint -commit.actions = Actions +commit.operations = Operations commit.revert = Revert commit.revert-header = Revert: %s commit.revert-content = Select branch to revert onto: @@ -1625,6 +1631,8 @@ pulls.reopened_at = `reopened this pull request %[2] pulls.merge_instruction_hint = `You can also view command line instructions.` pulls.merge_instruction_step1_desc = From your project repository, check out a new branch and test the changes. pulls.merge_instruction_step2_desc = Merge the changes and update on Gitea. +pulls.clear_merge_message = Clear merge message +pulls.clear_merge_message_hint = Clearing the merge message will only remove the commit message content and keep generated git trailers such as "Co-Authored-By …". pulls.auto_merge_button_when_succeed = (When checks succeed) pulls.auto_merge_when_succeed = Auto merge when all checks succeed @@ -2981,7 +2989,7 @@ monitor.queue.pool.cancel_desc = Leaving a queue without any worker groups may c notices.system_notice_list = System Notices notices.view_detail_header = View Notice Details -notices.actions = Actions +notices.operations = Operations notices.select_all = Select All notices.deselect_all = Deselect All notices.inverse_selection = Inverse Selection @@ -3184,3 +3192,23 @@ settings.delete.description = Deleting a package is permanent and cannot be undo settings.delete.notice = You are about to delete %s (%s). This operation is irreversible, are you sure? settings.delete.success = The package has been deleted. settings.delete.error = Failed to delete the package. +owner.settings.cleanuprules.title = Manage Cleanup Rules +owner.settings.cleanuprules.add = Add Cleanup Rule +owner.settings.cleanuprules.edit = Edit Cleanup Rule +owner.settings.cleanuprules.none = No cleanup rules available. Read the docs to learn more. +owner.settings.cleanuprules.preview = Cleanup Rule Preview +owner.settings.cleanuprules.preview.overview = %d packages are scheduled to be removed. +owner.settings.cleanuprules.preview.none = Cleanup rule does not match any packages. +owner.settings.cleanuprules.enabled = Enabled +owner.settings.cleanuprules.pattern_full_match = Apply pattern to full package name +owner.settings.cleanuprules.keep.title = Versions that match these rules are kept, even if they match a removal rule below. +owner.settings.cleanuprules.keep.count = Keep the most recent +owner.settings.cleanuprules.keep.count.1 = 1 version per package +owner.settings.cleanuprules.keep.count.n = %d versions per package +owner.settings.cleanuprules.keep.pattern = Keep versions matching +owner.settings.cleanuprules.keep.pattern.container = The latest version is always kept for Container packages. +owner.settings.cleanuprules.remove.title = Versions that match these rules are removed, unless a rule above says to keep them. +owner.settings.cleanuprules.remove.days = Remove versions older than +owner.settings.cleanuprules.remove.pattern = Remove versions matching +owner.settings.cleanuprules.success.update = Cleanup rule has been updated. +owner.settings.cleanuprules.success.delete = Cleanup rule has been deleted. diff --git a/package-lock.json b/package-lock.json index cd11a43e4f..b9c649c9de 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,12 +7,16 @@ "name": "gitea", "license": "MIT", "dependencies": { + "@citation-js/core": "0.6.1", + "@citation-js/plugin-bibtex": "0.6.1", + "@citation-js/plugin-csl": "0.6.4", + "@citation-js/plugin-software-formats": "0.6.0", "@claviska/jquery-minicolors": "2.3.6", "@mcaptcha/vanilla-glue": "0.1.0-alpha-3", - "@primer/octicons": "17.7.0", - "@vue/compiler-sfc": "3.2.41", + "@primer/octicons": "17.9.0", + "@vue/compiler-sfc": "3.2.45", "add-asset-webpack-plugin": "2.0.1", - "css-loader": "6.7.1", + "css-loader": "6.7.2", "dropzone": "6.0.0-beta.2", "easymde": "2.18.0", "esbuild-loader": "2.20.0", @@ -25,45 +29,46 @@ "less": "4.1.3", "less-loader": "11.1.0", "license-checker-webpack-plugin": "0.2.1", - "mermaid": "9.1.7", - "mini-css-extract-plugin": "2.6.1", + "mermaid": "9.2.2", + "mini-css-extract-plugin": "2.7.0", "monaco-editor": "0.34.1", "monaco-editor-webpack-plugin": "7.0.1", "pretty-ms": "8.0.0", "sortablejs": "1.15.0", - "swagger-ui-dist": "4.15.0", + "swagger-ui-dist": "4.15.5", "tippy.js": "6.3.7", "tributejs": "5.1.3", "uint8-to-base64": "0.2.0", - "vue": "3.2.41", + "vue": "3.2.45", "vue-bar-graph": "2.0.0", - "vue-loader": "17.0.0", + "vue-loader": "17.0.1", "vue3-calendar-heatmap": "2.0.0", - "webpack": "5.74.0", - "webpack-cli": "4.10.0", + "webpack": "5.75.0", + "webpack-cli": "5.0.0", "workbox-routing": "6.5.4", "workbox-strategies": "6.5.4", "worker-loader": "3.0.8", "wrap-ansi": "8.0.1" }, "devDependencies": { - "@playwright/test": "1.27.1", + "@playwright/test": "1.28.0", "@rollup/pluginutils": "5.0.2", - "@stoplight/spectral-cli": "6.5.1", - "eslint": "8.26.0", + "@stoplight/spectral-cli": "6.6.0", + "eslint": "8.28.0", "eslint-plugin-import": "2.26.0", "eslint-plugin-jquery": "1.5.1", "eslint-plugin-sonarjs": "0.16.0", - "eslint-plugin-unicorn": "44.0.2", - "eslint-plugin-vue": "9.6.0", - "jsdom": "20.0.1", + "eslint-plugin-unicorn": "45.0.0", + "eslint-plugin-vue": "9.7.0", + "jsdom": "20.0.3", "markdownlint-cli": "0.32.2", "postcss-less": "6.0.0", - "stylelint": "14.14.0", + "stylelint": "14.15.0", "stylelint-config-standard": "29.0.0", - "svgo": "3.0.0", - "updates": "13.1.10", - "vitest": "0.24.3" + "stylelint-declaration-strict-value": "1.9.1", + "svgo": "3.0.2", + "updates": "13.2.1", + "vitest": "0.25.2" }, "engines": { "node": ">= 14.0.0" @@ -182,9 +187,9 @@ } }, "node_modules/@babel/parser": { - "version": "7.19.6", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.19.6.tgz", - "integrity": "sha512-h1IUp81s2JYJ3mRkdxJgs4UvmSsRvDrx5ICSJbPvtWYv5i1nTBGcBpnog+89rAFMwvvru6E5NUHdBe01UeSzYA==", + "version": "7.20.3", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.20.3.tgz", + "integrity": "sha512-OP/s5a94frIPXwjzEcv5S/tpQfc6XhxYUnmWpgdqMWGgYCuErA3SzozaRAMQgSZWKeTJxht9aWAkUY+0UzvOFg==", "bin": { "parser": "bin/babel-parser.js" }, @@ -193,9 +198,83 @@ } }, "node_modules/@braintree/sanitize-url": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-6.0.1.tgz", - "integrity": "sha512-zr9Qs9KFQiEvMWdZesjcmRJlUck5NR+eKGS1uyKk+oYTWwlYrsoPEi6VmG6/TzBD1hKCGEimrhTgGS6hvn/xIQ==" + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-6.0.2.tgz", + "integrity": "sha512-Tbsj02wXCbqGmzdnXNk0SOF19ChhRU70BsroIi4Pm6Ehp56in6vch94mfbdQ17DozxkL3BAVjbZ4Qc1a0HFRAg==" + }, + "node_modules/@citation-js/core": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/@citation-js/core/-/core-0.6.1.tgz", + "integrity": "sha512-zvVxsAP4ciVHiZ60TmKTfjui4m6xeISSp/rtIhOcvZxZ70bBfkt83+kGnuI4xRlhB/oUrZN2fC9BSRKdivSobQ==", + "dependencies": { + "@citation-js/date": "^0.5.0", + "@citation-js/name": "^0.4.2", + "fetch-ponyfill": "^7.1.0", + "sync-fetch": "^0.4.1" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@citation-js/date": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/@citation-js/date/-/date-0.5.1.tgz", + "integrity": "sha512-1iDKAZ4ie48PVhovsOXQ+C6o55dWJloXqtznnnKy6CltJBQLIuLLuUqa8zlIvma0ZigjVjgDUhnVaNU1MErtZw==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/@citation-js/name": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@citation-js/name/-/name-0.4.2.tgz", + "integrity": "sha512-brSPsjs2fOVzSnARLKu0qncn6suWjHVQtrqSUrnqyaRH95r/Ad4wPF5EsoWr+Dx8HzkCGb/ogmoAzfCsqlTwTQ==", + "engines": { + "node": ">=6" + } + }, + "node_modules/@citation-js/plugin-bibtex": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/@citation-js/plugin-bibtex/-/plugin-bibtex-0.6.1.tgz", + "integrity": "sha512-JMw9h9MUXH7YWvgN0j+A5xI4Fw3cHYcDMzpweeAcXBfjfnC6q30Dyvs2YxfUxNEKvWDgRQjAiNNIzgWXs9uK1Q==", + "dependencies": { + "@citation-js/date": "^0.5.0", + "@citation-js/name": "^0.4.2", + "moo": "^0.5.1" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "@citation-js/core": "^0.6.0" + } + }, + "node_modules/@citation-js/plugin-csl": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/@citation-js/plugin-csl/-/plugin-csl-0.6.4.tgz", + "integrity": "sha512-RG4NrFIx0CZTfNeMCC8CL7UGFRiUv5/bNd/Nc6Q/NHx0cS/tYDQcKt0M24dpOI7PAZwVoddbDW4Iakn6nS4QsQ==", + "dependencies": { + "@citation-js/date": "^0.5.0", + "citeproc": "^2.4.6" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "@citation-js/core": "^0.6.0" + } + }, + "node_modules/@citation-js/plugin-software-formats": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@citation-js/plugin-software-formats/-/plugin-software-formats-0.6.0.tgz", + "integrity": "sha512-l0Vp2h9UNlqsGMgrJulA92csgu8l3WhhBC0F2nFl76aTMOrMzC9/DX1G2Ob5tUQvPfuy4B5ZZsYPJNTJdtPVhw==", + "dependencies": { + "@citation-js/date": "^0.5.0", + "@citation-js/name": "^0.4.2", + "js-yaml": "^4.0.0" + }, + "peerDependencies": { + "@citation-js/core": "^0.6.0" + } }, "node_modules/@claviska/jquery-minicolors": { "version": "2.3.6", @@ -231,9 +310,9 @@ } }, "node_modules/@esbuild/android-arm": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.15.12.tgz", - "integrity": "sha512-IC7TqIqiyE0MmvAhWkl/8AEzpOtbhRNDo7aph47We1NbE5w2bt/Q+giAhe0YYeVpYnIhGMcuZY92qDK6dQauvA==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.15.14.tgz", + "integrity": "sha512-+Rb20XXxRGisNu2WmNKk+scpanb7nL5yhuI1KR9wQFiC43ddPj/V1fmNyzlFC9bKiG4mYzxW7egtoHVcynr+OA==", "cpu": [ "arm" ], @@ -246,9 +325,9 @@ } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.15.12.tgz", - "integrity": "sha512-tZEowDjvU7O7I04GYvWQOS4yyP9E/7YlsB0jjw1Ycukgr2ycEzKyIk5tms5WnLBymaewc6VmRKnn5IJWgK4eFw==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.15.14.tgz", + "integrity": "sha512-eQi9rosGNVQFJyJWV0HCA5WZae/qWIQME7s8/j8DMvnylfBv62Pbu+zJ2eUDqNf2O4u3WB+OEXyfkpBoe194sg==", "cpu": [ "loong64" ], @@ -306,14 +385,14 @@ "dev": true }, "node_modules/@humanwhocodes/config-array": { - "version": "0.11.6", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.6.tgz", - "integrity": "sha512-jJr+hPTJYKyDILJfhNSHsjiwXYf26Flsz8DvNndOsHs5pwSnpGUEy8yzF0JYhCEvTDdV2vuOK5tt8BVhwO5/hg==", + "version": "0.11.7", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.7.tgz", + "integrity": "sha512-kBbPWzN8oVMLb0hOUYXhmxggL/1cJE6ydvjDIGi9EnAGUyA7cLVKQg+d/Dsm+KZwx2czGHrCmMVLiyg8s5JPKw==", "dev": true, "dependencies": { "@humanwhocodes/object-schema": "^1.2.1", "debug": "^4.1.1", - "minimatch": "^3.0.4" + "minimatch": "^3.0.5" }, "engines": { "node": ">=10.10.0" @@ -496,13 +575,13 @@ } }, "node_modules/@playwright/test": { - "version": "1.27.1", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.27.1.tgz", - "integrity": "sha512-mrL2q0an/7tVqniQQF6RBL2saskjljXzqNcCOVMUjRIgE6Y38nCNaP+Dc2FBW06bcpD3tqIws/HT9qiMHbNU0A==", + "version": "1.28.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.28.0.tgz", + "integrity": "sha512-vrHs5DFTPwYox5SGKq/7TDn/S4q6RA1zArd7uhO6EyP9hj3XgZBBM12ktMbnDQNxh/fL1IUKsTNLxihmsU38lQ==", "dev": true, "dependencies": { "@types/node": "*", - "playwright-core": "1.27.1" + "playwright-core": "1.28.0" }, "bin": { "playwright": "cli.js" @@ -521,17 +600,17 @@ } }, "node_modules/@primer/octicons": { - "version": "17.7.0", - "resolved": "https://registry.npmjs.org/@primer/octicons/-/octicons-17.7.0.tgz", - "integrity": "sha512-J5cVJDhExmqLGLWu8zHTOqcC8g1rQL7QzQZdbvHxW85u8ya82GtF5F68uHMDI5En3fsMlbkkF8Rz6dCaV3r+KA==", + "version": "17.9.0", + "resolved": "https://registry.npmjs.org/@primer/octicons/-/octicons-17.9.0.tgz", + "integrity": "sha512-B6y3VxPrF6U+GUjZR883NsstI7v/Qcup9puDG+fOJvCm8b7UXNl46TbRrctMCZnYlyIzUF3/SgjJhr5od/Y6sw==", "dependencies": { "object-assign": "^4.1.1" } }, "node_modules/@rollup/plugin-commonjs": { - "version": "20.0.0", - "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-20.0.0.tgz", - "integrity": "sha512-5K0g5W2Ol8hAcTHqcTBHiA7M58tfmYi1o9KxeJuuRNpGaTa5iLjcyemBitCBcKXaHamOBBEH2dGom6v6Unmqjg==", + "version": "22.0.2", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-22.0.2.tgz", + "integrity": "sha512-//NdP6iIwPbMTcazYsiBMbJW7gfmpHom33u1beiIoHDEM0Q9clvtQB1T0efvMqHeKsGohiHo97BCPCkBXdscwg==", "dev": true, "dependencies": { "@rollup/pluginutils": "^3.1.0", @@ -543,10 +622,10 @@ "resolve": "^1.17.0" }, "engines": { - "node": ">= 8.0.0" + "node": ">= 12.0.0" }, "peerDependencies": { - "rollup": "^2.38.3" + "rollup": "^2.68.0" } }, "node_modules/@rollup/plugin-commonjs/node_modules/@rollup/pluginutils": { @@ -617,13 +696,14 @@ } }, "node_modules/@stoplight/json": { - "version": "3.17.0", - "resolved": "https://registry.npmjs.org/@stoplight/json/-/json-3.17.0.tgz", - "integrity": "sha512-WW0z2bb0D4t8FTl+zNTCu46J8lEOsrUhBPgwEYQ3Ri2Y0MiRE4U1/9ZV8Ki+pIJznZgY9i42bbFwOBxyZn5/6w==", + "version": "3.20.1", + "resolved": "https://registry.npmjs.org/@stoplight/json/-/json-3.20.1.tgz", + "integrity": "sha512-FXfud+uWgIj1xv6nUO9WnmgmnVikaxJcbtR4XQt4C42n5c2qua3U05Z/3B57hP5TJRSj+tpn9ID6/bFeyYYlEg==", "dev": true, "dependencies": { - "@stoplight/ordered-object-literal": "^1.0.2", - "@stoplight/types": "^12.3.0", + "@stoplight/ordered-object-literal": "^1.0.3", + "@stoplight/path": "^1.3.2", + "@stoplight/types": "^13.6.0", "jsonc-parser": "~2.2.1", "lodash": "^4.17.21", "safe-stable-stringify": "^1.1" @@ -652,22 +732,21 @@ "dev": true }, "node_modules/@stoplight/json-ref-resolver": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/@stoplight/json-ref-resolver/-/json-ref-resolver-3.1.3.tgz", - "integrity": "sha512-SgoKXwVnlpIZUyAFX4W79eeuTWvXmNlMfICZixL16GZXnkjcW+uZnfmAU0ZIjcnaTgaI4mjfxn8LAP2KR6Cr0A==", + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/@stoplight/json-ref-resolver/-/json-ref-resolver-3.1.4.tgz", + "integrity": "sha512-842JVmMsi++qpDuIX+JpQvK7YY8FXEZZb+/z4xuRfStOAVEryJT/tbgGOWxniSdxEl9Eni5D/I2afMyy6BuiNw==", "dev": true, "dependencies": { "@stoplight/json": "^3.17.0", "@stoplight/path": "^1.3.2", - "@stoplight/types": "^12.3.0", - "@types/urijs": "^1.19.16", + "@stoplight/types": "^12.3.0 || ^13.0.0", + "@types/urijs": "^1.19.19", "dependency-graph": "~0.11.0", "fast-memoize": "^2.5.2", "immer": "^9.0.6", - "lodash.get": "^4.4.2", - "lodash.set": "^4.3.2", + "lodash": "^4.17.21", "tslib": "^2.3.1", - "urijs": "^1.19.6" + "urijs": "^1.19.11" }, "engines": { "node": ">=8.3.0" @@ -692,22 +771,21 @@ } }, "node_modules/@stoplight/spectral-cli": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/@stoplight/spectral-cli/-/spectral-cli-6.5.1.tgz", - "integrity": "sha512-+qpwsDG2jQ4ULQmegBWonI3UnF6tUh351WDnV1GU8acl8eaeKbS+ZUNBgoP2f9tnMTfITdctVRFEGC3D6P7f9g==", + "version": "6.6.0", + "resolved": "https://registry.npmjs.org/@stoplight/spectral-cli/-/spectral-cli-6.6.0.tgz", + "integrity": "sha512-z46fnrvraaWMio8Y9RYYkLO+XdmtxOWpy5qNJF3CsmWua0FZ4iOTryb5Cm3GkB0wEtqxNUCBUHvoo4hS6Noyqg==", "dev": true, "dependencies": { - "@rollup/plugin-commonjs": "^20.0.0", - "@stoplight/json": "3.17.0", + "@stoplight/json": "~3.20.1", "@stoplight/path": "1.3.2", - "@stoplight/spectral-core": "^1.5.1", - "@stoplight/spectral-parsers": "^1.0.1", - "@stoplight/spectral-ref-resolver": "1.0.1", - "@stoplight/spectral-ruleset-bundler": "^1.0.0", - "@stoplight/spectral-ruleset-migrator": "^1.5.0", + "@stoplight/spectral-core": "^1.15.1", + "@stoplight/spectral-parsers": "^1.0.2", + "@stoplight/spectral-ref-resolver": "1.0.2", + "@stoplight/spectral-ruleset-bundler": "^1.4.0", + "@stoplight/spectral-ruleset-migrator": "^1.9.0", "@stoplight/spectral-rulesets": ">=1", - "@stoplight/spectral-runtime": "^1.1.0", - "@stoplight/types": "12.3.0", + "@stoplight/spectral-runtime": "^1.1.2", + "@stoplight/types": "^13.6.0", "chalk": "4.1.2", "cliui": "7.0.4", "eol": "0.9.1", @@ -757,9 +835,9 @@ } }, "node_modules/@stoplight/spectral-core": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/@stoplight/spectral-core/-/spectral-core-1.15.0.tgz", - "integrity": "sha512-+DwK8SmnujMZJaxJeNU11vWY+DFOnt4oQM1TzAuvufdd3Y6Lsno88Jl31OaR1M9Fn7l/u3v1anBB/SSl/fI5rQ==", + "version": "1.15.1", + "resolved": "https://registry.npmjs.org/@stoplight/spectral-core/-/spectral-core-1.15.1.tgz", + "integrity": "sha512-IZV8L1Hyz9759KdqJIA90W5uvurHplMmaPPIZjQzG2Bq/39kN/sbLA/Js8uOf3xB9cHBbG599t4AB+uGsI8t0g==", "dev": true, "dependencies": { "@stoplight/better-ajv-errors": "1.0.3", @@ -774,7 +852,6 @@ "ajv": "^8.6.0", "ajv-errors": "~3.0.0", "ajv-formats": "~2.1.0", - "blueimp-md5": "2.18.0", "es-aggregate-error": "^1.0.7", "jsonpath-plus": "7.1.0", "lodash": "~4.17.21", @@ -789,23 +866,6 @@ "node": "^12.20 || >= 14.13" } }, - "node_modules/@stoplight/spectral-core/node_modules/@stoplight/json": { - "version": "3.20.1", - "resolved": "https://registry.npmjs.org/@stoplight/json/-/json-3.20.1.tgz", - "integrity": "sha512-FXfud+uWgIj1xv6nUO9WnmgmnVikaxJcbtR4XQt4C42n5c2qua3U05Z/3B57hP5TJRSj+tpn9ID6/bFeyYYlEg==", - "dev": true, - "dependencies": { - "@stoplight/ordered-object-literal": "^1.0.3", - "@stoplight/path": "^1.3.2", - "@stoplight/types": "^13.6.0", - "jsonc-parser": "~2.2.1", - "lodash": "^4.17.21", - "safe-stable-stringify": "^1.1" - }, - "engines": { - "node": ">=8.3.0" - } - }, "node_modules/@stoplight/spectral-core/node_modules/@stoplight/types": { "version": "13.6.0", "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.6.0.tgz", @@ -856,36 +916,6 @@ "node": ">=12" } }, - "node_modules/@stoplight/spectral-functions/node_modules/@stoplight/json": { - "version": "3.20.1", - "resolved": "https://registry.npmjs.org/@stoplight/json/-/json-3.20.1.tgz", - "integrity": "sha512-FXfud+uWgIj1xv6nUO9WnmgmnVikaxJcbtR4XQt4C42n5c2qua3U05Z/3B57hP5TJRSj+tpn9ID6/bFeyYYlEg==", - "dev": true, - "dependencies": { - "@stoplight/ordered-object-literal": "^1.0.3", - "@stoplight/path": "^1.3.2", - "@stoplight/types": "^13.6.0", - "jsonc-parser": "~2.2.1", - "lodash": "^4.17.21", - "safe-stable-stringify": "^1.1" - }, - "engines": { - "node": ">=8.3.0" - } - }, - "node_modules/@stoplight/spectral-functions/node_modules/@stoplight/types": { - "version": "13.7.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.7.0.tgz", - "integrity": "sha512-7ePIccfTxjEhruv8VrkDv5whP5qd9ijRzAWEbjYpUYnDfaqPTfq8/wMMjMCAKIecboxsAVD9LZy/3puXddGsDQ==", - "dev": true, - "dependencies": { - "@types/json-schema": "^7.0.4", - "utility-types": "^3.10.0" - }, - "engines": { - "node": "^12.20 || >=14.13" - } - }, "node_modules/@stoplight/spectral-parsers": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/@stoplight/spectral-parsers/-/spectral-parsers-1.0.2.tgz", @@ -901,45 +931,15 @@ "node": ">=12" } }, - "node_modules/@stoplight/spectral-parsers/node_modules/@stoplight/json": { - "version": "3.20.1", - "resolved": "https://registry.npmjs.org/@stoplight/json/-/json-3.20.1.tgz", - "integrity": "sha512-FXfud+uWgIj1xv6nUO9WnmgmnVikaxJcbtR4XQt4C42n5c2qua3U05Z/3B57hP5TJRSj+tpn9ID6/bFeyYYlEg==", - "dev": true, - "dependencies": { - "@stoplight/ordered-object-literal": "^1.0.3", - "@stoplight/path": "^1.3.2", - "@stoplight/types": "^13.6.0", - "jsonc-parser": "~2.2.1", - "lodash": "^4.17.21", - "safe-stable-stringify": "^1.1" - }, - "engines": { - "node": ">=8.3.0" - } - }, - "node_modules/@stoplight/spectral-parsers/node_modules/@stoplight/types": { - "version": "13.7.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.7.0.tgz", - "integrity": "sha512-7ePIccfTxjEhruv8VrkDv5whP5qd9ijRzAWEbjYpUYnDfaqPTfq8/wMMjMCAKIecboxsAVD9LZy/3puXddGsDQ==", - "dev": true, - "dependencies": { - "@types/json-schema": "^7.0.4", - "utility-types": "^3.10.0" - }, - "engines": { - "node": "^12.20 || >=14.13" - } - }, "node_modules/@stoplight/spectral-ref-resolver": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@stoplight/spectral-ref-resolver/-/spectral-ref-resolver-1.0.1.tgz", - "integrity": "sha512-0tY7nTOccvTsa3c4QbSWfJ8wGfPO1RXvmKnmBjuyLfoTMNuhkHPII9gKhCjygsshzsBLxs2IyRHZYhWYVnEbCA==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@stoplight/spectral-ref-resolver/-/spectral-ref-resolver-1.0.2.tgz", + "integrity": "sha512-ah6NIB/O1EdEaEu89So3LmtbKRXPVnSElgQ7oBRE9S4/VOedSqyXn+qqMd40tGnO2CsKgZaFUYXdSEHOshpHYw==", "dev": true, "dependencies": { "@stoplight/json-ref-readers": "1.2.2", - "@stoplight/json-ref-resolver": "3.1.3", - "@stoplight/spectral-runtime": "^1.0.0", + "@stoplight/json-ref-resolver": "~3.1.4", + "@stoplight/spectral-runtime": "^1.1.2", "dependency-graph": "0.11.0", "tslib": "^2.3.1" }, @@ -948,9 +948,9 @@ } }, "node_modules/@stoplight/spectral-ruleset-bundler": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@stoplight/spectral-ruleset-bundler/-/spectral-ruleset-bundler-1.3.3.tgz", - "integrity": "sha512-hfHl7XZeF/wWMpSrsLqLnH2GevRHjSIqtBL2aRjO2SjMCTbO9LVz80p4sYaxrCcu4wQ6K71gMZXsG687+3fAeg==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@stoplight/spectral-ruleset-bundler/-/spectral-ruleset-bundler-1.4.0.tgz", + "integrity": "sha512-aYDI4a145IXED+6jvRjj9Ha0fnB+s54cr8KbQbPCEyhCHW1cP8UGVeOuwAfk+9C4ZIg40OuYrugN5EhA35oQtA==", "dev": true, "dependencies": { "@rollup/plugin-commonjs": "~22.0.2", @@ -974,73 +974,10 @@ "node": "^12.20 || >= 14.13" } }, - "node_modules/@stoplight/spectral-ruleset-bundler/node_modules/@rollup/plugin-commonjs": { - "version": "22.0.2", - "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-22.0.2.tgz", - "integrity": "sha512-//NdP6iIwPbMTcazYsiBMbJW7gfmpHom33u1beiIoHDEM0Q9clvtQB1T0efvMqHeKsGohiHo97BCPCkBXdscwg==", - "dev": true, - "dependencies": { - "@rollup/pluginutils": "^3.1.0", - "commondir": "^1.0.1", - "estree-walker": "^2.0.1", - "glob": "^7.1.6", - "is-reference": "^1.2.1", - "magic-string": "^0.25.7", - "resolve": "^1.17.0" - }, - "engines": { - "node": ">= 12.0.0" - }, - "peerDependencies": { - "rollup": "^2.68.0" - } - }, - "node_modules/@stoplight/spectral-ruleset-bundler/node_modules/@rollup/pluginutils": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.1.0.tgz", - "integrity": "sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==", - "dev": true, - "dependencies": { - "@types/estree": "0.0.39", - "estree-walker": "^1.0.1", - "picomatch": "^2.2.2" - }, - "engines": { - "node": ">= 8.0.0" - }, - "peerDependencies": { - "rollup": "^1.20.0||^2.0.0" - } - }, - "node_modules/@stoplight/spectral-ruleset-bundler/node_modules/@rollup/pluginutils/node_modules/estree-walker": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-1.0.1.tgz", - "integrity": "sha512-1fMXF3YP4pZZVozF8j/ZLfvnR8NSIljt56UhbZ5PeeDmmGHpgpdwQt7ITlGvYaQukCvuBRMLEiKiYC+oeIg4cg==", - "dev": true - }, - "node_modules/@stoplight/spectral-ruleset-bundler/node_modules/@stoplight/types": { - "version": "13.7.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.7.0.tgz", - "integrity": "sha512-7ePIccfTxjEhruv8VrkDv5whP5qd9ijRzAWEbjYpUYnDfaqPTfq8/wMMjMCAKIecboxsAVD9LZy/3puXddGsDQ==", - "dev": true, - "dependencies": { - "@types/json-schema": "^7.0.4", - "utility-types": "^3.10.0" - }, - "engines": { - "node": "^12.20 || >=14.13" - } - }, - "node_modules/@stoplight/spectral-ruleset-bundler/node_modules/@types/estree": { - "version": "0.0.39", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", - "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==", - "dev": true - }, "node_modules/@stoplight/spectral-ruleset-migrator": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@stoplight/spectral-ruleset-migrator/-/spectral-ruleset-migrator-1.8.0.tgz", - "integrity": "sha512-zg6RPF+d8uS7zAp5TzUph3hQG4sgGcG5Fsw8Zx24H1REyuSkjiIfyee2Kf13c3BcIlTXvnFc4csz2rNXpZO7Ug==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@stoplight/spectral-ruleset-migrator/-/spectral-ruleset-migrator-1.9.0.tgz", + "integrity": "sha512-hPSjgXsTxMQ5UV1hfkVVPknhqRjmjSnCZD5jideM4rRU5NS1fj2Pse1CiXBsRChsuAGi/2s0Ke5uuOmFFsHrxQ==", "dev": true, "dependencies": { "@stoplight/json": "~3.20.1", @@ -1062,36 +999,6 @@ "node": ">=12" } }, - "node_modules/@stoplight/spectral-ruleset-migrator/node_modules/@stoplight/json": { - "version": "3.20.1", - "resolved": "https://registry.npmjs.org/@stoplight/json/-/json-3.20.1.tgz", - "integrity": "sha512-FXfud+uWgIj1xv6nUO9WnmgmnVikaxJcbtR4XQt4C42n5c2qua3U05Z/3B57hP5TJRSj+tpn9ID6/bFeyYYlEg==", - "dev": true, - "dependencies": { - "@stoplight/ordered-object-literal": "^1.0.3", - "@stoplight/path": "^1.3.2", - "@stoplight/types": "^13.6.0", - "jsonc-parser": "~2.2.1", - "lodash": "^4.17.21", - "safe-stable-stringify": "^1.1" - }, - "engines": { - "node": ">=8.3.0" - } - }, - "node_modules/@stoplight/spectral-ruleset-migrator/node_modules/@stoplight/types": { - "version": "13.7.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.7.0.tgz", - "integrity": "sha512-7ePIccfTxjEhruv8VrkDv5whP5qd9ijRzAWEbjYpUYnDfaqPTfq8/wMMjMCAKIecboxsAVD9LZy/3puXddGsDQ==", - "dev": true, - "dependencies": { - "@types/json-schema": "^7.0.4", - "utility-types": "^3.10.0" - }, - "engines": { - "node": "^12.20 || >=14.13" - } - }, "node_modules/@stoplight/spectral-rulesets": { "version": "1.14.1", "resolved": "https://registry.npmjs.org/@stoplight/spectral-rulesets/-/spectral-rulesets-1.14.1.tgz", @@ -1117,19 +1024,6 @@ "node": ">=12" } }, - "node_modules/@stoplight/spectral-rulesets/node_modules/@stoplight/types": { - "version": "13.7.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.7.0.tgz", - "integrity": "sha512-7ePIccfTxjEhruv8VrkDv5whP5qd9ijRzAWEbjYpUYnDfaqPTfq8/wMMjMCAKIecboxsAVD9LZy/3puXddGsDQ==", - "dev": true, - "dependencies": { - "@types/json-schema": "^7.0.4", - "utility-types": "^3.10.0" - }, - "engines": { - "node": "^12.20 || >=14.13" - } - }, "node_modules/@stoplight/spectral-runtime": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/@stoplight/spectral-runtime/-/spectral-runtime-1.1.2.tgz", @@ -1148,10 +1042,10 @@ "node": ">=12" } }, - "node_modules/@stoplight/types": { - "version": "12.3.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-12.3.0.tgz", - "integrity": "sha512-hgzUR1z5BlYvIzUeFK5pjs5JXSvEutA9Pww31+dVicBlunsG1iXopDx/cvfBY7rHOrgtZDuvyeK4seqkwAZ6Cg==", + "node_modules/@stoplight/spectral-runtime/node_modules/@stoplight/types": { + "version": "12.5.0", + "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-12.5.0.tgz", + "integrity": "sha512-dwqYcDrGmEyUv5TWrDam5TGOxU72ufyQ7hnOIIDdmW5ezOwZaBFoR5XQ9AsH49w7wgvOqB2Bmo799pJPWnpCbg==", "dev": true, "dependencies": { "@types/json-schema": "^7.0.4", @@ -1161,6 +1055,19 @@ "node": ">=8" } }, + "node_modules/@stoplight/types": { + "version": "13.8.0", + "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.8.0.tgz", + "integrity": "sha512-5glKswz7y9aACh+a+JegID+4xX//4TsIdv7iPl29hWnOoWrnlPbg3Gjc4nYUXXgMSaSlSsA15JU/0+rE89fR4A==", + "dev": true, + "dependencies": { + "@types/json-schema": "^7.0.4", + "utility-types": "^3.10.0" + }, + "engines": { + "node": "^12.20 || >=14.13" + } + }, "node_modules/@stoplight/yaml": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/@stoplight/yaml/-/yaml-4.2.3.tgz", @@ -1182,19 +1089,6 @@ "integrity": "sha512-sV+51I7WYnLJnKPn2EMWgS4EUfoP4iWEbrWwbXsj0MZCB/xOK8j6+C9fntIdOM50kpx45ZLC3s6kwKivWuqvyg==", "dev": true }, - "node_modules/@stoplight/yaml/node_modules/@stoplight/types": { - "version": "13.7.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.7.0.tgz", - "integrity": "sha512-7ePIccfTxjEhruv8VrkDv5whP5qd9ijRzAWEbjYpUYnDfaqPTfq8/wMMjMCAKIecboxsAVD9LZy/3puXddGsDQ==", - "dev": true, - "dependencies": { - "@types/json-schema": "^7.0.4", - "utility-types": "^3.10.0" - }, - "engines": { - "node": "^12.20 || >=14.13" - } - }, "node_modules/@swc/helpers": { "version": "0.2.14", "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.2.14.tgz", @@ -1219,9 +1113,9 @@ } }, "node_modules/@types/chai": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.3.tgz", - "integrity": "sha512-hC7OMnszpxhZPduX+m+nrx+uFoLkWOMiR4oa/AZF3MuSETYTZmFfJAHqZEM8MVlvfG7BEUcgvtwoCTxBp6hm3g==", + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.4.tgz", + "integrity": "sha512-KnRanxnpfpjUTqTCXslZSEdLfXExwgNxYPdiO2WGUj8+HDjFi8R3k5RVKPeSCzLjCcshCAtVO2QBbVuAV4kTnw==", "dev": true }, "node_modules/@types/chai-subset": { @@ -1251,9 +1145,9 @@ } }, "node_modules/@types/eslint": { - "version": "8.4.7", - "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.4.7.tgz", - "integrity": "sha512-ehM7cCt2RSFs42mb+lcmhFT9ouIlV92PuaeRGn8N8c98oMjG4Z5pJHA9b1QiCcuqnbPSHcyfiD3mlhqMaHsQIw==", + "version": "8.4.10", + "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.4.10.tgz", + "integrity": "sha512-Sl/HOqN8NKPmhWo2VBEPm0nvHnu2LL3v9vKo8MEq0EtbJ4eVzGPl41VNPvn5E1i5poMk4/XD8UriLHpJvEP/Nw==", "dependencies": { "@types/estree": "*", "@types/json-schema": "*" @@ -1296,9 +1190,9 @@ "dev": true }, "node_modules/@types/node": { - "version": "18.11.4", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.4.tgz", - "integrity": "sha512-BxcJpBu8D3kv/GZkx/gSMz6VnTJREBj/4lbzYOQueUOELkt8WrO6zAcSPmp9uRPEW/d+lUO8QK0W2xnS1hEU0A==" + "version": "18.11.9", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.9.tgz", + "integrity": "sha512-CRpX21/kGdzjOpFsZSkcrXMGIBWMGNIHXXBVFSH+ggkftxg+XYP20TESbh+zFvFj3EQOl5byk0HTRn1IL6hbqg==" }, "node_modules/@types/normalize-package-data": { "version": "2.4.1", @@ -1327,36 +1221,36 @@ "dev": true }, "node_modules/@vue/compiler-core": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.2.41.tgz", - "integrity": "sha512-oA4mH6SA78DT+96/nsi4p9DX97PHcNROxs51lYk7gb9Z4BPKQ3Mh+BLn6CQZBw857Iuhu28BfMSRHAlPvD4vlw==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.2.45.tgz", + "integrity": "sha512-rcMj7H+PYe5wBV3iYeUgbCglC+pbpN8hBLTJvRiK2eKQiWqu+fG9F+8sW99JdL4LQi7Re178UOxn09puSXvn4A==", "dependencies": { "@babel/parser": "^7.16.4", - "@vue/shared": "3.2.41", + "@vue/shared": "3.2.45", "estree-walker": "^2.0.2", "source-map": "^0.6.1" } }, "node_modules/@vue/compiler-dom": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.2.41.tgz", - "integrity": "sha512-xe5TbbIsonjENxJsYRbDJvthzqxLNk+tb3d/c47zgREDa/PCp6/Y4gC/skM4H6PIuX5DAxm7fFJdbjjUH2QTMw==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.2.45.tgz", + "integrity": "sha512-tyYeUEuKqqZO137WrZkpwfPCdiiIeXYCcJ8L4gWz9vqaxzIQRccTSwSWZ/Axx5YR2z+LvpUbmPNXxuBU45lyRw==", "dependencies": { - "@vue/compiler-core": "3.2.41", - "@vue/shared": "3.2.41" + "@vue/compiler-core": "3.2.45", + "@vue/shared": "3.2.45" } }, "node_modules/@vue/compiler-sfc": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.2.41.tgz", - "integrity": "sha512-+1P2m5kxOeaxVmJNXnBskAn3BenbTmbxBxWOtBq3mQTCokIreuMULFantBUclP0+KnzNCMOvcnKinqQZmiOF8w==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.2.45.tgz", + "integrity": "sha512-1jXDuWah1ggsnSAOGsec8cFjT/K6TMZ0sPL3o3d84Ft2AYZi2jWJgRMjw4iaK0rBfA89L5gw427H4n1RZQBu6Q==", "dependencies": { "@babel/parser": "^7.16.4", - "@vue/compiler-core": "3.2.41", - "@vue/compiler-dom": "3.2.41", - "@vue/compiler-ssr": "3.2.41", - "@vue/reactivity-transform": "3.2.41", - "@vue/shared": "3.2.41", + "@vue/compiler-core": "3.2.45", + "@vue/compiler-dom": "3.2.45", + "@vue/compiler-ssr": "3.2.45", + "@vue/reactivity-transform": "3.2.45", + "@vue/shared": "3.2.45", "estree-walker": "^2.0.2", "magic-string": "^0.25.7", "postcss": "^8.1.10", @@ -1364,69 +1258,69 @@ } }, "node_modules/@vue/compiler-ssr": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.2.41.tgz", - "integrity": "sha512-Y5wPiNIiaMz/sps8+DmhaKfDm1xgj6GrH99z4gq2LQenfVQcYXmHIOBcs5qPwl7jaW3SUQWjkAPKMfQemEQZwQ==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.2.45.tgz", + "integrity": "sha512-6BRaggEGqhWht3lt24CrIbQSRD5O07MTmd+LjAn5fJj568+R9eUD2F7wMQJjX859seSlrYog7sUtrZSd7feqrQ==", "dependencies": { - "@vue/compiler-dom": "3.2.41", - "@vue/shared": "3.2.41" + "@vue/compiler-dom": "3.2.45", + "@vue/shared": "3.2.45" } }, "node_modules/@vue/reactivity": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.2.41.tgz", - "integrity": "sha512-9JvCnlj8uc5xRiQGZ28MKGjuCoPhhTwcoAdv3o31+cfGgonwdPNuvqAXLhlzu4zwqavFEG5tvaoINQEfxz+l6g==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.2.45.tgz", + "integrity": "sha512-PRvhCcQcyEVohW0P8iQ7HDcIOXRjZfAsOds3N99X/Dzewy8TVhTCT4uXpAHfoKjVTJRA0O0K+6QNkDIZAxNi3A==", "dependencies": { - "@vue/shared": "3.2.41" + "@vue/shared": "3.2.45" } }, "node_modules/@vue/reactivity-transform": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/reactivity-transform/-/reactivity-transform-3.2.41.tgz", - "integrity": "sha512-mK5+BNMsL4hHi+IR3Ft/ho6Za+L3FA5j8WvreJ7XzHrqkPq8jtF/SMo7tuc9gHjLDwKZX1nP1JQOKo9IEAn54A==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/reactivity-transform/-/reactivity-transform-3.2.45.tgz", + "integrity": "sha512-BHVmzYAvM7vcU5WmuYqXpwaBHjsS8T63jlKGWVtHxAHIoMIlmaMyurUSEs1Zcg46M4AYT5MtB1U274/2aNzjJQ==", "dependencies": { "@babel/parser": "^7.16.4", - "@vue/compiler-core": "3.2.41", - "@vue/shared": "3.2.41", + "@vue/compiler-core": "3.2.45", + "@vue/shared": "3.2.45", "estree-walker": "^2.0.2", "magic-string": "^0.25.7" } }, "node_modules/@vue/runtime-core": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.2.41.tgz", - "integrity": "sha512-0LBBRwqnI0p4FgIkO9q2aJBBTKDSjzhnxrxHYengkAF6dMOjeAIZFDADAlcf2h3GDALWnblbeprYYpItiulSVQ==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.2.45.tgz", + "integrity": "sha512-gzJiTA3f74cgARptqzYswmoQx0fIA+gGYBfokYVhF8YSXjWTUA2SngRzZRku2HbGbjzB6LBYSbKGIaK8IW+s0A==", "dependencies": { - "@vue/reactivity": "3.2.41", - "@vue/shared": "3.2.41" + "@vue/reactivity": "3.2.45", + "@vue/shared": "3.2.45" } }, "node_modules/@vue/runtime-dom": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.2.41.tgz", - "integrity": "sha512-U7zYuR1NVIP8BL6jmOqmapRAHovEFp7CSw4pR2FacqewXNGqZaRfHoNLQsqQvVQ8yuZNZtxSZy0FFyC70YXPpA==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.2.45.tgz", + "integrity": "sha512-cy88YpfP5Ue2bDBbj75Cb4bIEZUMM/mAkDMfqDTpUYVgTf/kuQ2VQ8LebuZ8k6EudgH8pYhsGWHlY0lcxlvTwA==", "dependencies": { - "@vue/runtime-core": "3.2.41", - "@vue/shared": "3.2.41", + "@vue/runtime-core": "3.2.45", + "@vue/shared": "3.2.45", "csstype": "^2.6.8" } }, "node_modules/@vue/server-renderer": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.2.41.tgz", - "integrity": "sha512-7YHLkfJdTlsZTV0ae5sPwl9Gn/EGr2hrlbcS/8naXm2CDpnKUwC68i1wGlrYAfIgYWL7vUZwk2GkYLQH5CvFig==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.2.45.tgz", + "integrity": "sha512-ebiMq7q24WBU1D6uhPK//2OTR1iRIyxjF5iVq/1a5I1SDMDyDu4Ts6fJaMnjrvD3MqnaiFkKQj+LKAgz5WIK3g==", "dependencies": { - "@vue/compiler-ssr": "3.2.41", - "@vue/shared": "3.2.41" + "@vue/compiler-ssr": "3.2.45", + "@vue/shared": "3.2.45" }, "peerDependencies": { - "vue": "3.2.41" + "vue": "3.2.45" } }, "node_modules/@vue/shared": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.2.41.tgz", - "integrity": "sha512-W9mfWLHmJhkfAmV+7gDjcHeAWALQtgGT3JErxULl0oz6R6+3ug91I7IErs93eCFhPCZPHBs4QJS7YWEV7A3sxw==" + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.2.45.tgz", + "integrity": "sha512-Ewzq5Yhimg7pSztDV+RH1UDKBzmtqieXQlpTVm2AwraoRL/Rks96mvd8Vgi7Lj+h+TH8dv7mXD3FRZR3TUvbSg==" }, "node_modules/@webassemblyjs/ast": { "version": "1.11.1", @@ -1560,31 +1454,39 @@ } }, "node_modules/@webpack-cli/configtest": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-1.2.0.tgz", - "integrity": "sha512-4FB8Tj6xyVkyqjj1OaTqCjXYULB9FMkqQ8yGrZjRDrYh0nOE+7Lhs45WioWQQMV+ceFlE368Ukhe6xdvJM9Egg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-2.0.0.tgz", + "integrity": "sha512-war4OU8NGjBqU3DP3bx6ciODXIh7dSXcpQq+P4K2Tqyd8L5OjZ7COx9QXx/QdCIwL2qoX09Wr4Cwf7uS4qdEng==", + "engines": { + "node": ">=14.15.0" + }, "peerDependencies": { - "webpack": "4.x.x || 5.x.x", - "webpack-cli": "4.x.x" + "webpack": "5.x.x", + "webpack-cli": "5.x.x" } }, "node_modules/@webpack-cli/info": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@webpack-cli/info/-/info-1.5.0.tgz", - "integrity": "sha512-e8tSXZpw2hPl2uMJY6fsMswaok5FdlGNRTktvFk2sD8RjH0hE2+XistawJx1vmKteh4NmGmNUrp+Tb2w+udPcQ==", - "dependencies": { - "envinfo": "^7.7.3" + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@webpack-cli/info/-/info-2.0.0.tgz", + "integrity": "sha512-NNxDgbo4VOkNhOlTgY0Elhz3vKpOJq4/PKeKg7r8cmYM+GQA9vDofLYyup8jS6EpUvhNmR30cHTCEIyvXpskwA==", + "engines": { + "node": ">=14.15.0" }, "peerDependencies": { - "webpack-cli": "4.x.x" + "webpack": "5.x.x", + "webpack-cli": "5.x.x" } }, "node_modules/@webpack-cli/serve": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/@webpack-cli/serve/-/serve-1.7.0.tgz", - "integrity": "sha512-oxnCNGj88fL+xzV+dacXs44HcDwf1ovs3AuEzvP7mqXw7fQntqIhQ1BRmynh4qEKQSSSRSWVyXRjmTbZIX9V2Q==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@webpack-cli/serve/-/serve-2.0.0.tgz", + "integrity": "sha512-Rumq5mHvGXamnOh3O8yLk1sjx8dB30qF1OeR6VC00DIR6SLJ4bwwUGKC4pE7qBFoQyyh0H9sAg3fikYgAqVR0w==", + "engines": { + "node": ">=14.15.0" + }, "peerDependencies": { - "webpack-cli": "4.x.x" + "webpack": "5.x.x", + "webpack-cli": "5.x.x" }, "peerDependenciesMeta": { "webpack-dev-server": { @@ -1694,9 +1596,9 @@ } }, "node_modules/ajv": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz", - "integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==", + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.2.tgz", + "integrity": "sha512-E4bfmKAhGiSTvMfL1Myyycaub+cUEU2/IvpylXkUu7CHBkBj1f/ikdzbD7YQ6FKUbixDxeYvB/xY4fvyroDlQg==", "dependencies": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -1783,8 +1685,7 @@ "node_modules/argparse": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" }, "node_modules/array-find-index": { "version": "1.0.2", @@ -1795,15 +1696,15 @@ } }, "node_modules/array-includes": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.5.tgz", - "integrity": "sha512-iSDYZMMyTPkiFasVqfuAQnWAYcvO/SeBSCGKePoEthjp4LEMTe4uLc7b025o4jAZpHhihh8xPo99TNWUWWkGDQ==", + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.6.tgz", + "integrity": "sha512-sgTbLvL6cNnw24FnbaDyjmvddQ2ML8arZsgaJhoABMoplz/4QRhtrYS+alr1BUM1Bwp6dhx8vVCBSLG+StwOFw==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.1.4", - "es-abstract": "^1.19.5", - "get-intrinsic": "^1.1.1", + "es-abstract": "^1.20.4", + "get-intrinsic": "^1.1.3", "is-string": "^1.0.7" }, "engines": { @@ -1823,14 +1724,14 @@ } }, "node_modules/array.prototype.flat": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.0.tgz", - "integrity": "sha512-12IUEkHsAhA4DY5s0FPgNXIdc8VRSqD9Zp78a5au9abH/SOBrsp082JOWFNTjkMozh8mqcdiKuaLGhPeYztxSw==", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.1.tgz", + "integrity": "sha512-roTU0KWIOmJ4DRLmwKd19Otg0/mT3qPNt0Qb3GWW8iObuZXxrjB/pzn0R3hqpRSWg4HCwqx+0vwOnWnvlOyeIA==", "dev": true, "dependencies": { "call-bind": "^1.0.2", - "define-properties": "^1.1.3", - "es-abstract": "^1.19.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4", "es-shim-unscopables": "^1.0.0" }, "engines": { @@ -1908,6 +1809,25 @@ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, "node_modules/big.js": { "version": "5.2.2", "resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz", @@ -1916,12 +1836,6 @@ "node": "*" } }, - "node_modules/blueimp-md5": { - "version": "2.18.0", - "resolved": "https://registry.npmjs.org/blueimp-md5/-/blueimp-md5-2.18.0.tgz", - "integrity": "sha512-vE52okJvzsVWhcgUHOv+69OG3Mdg151xyn41aVQN/5W5S+S43qZhxECtYLAEHMSFWX6Mv5IZrzj3T5+JqXfj5Q==", - "dev": true - }, "node_modules/boolbase": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", @@ -1975,6 +1889,29 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, + "node_modules/buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -2056,9 +1993,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001423", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001423.tgz", - "integrity": "sha512-09iwWGOlifvE1XuHokFMP7eR38a0JnajoyL3/i87c8ZjRWRrdKo1fqjNfugfBD0UDBIOz0U+jtNhJ0EPm1VleQ==", + "version": "1.0.30001431", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001431.tgz", + "integrity": "sha512-zBUoFU0ZcxpvSt9IU66dXVT/3ctO1cy4y9cscs1szkPlcWb6pasYM144GqrUygUbT+k7cmUCW61cvskjcv0enQ==", "funding": [ { "type": "opencollective", @@ -2071,14 +2008,14 @@ ] }, "node_modules/chai": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.6.tgz", - "integrity": "sha512-bbcp3YfHCUzMOvKqsztczerVgBKSsEijCySNlHHbX3VG1nskvqjz5Rfso1gGwD6w6oOV3eI60pKuMOV5MV7p3Q==", + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.7.tgz", + "integrity": "sha512-HLnAzZ2iupm25PlN0xFreAlBA5zaBSv3og0DdeGA4Ar6h6rJ3A0rolRUKJhSF2V10GZKDgWF/VmAEsNWjCRB+A==", "dev": true, "dependencies": { "assertion-error": "^1.1.0", "check-error": "^1.0.2", - "deep-eql": "^3.0.1", + "deep-eql": "^4.1.2", "get-func-name": "^2.0.0", "loupe": "^2.3.1", "pathval": "^1.1.1", @@ -2121,10 +2058,18 @@ } }, "node_modules/ci-info": { - "version": "3.5.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.5.0.tgz", - "integrity": "sha512-yH4RezKOGlOhxkmhbeNuC4eYZKAUsEaGtBuBzDDP1eFUKiccDWzBABxBfOx31IDwDIXMTxWuwAxUGModvkbuVw==", - "dev": true + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.6.1.tgz", + "integrity": "sha512-up5ggbaDqOqJ4UqLKZ2naVkyqSJQgJi5lwD6b6mM748ysrghDBX0bx/qJTUHzw7zu6Mq4gycviSF5hJnwceD8w==", + "dev": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/citeproc": { + "version": "2.4.62", + "resolved": "https://registry.npmjs.org/citeproc/-/citeproc-2.4.62.tgz", + "integrity": "sha512-l3uFfSEwNZp/jlz/TpgyBs85kOww6VlQHbAth0cpbgOn6iulZd+QlFY43LrRelzcYt3FZHTZ3soDyd8lNmkqdw==" }, "node_modules/clean-regexp": { "version": "1.0.0", @@ -2200,9 +2145,9 @@ } }, "node_modules/codemirror": { - "version": "5.65.9", - "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-5.65.9.tgz", - "integrity": "sha512-19Jox5sAKpusTDgqgKB5dawPpQcY+ipQK7xoEI+MVucEF9qqFaXpeqY1KaoyGBso/wHQoDa4HMMxMjdsS3Zzzw==" + "version": "5.65.10", + "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-5.65.10.tgz", + "integrity": "sha512-IXAG5wlhbgcTJ6rZZcmi4+sjWIbJqIGfeg3tNa3yX84Jb3T4huS5qzQAo/cUisc1l3bI47WZodpyf7cYcocDKg==" }, "node_modules/codemirror-spell-checker": { "version": "1.1.2", @@ -2288,9 +2233,9 @@ "dev": true }, "node_modules/cosmiconfig": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.0.1.tgz", - "integrity": "sha512-a1YWNUV2HwGimB7dU2s1wUMurNKjpx60HxBB6xUM8Re+2s1g1IIfJvFR0/iCF+XHdE0GMTKTuLR32UQff4TEyQ==", + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.1.0.tgz", + "integrity": "sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA==", "dev": true, "dependencies": { "@types/parse-json": "^4.0.0", @@ -2316,6 +2261,15 @@ "node": ">= 8" } }, + "node_modules/css-color-names": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/css-color-names/-/css-color-names-0.0.4.tgz", + "integrity": "sha512-zj5D7X1U2h2zsXOAM8EyUREBnnts6H+Jm+d1M2DbiQQcUtnqgQsMrdo8JW9R80YFUmIdBZeMu5wvYM7hcgWP/Q==", + "dev": true, + "engines": { + "node": "*" + } + }, "node_modules/css-functions-list": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/css-functions-list/-/css-functions-list-3.1.0.tgz", @@ -2326,18 +2280,18 @@ } }, "node_modules/css-loader": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-6.7.1.tgz", - "integrity": "sha512-yB5CNFa14MbPJcomwNh3wLThtkZgcNyI2bNMRt8iE5Z8Vwl7f8vQXFAzn2HDOJvtDq2NTZBUGMSUNNyrv3/+cw==", + "version": "6.7.2", + "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-6.7.2.tgz", + "integrity": "sha512-oqGbbVcBJkm8QwmnNzrFrWTnudnRZC+1eXikLJl0n4ljcfotgRifpg2a1lKy8jTrc4/d9A/ap1GFq1jDKG7J+Q==", "dependencies": { "icss-utils": "^5.1.0", - "postcss": "^8.4.7", + "postcss": "^8.4.18", "postcss-modules-extract-imports": "^3.0.0", "postcss-modules-local-by-default": "^4.0.0", "postcss-modules-scope": "^3.0.0", "postcss-modules-values": "^4.0.0", "postcss-value-parser": "^4.2.0", - "semver": "^7.3.5" + "semver": "^7.3.8" }, "engines": { "node": ">= 12.13.0" @@ -2366,6 +2320,12 @@ "url": "https://github.com/sponsors/fb55" } }, + "node_modules/css-shorthand-properties": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/css-shorthand-properties/-/css-shorthand-properties-1.1.1.tgz", + "integrity": "sha512-Md+Juc7M3uOdbAFwOYlTrccIZ7oCFuzrhKYQjdeUEW/sE1hv17Jp/Bws+ReOPpGVBTYCBoYo+G17V5Qo8QQ75A==", + "dev": true + }, "node_modules/css-tree": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-2.2.1.tgz", @@ -2380,6 +2340,23 @@ "npm": ">=7.0.0" } }, + "node_modules/css-values": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/css-values/-/css-values-0.1.0.tgz", + "integrity": "sha512-hQ6JSn4t/70aOCvdlP9zTOsFFUifMSKWz3PX7rz5NZl+uEHCqTFVJJvfP07isErCGEVHYoc8Orja8wLKZRvOeg==", + "dev": true, + "dependencies": { + "css-color-names": "0.0.4", + "ends-with": "^0.2.0", + "postcss-value-parser": "^3.3.0" + } + }, + "node_modules/css-values/node_modules/postcss-value-parser": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-3.3.1.tgz", + "integrity": "sha512-pISE66AbVkp4fDQ7VHBwRNXzAAKJjw4Vw7nWI/+Q3vuly7SNfgYXvm6i5IgFylHGK5sP/xHAbB7N49OS4gWNyQ==", + "dev": true + }, "node_modules/css-what": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz", @@ -3184,9 +3161,9 @@ } }, "node_modules/decamelize-keys": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/decamelize-keys/-/decamelize-keys-1.1.0.tgz", - "integrity": "sha512-ocLWuYzRPoS9bfiSdDd3cxvrzovVMZnRDVEzAs+hWIVXGDbHxWMECij2OBuyB/An0FFW/nLuq6Kv1i/YC5Qfzg==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/decamelize-keys/-/decamelize-keys-1.1.1.tgz", + "integrity": "sha512-WiPxgEirIV0/eIOMcnFBA3/IJZAZqKnwAwWyvvdi4lsr1WCN22nhdf/3db3DoZcUjTV2SqfzIwNyp6y2xs3nmg==", "dev": true, "dependencies": { "decamelize": "^1.1.0", @@ -3194,6 +3171,9 @@ }, "engines": { "node": ">=0.10.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/decamelize-keys/node_modules/map-obj": { @@ -3212,15 +3192,15 @@ "dev": true }, "node_modules/deep-eql": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-3.0.1.tgz", - "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==", + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.2.tgz", + "integrity": "sha512-gT18+YW4CcW/DBNTwAmqTtkJh7f9qqScu2qFVlx7kCoeY9tlBu9cUcr7+I+Z/noG8INehS3xQgLpTtd/QUTn4w==", "dev": true, "dependencies": { "type-detect": "^4.0.0" }, "engines": { - "node": ">=0.12" + "node": ">=6" } }, "node_modules/deep-extend": { @@ -3550,6 +3530,15 @@ "node": ">= 4" } }, + "node_modules/ends-with": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/ends-with/-/ends-with-0.2.0.tgz", + "integrity": "sha512-lRppY4dK3VkqBdR242sKcAJeYc8Gf/DhoX9AWvWI2RzccmLnqBQfwm2k4oSDv5MPDjUqawCauXhZkyWxkVhRsg==", + "dev": true, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/enhanced-resolve": { "version": "5.10.0", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.10.0.tgz", @@ -3651,17 +3640,17 @@ } }, "node_modules/es-aggregate-error": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/es-aggregate-error/-/es-aggregate-error-1.0.8.tgz", - "integrity": "sha512-AKUb5MKLWMozPlFRHOKqWD7yta5uaEhH21qwtnf6FlKjNjTJOoqFi0/G14+FfSkIQhhu6X68Af4xgRC6y8qG4A==", + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/es-aggregate-error/-/es-aggregate-error-1.0.9.tgz", + "integrity": "sha512-fvnX40sb538wdU6r4s35cq4EY6Lr09Upj40BEVem4LEsuW8XgQep9yD5Q1U2KftokNp1rWODFJ2qwZSsAjFpbg==", "dev": true, "dependencies": { "define-properties": "^1.1.4", - "es-abstract": "^1.19.5", + "es-abstract": "^1.20.4", "function-bind": "^1.1.1", "functions-have-names": "^1.2.3", - "get-intrinsic": "^1.1.1", - "globalthis": "^1.0.2", + "get-intrinsic": "^1.1.3", + "globalthis": "^1.0.3", "has-property-descriptors": "^1.0.0" }, "engines": { @@ -3703,9 +3692,9 @@ } }, "node_modules/esbuild": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.15.12.tgz", - "integrity": "sha512-PcT+/wyDqJQsRVhaE9uX/Oq4XLrFh0ce/bs2TJh4CSaw9xuvI+xFrH2nAYOADbhQjUgAhNWC5LKoUsakm4dxng==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.15.14.tgz", + "integrity": "sha512-pJN8j42fvWLFWwSMG4luuupl2Me7mxciUOsMegKvwCmhEbJ2covUdFnihxm0FMIBV+cbwbtMoHgMCCI+pj1btQ==", "hasInstallScript": true, "bin": { "esbuild": "bin/esbuild" @@ -3714,34 +3703,34 @@ "node": ">=12" }, "optionalDependencies": { - "@esbuild/android-arm": "0.15.12", - "@esbuild/linux-loong64": "0.15.12", - "esbuild-android-64": "0.15.12", - "esbuild-android-arm64": "0.15.12", - "esbuild-darwin-64": "0.15.12", - "esbuild-darwin-arm64": "0.15.12", - "esbuild-freebsd-64": "0.15.12", - "esbuild-freebsd-arm64": "0.15.12", - "esbuild-linux-32": "0.15.12", - "esbuild-linux-64": "0.15.12", - "esbuild-linux-arm": "0.15.12", - "esbuild-linux-arm64": "0.15.12", - "esbuild-linux-mips64le": "0.15.12", - "esbuild-linux-ppc64le": "0.15.12", - "esbuild-linux-riscv64": "0.15.12", - "esbuild-linux-s390x": "0.15.12", - "esbuild-netbsd-64": "0.15.12", - "esbuild-openbsd-64": "0.15.12", - "esbuild-sunos-64": "0.15.12", - "esbuild-windows-32": "0.15.12", - "esbuild-windows-64": "0.15.12", - "esbuild-windows-arm64": "0.15.12" + "@esbuild/android-arm": "0.15.14", + "@esbuild/linux-loong64": "0.15.14", + "esbuild-android-64": "0.15.14", + "esbuild-android-arm64": "0.15.14", + "esbuild-darwin-64": "0.15.14", + "esbuild-darwin-arm64": "0.15.14", + "esbuild-freebsd-64": "0.15.14", + "esbuild-freebsd-arm64": "0.15.14", + "esbuild-linux-32": "0.15.14", + "esbuild-linux-64": "0.15.14", + "esbuild-linux-arm": "0.15.14", + "esbuild-linux-arm64": "0.15.14", + "esbuild-linux-mips64le": "0.15.14", + "esbuild-linux-ppc64le": "0.15.14", + "esbuild-linux-riscv64": "0.15.14", + "esbuild-linux-s390x": "0.15.14", + "esbuild-netbsd-64": "0.15.14", + "esbuild-openbsd-64": "0.15.14", + "esbuild-sunos-64": "0.15.14", + "esbuild-windows-32": "0.15.14", + "esbuild-windows-64": "0.15.14", + "esbuild-windows-arm64": "0.15.14" } }, "node_modules/esbuild-android-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-android-64/-/esbuild-android-64-0.15.12.tgz", - "integrity": "sha512-MJKXwvPY9g0rGps0+U65HlTsM1wUs9lbjt5CU19RESqycGFDRijMDQsh68MtbzkqWSRdEtiKS1mtPzKneaAI0Q==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-android-64/-/esbuild-android-64-0.15.14.tgz", + "integrity": "sha512-HuilVIb4rk9abT4U6bcFdU35UHOzcWVGLSjEmC58OVr96q5UiRqzDtWjPlCMugjhgUGKEs8Zf4ueIvYbOStbIg==", "cpu": [ "x64" ], @@ -3754,9 +3743,9 @@ } }, "node_modules/esbuild-android-arm64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-android-arm64/-/esbuild-android-arm64-0.15.12.tgz", - "integrity": "sha512-Hc9SEcZbIMhhLcvhr1DH+lrrec9SFTiRzfJ7EGSBZiiw994gfkVV6vG0sLWqQQ6DD7V4+OggB+Hn0IRUdDUqvA==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-android-arm64/-/esbuild-android-arm64-0.15.14.tgz", + "integrity": "sha512-/QnxRVxsR2Vtf3XottAHj7hENAMW2wCs6S+OZcAbc/8nlhbAL/bCQRCVD78VtI5mdwqWkVi3wMqM94kScQCgqg==", "cpu": [ "arm64" ], @@ -3769,9 +3758,9 @@ } }, "node_modules/esbuild-darwin-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-darwin-64/-/esbuild-darwin-64-0.15.12.tgz", - "integrity": "sha512-qkmqrTVYPFiePt5qFjP8w/S+GIUMbt6k8qmiPraECUWfPptaPJUGkCKrWEfYFRWB7bY23FV95rhvPyh/KARP8Q==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-darwin-64/-/esbuild-darwin-64-0.15.14.tgz", + "integrity": "sha512-ToNuf1uifu8hhwWvoZJGCdLIX/1zpo8cOGnT0XAhDQXiKOKYaotVNx7pOVB1f+wHoWwTLInrOmh3EmA7Fd+8Vg==", "cpu": [ "x64" ], @@ -3784,9 +3773,9 @@ } }, "node_modules/esbuild-darwin-arm64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.15.12.tgz", - "integrity": "sha512-z4zPX02tQ41kcXMyN3c/GfZpIjKoI/BzHrdKUwhC/Ki5BAhWv59A9M8H+iqaRbwpzYrYidTybBwiZAIWCLJAkw==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.15.14.tgz", + "integrity": "sha512-KgGP+y77GszfYJgceO0Wi/PiRtYo5y2Xo9rhBUpxTPaBgWDJ14gqYN0+NMbu+qC2fykxXaipHxN4Scaj9tUS1A==", "cpu": [ "arm64" ], @@ -3799,9 +3788,9 @@ } }, "node_modules/esbuild-freebsd-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-freebsd-64/-/esbuild-freebsd-64-0.15.12.tgz", - "integrity": "sha512-XFL7gKMCKXLDiAiBjhLG0XECliXaRLTZh6hsyzqUqPUf/PY4C6EJDTKIeqqPKXaVJ8+fzNek88285krSz1QECw==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-64/-/esbuild-freebsd-64-0.15.14.tgz", + "integrity": "sha512-xr0E2n5lyWw3uFSwwUXHc0EcaBDtsal/iIfLioflHdhAe10KSctV978Te7YsfnsMKzcoGeS366+tqbCXdqDHQA==", "cpu": [ "x64" ], @@ -3814,9 +3803,9 @@ } }, "node_modules/esbuild-freebsd-arm64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.15.12.tgz", - "integrity": "sha512-jwEIu5UCUk6TjiG1X+KQnCGISI+ILnXzIzt9yDVrhjug2fkYzlLbl0K43q96Q3KB66v6N1UFF0r5Ks4Xo7i72g==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.15.14.tgz", + "integrity": "sha512-8XH96sOQ4b1LhMlO10eEWOjEngmZ2oyw3pW4o8kvBcpF6pULr56eeYVP5radtgw54g3T8nKHDHYEI5AItvskZg==", "cpu": [ "arm64" ], @@ -3829,9 +3818,9 @@ } }, "node_modules/esbuild-linux-32": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-32/-/esbuild-linux-32-0.15.12.tgz", - "integrity": "sha512-uSQuSEyF1kVzGzuIr4XM+v7TPKxHjBnLcwv2yPyCz8riV8VUCnO/C4BF3w5dHiVpCd5Z1cebBtZJNlC4anWpwA==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-32/-/esbuild-linux-32-0.15.14.tgz", + "integrity": "sha512-6ssnvwaTAi8AzKN8By2V0nS+WF5jTP7SfuK6sStGnDP7MCJo/4zHgM9oE1eQTS2jPmo3D673rckuCzRlig+HMA==", "cpu": [ "ia32" ], @@ -3844,9 +3833,9 @@ } }, "node_modules/esbuild-linux-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.15.12.tgz", - "integrity": "sha512-QcgCKb7zfJxqT9o5z9ZUeGH1k8N6iX1Y7VNsEi5F9+HzN1OIx7ESxtQXDN9jbeUSPiRH1n9cw6gFT3H4qbdvcA==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.15.14.tgz", + "integrity": "sha512-ONySx3U0wAJOJuxGUlXBWxVKFVpWv88JEv0NZ6NlHknmDd1yCbf4AEdClSgLrqKQDXYywmw4gYDvdLsS6z0hcw==", "cpu": [ "x64" ], @@ -3859,9 +3848,9 @@ } }, "node_modules/esbuild-linux-arm": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-arm/-/esbuild-linux-arm-0.15.12.tgz", - "integrity": "sha512-Wf7T0aNylGcLu7hBnzMvsTfEXdEdJY/hY3u36Vla21aY66xR0MS5I1Hw8nVquXjTN0A6fk/vnr32tkC/C2lb0A==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm/-/esbuild-linux-arm-0.15.14.tgz", + "integrity": "sha512-D2LImAIV3QzL7lHURyCHBkycVFbKwkDb1XEUWan+2fb4qfW7qAeUtul7ZIcIwFKZgPcl+6gKZmvLgPSj26RQ2Q==", "cpu": [ "arm" ], @@ -3874,9 +3863,9 @@ } }, "node_modules/esbuild-linux-arm64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-arm64/-/esbuild-linux-arm64-0.15.12.tgz", - "integrity": "sha512-HtNq5xm8fUpZKwWKS2/YGwSfTF+339L4aIA8yphNKYJckd5hVdhfdl6GM2P3HwLSCORS++++7++//ApEwXEuAQ==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm64/-/esbuild-linux-arm64-0.15.14.tgz", + "integrity": "sha512-kle2Ov6a1e5AjlHlMQl1e+c4myGTeggrRzArQFmWp6O6JoqqB9hT+B28EW4tjFWgV/NxUq46pWYpgaWXsXRPAg==", "cpu": [ "arm64" ], @@ -3889,9 +3878,9 @@ } }, "node_modules/esbuild-linux-mips64le": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.15.12.tgz", - "integrity": "sha512-Qol3+AvivngUZkTVFgLpb0H6DT+N5/zM3V1YgTkryPYFeUvuT5JFNDR3ZiS6LxhyF8EE+fiNtzwlPqMDqVcc6A==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.15.14.tgz", + "integrity": "sha512-FVdMYIzOLXUq+OE7XYKesuEAqZhmAIV6qOoYahvUp93oXy0MOVTP370ECbPfGXXUdlvc0TNgkJa3YhEwyZ6MRA==", "cpu": [ "mips64el" ], @@ -3904,9 +3893,9 @@ } }, "node_modules/esbuild-linux-ppc64le": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.15.12.tgz", - "integrity": "sha512-4D8qUCo+CFKaR0cGXtGyVsOI7w7k93Qxb3KFXWr75An0DHamYzq8lt7TNZKoOq/Gh8c40/aKaxvcZnTgQ0TJNg==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.15.14.tgz", + "integrity": "sha512-2NzH+iuzMDA+jjtPjuIz/OhRDf8tzbQ1tRZJI//aT25o1HKc0reMMXxKIYq/8nSHXiJSnYV4ODzTiv45s+h73w==", "cpu": [ "ppc64" ], @@ -3919,9 +3908,9 @@ } }, "node_modules/esbuild-linux-riscv64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-riscv64/-/esbuild-linux-riscv64-0.15.12.tgz", - "integrity": "sha512-G9w6NcuuCI6TUUxe6ka0enjZHDnSVK8bO+1qDhMOCtl7Tr78CcZilJj8SGLN00zO5iIlwNRZKHjdMpfFgNn1VA==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-riscv64/-/esbuild-linux-riscv64-0.15.14.tgz", + "integrity": "sha512-VqxvutZNlQxmUNS7Ac+aczttLEoHBJ9e3OYGqnULrfipRvG97qLrAv9EUY9iSrRKBqeEbSvS9bSfstZqwz0T4Q==", "cpu": [ "riscv64" ], @@ -3934,9 +3923,9 @@ } }, "node_modules/esbuild-linux-s390x": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-s390x/-/esbuild-linux-s390x-0.15.12.tgz", - "integrity": "sha512-Lt6BDnuXbXeqSlVuuUM5z18GkJAZf3ERskGZbAWjrQoi9xbEIsj/hEzVnSAFLtkfLuy2DE4RwTcX02tZFunXww==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-s390x/-/esbuild-linux-s390x-0.15.14.tgz", + "integrity": "sha512-+KVHEUshX5n6VP6Vp/AKv9fZIl5kr2ph8EUFmQUJnDpHwcfTSn2AQgYYm0HTBR2Mr4d0Wlr0FxF/Cs5pbFgiOw==", "cpu": [ "s390x" ], @@ -3968,9 +3957,9 @@ } }, "node_modules/esbuild-netbsd-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-netbsd-64/-/esbuild-netbsd-64-0.15.12.tgz", - "integrity": "sha512-jlUxCiHO1dsqoURZDQts+HK100o0hXfi4t54MNRMCAqKGAV33JCVvMplLAa2FwviSojT/5ZG5HUfG3gstwAG8w==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-netbsd-64/-/esbuild-netbsd-64-0.15.14.tgz", + "integrity": "sha512-6D/dr17piEgevIm1xJfZP2SjB9Z+g8ERhNnBdlZPBWZl+KSPUKLGF13AbvC+nzGh8IxOH2TyTIdRMvKMP0nEzQ==", "cpu": [ "x64" ], @@ -3983,9 +3972,9 @@ } }, "node_modules/esbuild-openbsd-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-openbsd-64/-/esbuild-openbsd-64-0.15.12.tgz", - "integrity": "sha512-1o1uAfRTMIWNOmpf8v7iudND0L6zRBYSH45sofCZywrcf7NcZA+c7aFsS1YryU+yN7aRppTqdUK1PgbZVaB1Dw==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-openbsd-64/-/esbuild-openbsd-64-0.15.14.tgz", + "integrity": "sha512-rREQBIlMibBetgr2E9Lywt2Qxv2ZdpmYahR4IUlAQ1Efv/A5gYdO0/VIN3iowDbCNTLxp0bb57Vf0LFcffD6kA==", "cpu": [ "x64" ], @@ -3998,9 +3987,9 @@ } }, "node_modules/esbuild-sunos-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-sunos-64/-/esbuild-sunos-64-0.15.12.tgz", - "integrity": "sha512-nkl251DpoWoBO9Eq9aFdoIt2yYmp4I3kvQjba3jFKlMXuqQ9A4q+JaqdkCouG3DHgAGnzshzaGu6xofGcXyPXg==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-sunos-64/-/esbuild-sunos-64-0.15.14.tgz", + "integrity": "sha512-DNVjSp/BY4IfwtdUAvWGIDaIjJXY5KI4uD82+15v6k/w7px9dnaDaJJ2R6Mu+KCgr5oklmFc0KjBjh311Gxl9Q==", "cpu": [ "x64" ], @@ -4013,9 +4002,9 @@ } }, "node_modules/esbuild-windows-32": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-windows-32/-/esbuild-windows-32-0.15.12.tgz", - "integrity": "sha512-WlGeBZHgPC00O08luIp5B2SP4cNCp/PcS+3Pcg31kdcJPopHxLkdCXtadLU9J82LCfw4TVls21A6lilQ9mzHrw==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-windows-32/-/esbuild-windows-32-0.15.14.tgz", + "integrity": "sha512-pHBWrcA+/oLgvViuG9FO3kNPO635gkoVrRQwe6ZY1S0jdET07xe2toUvQoJQ8KT3/OkxqUasIty5hpuKFLD+eg==", "cpu": [ "ia32" ], @@ -4028,9 +4017,9 @@ } }, "node_modules/esbuild-windows-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.15.12.tgz", - "integrity": "sha512-VActO3WnWZSN//xjSfbiGOSyC+wkZtI8I4KlgrTo5oHJM6z3MZZBCuFaZHd8hzf/W9KPhF0lY8OqlmWC9HO5AA==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.15.14.tgz", + "integrity": "sha512-CszIGQVk/P8FOS5UgAH4hKc9zOaFo69fe+k1rqgBHx3CSK3Opyk5lwYriIamaWOVjBt7IwEP6NALz+tkVWdFog==", "cpu": [ "x64" ], @@ -4043,9 +4032,9 @@ } }, "node_modules/esbuild-windows-arm64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-windows-arm64/-/esbuild-windows-arm64-0.15.12.tgz", - "integrity": "sha512-Of3MIacva1OK/m4zCNIvBfz8VVROBmQT+gRX6pFTLPngFYcj6TFH/12VveAqq1k9VB2l28EoVMNMUCcmsfwyuA==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-windows-arm64/-/esbuild-windows-arm64-0.15.14.tgz", + "integrity": "sha512-KW9W4psdZceaS9A7Jsgl4WialOznSURvqX/oHZk3gOP7KbjtHLSsnmSvNdzagGJfxbAe30UVGXRe8q8nDsOSQw==", "cpu": [ "arm64" ], @@ -4162,9 +4151,9 @@ } }, "node_modules/eslint": { - "version": "8.26.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.26.0.tgz", - "integrity": "sha512-kzJkpaw1Bfwheq4VXUezFriD1GxszX6dUekM7Z3aC2o4hju+tsR/XyTC3RcoSD7jmy9VkPU3+N6YjVU2e96Oyg==", + "version": "8.28.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.28.0.tgz", + "integrity": "sha512-S27Di+EVyMxcHiwDrFzk8dJYAaD+/5SoWKxL1ri/71CRHsnJnRDPNt2Kzj24+MT9FDupf4aqqyqPrvI8MvQ4VQ==", "dev": true, "dependencies": { "@eslint/eslintrc": "^1.3.3", @@ -4338,24 +4327,26 @@ } }, "node_modules/eslint-plugin-unicorn": { - "version": "44.0.2", - "resolved": "https://registry.npmjs.org/eslint-plugin-unicorn/-/eslint-plugin-unicorn-44.0.2.tgz", - "integrity": "sha512-GLIDX1wmeEqpGaKcnMcqRvMVsoabeF0Ton0EX4Th5u6Kmf7RM9WBl705AXFEsns56ESkEs0uyelLuUTvz9Tr0w==", + "version": "45.0.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-unicorn/-/eslint-plugin-unicorn-45.0.0.tgz", + "integrity": "sha512-iP8cMRxXKHonKioOhnCoCcqVhoqhAp6rB+nsoLjXFDxTHz3btWMAp8xwzjHA0B1K6YV/U/Yvqn1bUXZt8sJPuQ==", "dev": true, "dependencies": { "@babel/helper-validator-identifier": "^7.19.1", - "ci-info": "^3.4.0", + "ci-info": "^3.6.1", "clean-regexp": "^1.0.0", "eslint-utils": "^3.0.0", "esquery": "^1.4.0", "indent-string": "^4.0.0", "is-builtin-module": "^3.2.0", + "jsesc": "3.0.2", "lodash": "^4.17.21", "pluralize": "^8.0.0", "read-pkg-up": "^7.0.1", "regexp-tree": "^0.1.24", + "regjsparser": "0.9.1", "safe-regex": "^2.1.1", - "semver": "^7.3.7", + "semver": "^7.3.8", "strip-indent": "^3.0.0" }, "engines": { @@ -4365,13 +4356,13 @@ "url": "https://github.com/sindresorhus/eslint-plugin-unicorn?sponsor=1" }, "peerDependencies": { - "eslint": ">=8.23.1" + "eslint": ">=8.28.0" } }, "node_modules/eslint-plugin-vue": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-vue/-/eslint-plugin-vue-9.6.0.tgz", - "integrity": "sha512-zzySkJgVbFCylnG2+9MDF7N+2Rjze2y0bF8GyUNpFOnT8mCMfqqtLDJkHBuYu9N/psW1A6DVbQhPkP92E+qakA==", + "version": "9.7.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-vue/-/eslint-plugin-vue-9.7.0.tgz", + "integrity": "sha512-DrOO3WZCZEwcLsnd3ohFwqCoipGRSTKTBTnLwdhqAbYZtzWl0o7D+D8ZhlmiZvABKTEl8AFsqH1GHGdybyoQmw==", "dev": true, "dependencies": { "eslint-utils": "^3.0.0", @@ -4461,9 +4452,9 @@ "dev": true }, "node_modules/espree": { - "version": "9.4.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.4.0.tgz", - "integrity": "sha512-DQmnRpLj7f6TgN/NYb0MTzJXL+vJF9h3pHy4JhCIs3zwcgez8xmGg3sXHcEO97BrmO2OSvCwMdfdlyl+E9KjOw==", + "version": "9.4.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.4.1.tgz", + "integrity": "sha512-XwctdmTO6SIvCzd9810yyNzIrOrqNYV9Koizx4C/mRhf9uq0o4yHoCEU/670pOxOL/MSraektvSAji79kX90Vg==", "dev": true, "dependencies": { "acorn": "^8.8.0", @@ -4552,6 +4543,11 @@ "node": ">=0.8.x" } }, + "node_modules/fast-clone": { + "version": "1.5.13", + "resolved": "https://registry.npmjs.org/fast-clone/-/fast-clone-1.5.13.tgz", + "integrity": "sha512-0ez7coyFBQFjZtId+RJqJ+EQs61w9xARfqjqK0AD9vIUkSxWD4HvPt80+5evebZ1tTnv1GYKrPTipx7kOW5ipA==" + }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -4616,6 +4612,14 @@ "reusify": "^1.0.4" } }, + "node_modules/fetch-ponyfill": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/fetch-ponyfill/-/fetch-ponyfill-7.1.0.tgz", + "integrity": "sha512-FhbbL55dj/qdVO3YNK7ZEkshvj3eQ7EuIGV2I6ic/2YiocvyWv+7jg2s4AyS0wdRU75s3tA8ZxI/xPigb0v5Aw==", + "dependencies": { + "node-fetch": "~2.6.1" + } + }, "node_modules/file-entry-cache": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", @@ -4966,9 +4970,9 @@ } }, "node_modules/globals": { - "version": "13.17.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.17.0.tgz", - "integrity": "sha512-1C+6nQRb1GwGMKm2dH/E7enFAMxGTmGI7/dEdhy/DNelv85w9B72t3uc5frtMNXIbzrarJJ/lTCjcaZwbLJmyw==", + "version": "13.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.18.0.tgz", + "integrity": "sha512-/mR4KI8Ps2spmoc0Ulu9L7agOF0du1CZNQ3dke8yItYlyKNmGrkONemBbd6V8UTc1Wgcqn21t3WYB7dbRmh6/A==", "dev": true, "dependencies": { "type-fest": "^0.20.2" @@ -5221,6 +5225,25 @@ "postcss": "^8.1.0" } }, + "node_modules/ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, "node_modules/ignore": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.0.tgz", @@ -5359,11 +5382,11 @@ } }, "node_modules/interpret": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/interpret/-/interpret-2.2.0.tgz", - "integrity": "sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-3.1.1.tgz", + "integrity": "sha512-6xwYfHbajpoF0xLW+iwLkhwgvLoZDfjYfoFNu8ftMoXINzwuymNLd9u/KmwtdT2GbR+/Cz66otEGEVVUHX9QLQ==", "engines": { - "node": ">= 0.10" + "node": ">=10.13.0" } }, "node_modules/ip": { @@ -5724,7 +5747,6 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "dev": true, "dependencies": { "argparse": "^2.0.1" }, @@ -5733,18 +5755,18 @@ } }, "node_modules/jsdom": { - "version": "20.0.1", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-20.0.1.tgz", - "integrity": "sha512-pksjj7Rqoa+wdpkKcLzQRHhJCEE42qQhl/xLMUKHgoSejaKOdaXEAnqs6uDNwMl/fciHTzKeR8Wm8cw7N+g98A==", + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-20.0.3.tgz", + "integrity": "sha512-SYhBvTh89tTfCD/CRdSOm13mOBa42iTaTyfyEWBdKcGdPxPtLFBXuHR8XHb33YNYaP+lLbmSvBTsnoesCNJEsQ==", "dev": true, "dependencies": { "abab": "^2.0.6", - "acorn": "^8.8.0", + "acorn": "^8.8.1", "acorn-globals": "^7.0.0", "cssom": "^0.5.0", "cssstyle": "^2.3.0", "data-urls": "^3.0.2", - "decimal.js": "^10.4.1", + "decimal.js": "^10.4.2", "domexception": "^4.0.0", "escodegen": "^2.0.0", "form-data": "^4.0.0", @@ -5757,12 +5779,12 @@ "saxes": "^6.0.0", "symbol-tree": "^3.2.4", "tough-cookie": "^4.1.2", - "w3c-xmlserializer": "^3.0.0", + "w3c-xmlserializer": "^4.0.0", "webidl-conversions": "^7.0.0", "whatwg-encoding": "^2.0.0", "whatwg-mimetype": "^3.0.0", "whatwg-url": "^11.0.0", - "ws": "^8.9.0", + "ws": "^8.11.0", "xml-name-validator": "^4.0.0" }, "engines": { @@ -5786,6 +5808,18 @@ "node": ">= 10.16.0" } }, + "node_modules/jsesc": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.0.2.tgz", + "integrity": "sha512-xKqzzWXDttJuOcawBt4KnKHHIf5oQ/Cxax+0PWFG+DFDgHNAdi+TXECADI+RYiFUMmx8792xsMbbgXj4CwnP4g==", + "dev": true, + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, "node_modules/json-parse-even-better-errors": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", @@ -5888,9 +5922,9 @@ } }, "node_modules/known-css-properties": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.25.0.tgz", - "integrity": "sha512-b0/9J1O9Jcyik1GC6KC42hJ41jKwdO/Mq8Mdo5sYN+IuRTXs2YFHZC3kZSx6ueusqa95x3wLYe/ytKjbAfGixA==", + "version": "0.26.0", + "resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.26.0.tgz", + "integrity": "sha512-5FZRzrZzNTBruuurWpvZnvP9pum+fe0HcK8z/ooo+U+Hmp4vtbyp1/QDsqmufirXy4egGzbaH/y2uCZf+6W5Kg==", "dev": true }, "node_modules/less": { @@ -6032,9 +6066,9 @@ } }, "node_modules/loader-utils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.3.tgz", - "integrity": "sha512-THWqIsn8QRnvLl0shHYVBN9syumU8pYWEHPTmkiVGd+7K5eFNVSY6AJhRvgGF70gg1Dz+l/k8WicvFCxdEs60A==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.4.tgz", + "integrity": "sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw==", "dependencies": { "big.js": "^5.2.2", "emojis-list": "^3.0.0", @@ -6081,24 +6115,12 @@ "resolved": "https://registry.npmjs.org/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz", "integrity": "sha512-xYHt68QRoYGjeeM/XOE1uJtvXQAgvszfBhjV4yvsQH0u2i9I6cI6c6/eG4Hh3UAOVn0y/xAXwmTzEay49Q//HA==" }, - "node_modules/lodash.get": { - "version": "4.4.2", - "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", - "integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==", - "dev": true - }, "node_modules/lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", "dev": true }, - "node_modules/lodash.set": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/lodash.set/-/lodash.set-4.3.2.tgz", - "integrity": "sha512-4hNPN5jlm/N/HLMCO43v8BXKq9Z7QdAGc/VGrRD61w8gN9g/6jF9A4L1pbUgBLCffi0w9VsXfTOij5x8iTyFvg==", - "dev": true - }, "node_modules/lodash.template": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-4.5.0.tgz", @@ -6129,9 +6151,9 @@ "dev": true }, "node_modules/loupe": { - "version": "2.3.4", - "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.4.tgz", - "integrity": "sha512-OvKfgCC2Ndby6aSTREl5aCCPTNIzlDfQZvZxNUrBrihDhL3xcrYegTblhmEiCrg2kKQz4XsFIaemE5BF4ybSaQ==", + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.6.tgz", + "integrity": "sha512-RaPMZKiMy8/JruncMU5Bt6na1eftNoo++R4Y+N2FrxkDVTrGvcyzFTsaGif4QTeKESheMGegbhw6iUAq+5A8zA==", "dev": true, "dependencies": { "get-func-name": "^2.0.0" @@ -6305,9 +6327,9 @@ } }, "node_modules/marked": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/marked/-/marked-4.1.1.tgz", - "integrity": "sha512-0cNMnTcUJPxbA6uWmCmjWz4NJRe/0Xfk2NhXCUHjew9qJzFN20krFnsUe7QynwqOwa5m1fZ4UDg0ycKFVC0ccw==", + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/marked/-/marked-4.2.3.tgz", + "integrity": "sha512-slWRdJkbTZ+PjkyJnE30Uid64eHwbwa1Q25INCAYfZlK4o6ylagBy/Le9eWntqJFoFT93ikUKMv47GZ4gTwHkw==", "bin": { "marked": "bin/marked.js" }, @@ -6434,19 +6456,23 @@ } }, "node_modules/mermaid": { - "version": "9.1.7", - "resolved": "https://registry.npmjs.org/mermaid/-/mermaid-9.1.7.tgz", - "integrity": "sha512-MRVHXy5FLjnUQUG7YS3UN9jEN6FXCJbFCXVGJQjVIbiR6Vhw0j/6pLIjqsiah9xoHmQU6DEaKOvB3S1g/1nBPA==", + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/mermaid/-/mermaid-9.2.2.tgz", + "integrity": "sha512-6s7eKMqFJGS+0MYjmx8f6ZigqKBJVoSx5ql2gw6a4Aa+WJ49QiEJg7gPwywaBg3DZMs79UP7trESp4+jmaQccw==", "dependencies": { "@braintree/sanitize-url": "^6.0.0", "d3": "^7.0.0", "dagre": "^0.8.5", "dagre-d3": "^0.6.4", "dompurify": "2.4.0", + "fast-clone": "^1.5.13", "graphlib": "^2.1.8", "khroma": "^2.0.0", - "moment-mini": "2.24.0", - "stylis": "^4.0.10" + "lodash": "^4.17.21", + "moment-mini": "^2.24.0", + "non-layered-tidy-tree-layout": "^2.0.2", + "stylis": "^4.1.2", + "uuid": "^9.0.0" } }, "node_modules/micromatch": { @@ -6502,9 +6528,9 @@ } }, "node_modules/mini-css-extract-plugin": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-2.6.1.tgz", - "integrity": "sha512-wd+SD57/K6DiV7jIR34P+s3uckTRuQvx0tKPcvjFlrEylk6P4mQ2KSWk1hblj1Kxaqok7LogKOieygXqBczNlg==", + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-2.7.0.tgz", + "integrity": "sha512-auqtVo8KhTScMsba7MbijqZTfibbXiBNlPAQbsVt7enQfcDYLdgG57eGxMqwVU3mfeWANY4F1wUg+rMF+ycZgw==", "dependencies": { "schema-utils": "^4.0.0" }, @@ -6554,9 +6580,9 @@ } }, "node_modules/moment-mini": { - "version": "2.24.0", - "resolved": "https://registry.npmjs.org/moment-mini/-/moment-mini-2.24.0.tgz", - "integrity": "sha512-9ARkWHBs+6YJIvrIp0Ik5tyTTtP9PoV0Ssu2Ocq5y9v8+NOOpWiRshAp8c4rZVWTOe+157on/5G+zj5pwIQFEQ==" + "version": "2.29.4", + "resolved": "https://registry.npmjs.org/moment-mini/-/moment-mini-2.29.4.tgz", + "integrity": "sha512-uhXpYwHFeiTbY9KSgPPRoo1nt8OxNVdMVoTBYHfSEKeRkIkwGpO+gERmhuhBtzfaeOyTkykSrm2+noJBgqt3Hg==" }, "node_modules/monaco-editor": { "version": "0.34.1", @@ -6575,6 +6601,11 @@ "webpack": "^4.5.0 || 5.x" } }, + "node_modules/moo": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.2.tgz", + "integrity": "sha512-iSAJLHYKnX41mKcJKjqvnAN9sf0LMDTXDEvFv+ffuRR9a1MIuXLjMNL6EsnDHSkKLTWNqQQ5uo61P4EbU4NU+Q==" + }, "node_modules/ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -6599,9 +6630,9 @@ "dev": true }, "node_modules/needle": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/needle/-/needle-3.1.0.tgz", - "integrity": "sha512-gCE9weDhjVGCRqS8dwDR/D3GTAeyXLXuqp7I8EzH6DllZGXSUyxuqqLh+YX9rMAWaaTFyVAg6rHGL25dqvczKw==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/needle/-/needle-3.2.0.tgz", + "integrity": "sha512-oUvzXnyLiVyVGoianLijF9O/RecZUf7TkBfimjGrLM4eQhXyeJwM6GeAWccwfQ9aa4gMCZKqhAOuLaMIcQxajQ==", "optional": true, "dependencies": { "debug": "^3.2.6", @@ -6671,7 +6702,6 @@ "version": "2.6.7", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", - "dev": true, "dependencies": { "whatwg-url": "^5.0.0" }, @@ -6690,20 +6720,17 @@ "node_modules/node-fetch/node_modules/tr46": { "version": "0.0.3", "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "dev": true + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" }, "node_modules/node-fetch/node_modules/webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "dev": true + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" }, "node_modules/node-fetch/node_modules/whatwg-url": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "dev": true, "dependencies": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" @@ -6714,6 +6741,11 @@ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.6.tgz", "integrity": "sha512-PiVXnNuFm5+iYkLBNeq5211hvO38y63T0i2KKh2KnUs3RpzJ+JtODFjkD8yjLwnDkTYF1eKXheUwdssR+NRZdg==" }, + "node_modules/non-layered-tidy-tree-layout": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/non-layered-tidy-tree-layout/-/non-layered-tidy-tree-layout-2.0.2.tgz", + "integrity": "sha512-gkXMxRzUH+PB0ax9dUN0yYF0S25BqeAYqhgMaLUFmpXLEk7Fcu8f4emJuOAY0V8kjDICxROIKsTAKsV/v355xw==" + }, "node_modules/normalize-package-data": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", @@ -6807,14 +6839,14 @@ } }, "node_modules/object.values": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.5.tgz", - "integrity": "sha512-QUZRW0ilQ3PnPpbNtgdNV1PDbEqLIiSFB3l+EnGtBQ/8SUTLj1PZwtQHABZtLgwpJZTSZhuGLOGk57Drx2IvYg==", + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.6.tgz", + "integrity": "sha512-FVVTkD1vENCsAcwNs9k6jea2uHC/X0+JcjG8YA60FN5CMaJmG95wT9jek/xX9nornqGRrBkKtzuAu2wuHpKqvw==", "dev": true, "dependencies": { "call-bind": "^1.0.2", - "define-properties": "^1.1.3", - "es-abstract": "^1.19.1" + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" }, "engines": { "node": ">= 0.4" @@ -7148,9 +7180,9 @@ } }, "node_modules/playwright-core": { - "version": "1.27.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.27.1.tgz", - "integrity": "sha512-9EmeXDncC2Pmp/z+teoVYlvmPWUC6ejSSYZUln7YaP89Z6lpAaiaAnqroUt/BoLo8tn7WYShcfaCh+xofZa44Q==", + "version": "1.28.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.28.0.tgz", + "integrity": "sha512-nJLknd28kPBiCNTbqpu6Wmkrh63OEqJSFw9xOfL9qxfNwody7h6/L3O2dZoWQ6Oxcm0VOHjWmGiCUGkc0X3VZA==", "dev": true, "bin": { "playwright": "cli.js" @@ -7178,9 +7210,9 @@ } }, "node_modules/postcss": { - "version": "8.4.18", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.18.tgz", - "integrity": "sha512-Wi8mWhncLJm11GATDaQKobXSNEYGUHeQLiQqDFG1qQ5UTDPTEvKw0Xt5NsTpktGTwLps3ByrWsBrG0rB8YQ9oA==", + "version": "8.4.19", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.19.tgz", + "integrity": "sha512-h+pbPsyhlYj6N2ozBmHhHrs9DzGmbaarbLvWipMRO7RLS+v4onj26MPFXA5OBYFxyqYhUJK456SwDcY9H2/zsA==", "funding": [ { "type": "opencollective", @@ -7296,9 +7328,9 @@ } }, "node_modules/postcss-selector-parser": { - "version": "6.0.10", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz", - "integrity": "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==", + "version": "6.0.11", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.11.tgz", + "integrity": "sha512-zbARubNdogI9j7WY4nQJBiNqQf3sLS3wCP4WfOidu+p28LofJqDH1tcXypGrcmMHhDk2t9wGhCsYe/+szLTy1g==", "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" @@ -7593,14 +7625,14 @@ } }, "node_modules/rechoir": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.7.1.tgz", - "integrity": "sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg==", + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.8.0.tgz", + "integrity": "sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ==", "dependencies": { - "resolve": "^1.9.0" + "resolve": "^1.20.0" }, "engines": { - "node": ">= 0.10" + "node": ">= 10.13.0" } }, "node_modules/redent": { @@ -7654,6 +7686,27 @@ "url": "https://github.com/sponsors/mysticatea" } }, + "node_modules/regjsparser": { + "version": "0.9.1", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.9.1.tgz", + "integrity": "sha512-dQUtn90WanSNl+7mQKcXAgZxvUe7Z0SqXlgzv0za4LwiUhyzBC58yQO3liFoUgu8GiJVInAhJjkj1N0EtQ5nkQ==", + "dev": true, + "dependencies": { + "jsesc": "~0.5.0" + }, + "bin": { + "regjsparser": "bin/parser" + } + }, + "node_modules/regjsparser/node_modules/jsesc": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", + "integrity": "sha512-uZz5UnB7u4T9LvwmFqXii7pZSouaRPorGs5who1Ip7VO0wxanFvBL7GkM6dTHlgX+jhBApRetaWpnDabOeTcnA==", + "dev": true, + "bin": { + "jsesc": "bin/jsesc" + } + }, "node_modules/require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -7979,6 +8032,15 @@ "node": ">=8" } }, + "node_modules/shortcss": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/shortcss/-/shortcss-0.1.3.tgz", + "integrity": "sha512-MIOoTd99CIGTrAuGiMUx9VZrnrZmWzEHuKbGM/w+ia/w98cezhlN9w4aQOVSxswdoqkUnWrMw3tThOi3sevZAg==", + "dev": true, + "dependencies": { + "css-shorthand-properties": "^1.0.0" + } + }, "node_modules/side-channel": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", @@ -8222,28 +8284,28 @@ } }, "node_modules/string.prototype.trimend": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.5.tgz", - "integrity": "sha512-I7RGvmjV4pJ7O3kdf+LXFpVfdNOxtCW/2C8f6jNiW4+PQchwxkCDzlk1/7p+Wl4bqFIZeF47qAHXLuHHWKAxog==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.6.tgz", + "integrity": "sha512-JySq+4mrPf9EsDBEDYMOb/lM7XQLulwg5R/m1r0PXEFqrV0qHvl58sdTilSXtKOflCsK2E8jxf+GKC0T07RWwQ==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.1.4", - "es-abstract": "^1.19.5" + "es-abstract": "^1.20.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" } }, "node_modules/string.prototype.trimstart": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.5.tgz", - "integrity": "sha512-THx16TJCGlsN0o6dl2o6ncWUsdgnLRSA23rRE5pyGBw/mLr3Ej/R2LaqCtgP8VNMGZsvMWnf9ooZPyY2bHvUFg==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.6.tgz", + "integrity": "sha512-omqjMDaY92pbn5HOX7f9IccLA+U1tA9GvtU4JrodiXFfYB7jPzzHpRzpglLAjtUV6bB557zwClJezTqnAiYnQA==", "dev": true, "dependencies": { "call-bind": "^1.0.2", "define-properties": "^1.1.4", - "es-abstract": "^1.19.5" + "es-abstract": "^1.20.4" }, "funding": { "url": "https://github.com/sponsors/ljharb" @@ -8312,15 +8374,15 @@ "dev": true }, "node_modules/stylelint": { - "version": "14.14.0", - "resolved": "https://registry.npmjs.org/stylelint/-/stylelint-14.14.0.tgz", - "integrity": "sha512-yUI+4xXfPHVnueYddSQ/e1GuEA/2wVhWQbGj16AmWLtQJtn28lVxfS4b0CsWyVRPgd3Auzi0NXOthIEUhtQmmA==", + "version": "14.15.0", + "resolved": "https://registry.npmjs.org/stylelint/-/stylelint-14.15.0.tgz", + "integrity": "sha512-JOgDAo5QRsqiOZPZO+B9rKJvBm64S0xasbuRPAbPs6/vQDgDCnZLIiw6XcAS6GQKk9k1sBWR6rmH3Mfj8OknKg==", "dev": true, "dependencies": { "@csstools/selector-specificity": "^2.0.2", "balanced-match": "^2.0.0", "colord": "^2.9.3", - "cosmiconfig": "^7.0.1", + "cosmiconfig": "^7.1.0", "css-functions-list": "^3.1.0", "debug": "^4.3.4", "fast-glob": "^3.2.12", @@ -8334,13 +8396,13 @@ "import-lazy": "^4.0.0", "imurmurhash": "^0.1.4", "is-plain-object": "^5.0.0", - "known-css-properties": "^0.25.0", + "known-css-properties": "^0.26.0", "mathml-tag-names": "^2.1.3", "meow": "^9.0.0", "micromatch": "^4.0.5", "normalize-path": "^3.0.0", "picocolors": "^1.0.0", - "postcss": "^8.4.17", + "postcss": "^8.4.19", "postcss-media-query-parser": "^0.2.3", "postcss-resolve-nested-selector": "^0.1.1", "postcss-safe-parser": "^6.0.0", @@ -8352,7 +8414,7 @@ "style-search": "^0.1.0", "supports-hyperlinks": "^2.3.0", "svg-tags": "^1.0.0", - "table": "^6.8.0", + "table": "^6.8.1", "v8-compile-cache": "^2.3.0", "write-file-atomic": "^4.0.2" }, @@ -8388,6 +8450,19 @@ "stylelint": "^14.14.0" } }, + "node_modules/stylelint-declaration-strict-value": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/stylelint-declaration-strict-value/-/stylelint-declaration-strict-value-1.9.1.tgz", + "integrity": "sha512-iIkMh2ukIfSTtJoEDgGq5cqUyYWP8NExPk2YSGcePtFikb7KmJoSi0QYajiZRxge/PTbYspci7nIcrtArJlAsw==", + "dev": true, + "dependencies": { + "css-values": "^0.1.0", + "shortcss": "^0.1.3" + }, + "peerDependencies": { + "stylelint": ">=7 <=14" + } + }, "node_modules/stylelint/node_modules/balanced-match": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-2.0.0.tgz", @@ -8404,9 +8479,9 @@ } }, "node_modules/stylis": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.1.2.tgz", - "integrity": "sha512-Nn2CCrG2ZaFziDxaZPN43CXqn+j7tcdjPFCkRBkFue8QYXC2HdEwnw5TCBo4yQZ2WxKYeSi0fdoOrtEqgDrXbA==" + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.1.3.tgz", + "integrity": "sha512-GP6WDNWf+o403jrEp9c5jibKavrtLW+/qYGhFxFrG8maXhwTBI7gLLhiBb0o7uFccWN+EOS9aMO6cGHWAO07OA==" }, "node_modules/superstruct": { "version": "0.10.13", @@ -8455,9 +8530,9 @@ "dev": true }, "node_modules/svgo": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/svgo/-/svgo-3.0.0.tgz", - "integrity": "sha512-mSqPn6RDeNqJvCeqHERlfWJjd4crP/2PgFelil9WpTwC4D3okAUopPsH3lnEyl7ONXfDVyISOihDjO0uK8YVAA==", + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/svgo/-/svgo-3.0.2.tgz", + "integrity": "sha512-Z706C1U2pb1+JGP48fbazf3KxHrWOsLme6Rv7imFBn5EnuanDW1GPaA/P1/dvObE670JDePC3mnj0k0B7P0jjQ==", "dev": true, "dependencies": { "@trysound/sax": "0.2.0", @@ -8488,9 +8563,9 @@ } }, "node_modules/swagger-ui-dist": { - "version": "4.15.0", - "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-4.15.0.tgz", - "integrity": "sha512-vAsIdNHraLuBRm1vrxcMaLk/y/PGBTvHLf4lQGQ3LaEXkORtIxw11sBMpYJL3keOLaFJ1OqNXuURd6eShoFLZQ==" + "version": "4.15.5", + "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-4.15.5.tgz", + "integrity": "sha512-V3eIa28lwB6gg7/wfNvAbjwJYmDXy1Jo1POjyTzlB6wPcHiGlRxq39TSjYGVjQrUSAzpv+a7nzp7mDxgNy57xA==" }, "node_modules/symbol-tree": { "version": "3.2.4", @@ -8498,10 +8573,22 @@ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", "dev": true }, + "node_modules/sync-fetch": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/sync-fetch/-/sync-fetch-0.4.2.tgz", + "integrity": "sha512-vilDD6yTGwyUjm7/W5WUUOCw1GH1aV591zC21XhbV6MJNZqfZcNMs9DVPHzy1UAmQ2GAg6S03F5TQ3paegKSdg==", + "dependencies": { + "buffer": "^5.7.1", + "node-fetch": "^2.6.1" + }, + "engines": { + "node": ">=14" + } + }, "node_modules/table": { - "version": "6.8.0", - "resolved": "https://registry.npmjs.org/table/-/table-6.8.0.tgz", - "integrity": "sha512-s/fitrbVeEyHKFa7mFdkuQMWlH1Wgw/yEXMt5xACT4ZpzWFluehAxRtUUQKPuWhaLAWhFcVx6w3oC8VKaUfPGA==", + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/table/-/table-6.8.1.tgz", + "integrity": "sha512-Y4X9zqrCftUhMeH2EptSSERdVKt/nEdijTOacGD/97EKjhQ/Qs8RTlEGABSJNNN8lac9kheH+af7yAkEWlgneA==", "dev": true, "dependencies": { "ajv": "^8.0.1", @@ -8755,9 +8842,9 @@ } }, "node_modules/tslib": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", - "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==" + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz", + "integrity": "sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==" }, "node_modules/type-check": { "version": "0.4.0", @@ -8867,9 +8954,9 @@ } }, "node_modules/updates": { - "version": "13.1.10", - "resolved": "https://registry.npmjs.org/updates/-/updates-13.1.10.tgz", - "integrity": "sha512-YSt1ncMoBXAQZndhLwiywvEGHXmA4424SlAf2HMUDuf8qE9Tlqj0s6IANb388HrjkybdZJkaadLSg/hkigwnuQ==", + "version": "13.2.1", + "resolved": "https://registry.npmjs.org/updates/-/updates-13.2.1.tgz", + "integrity": "sha512-d+nIbU2fl/PDEvUkbQch4uRdkXt9AQoPlH6b/FPTOAzF9voGbXgZNNxgO79Jeish24ZMfOqUl5lJcKSwMO2RJQ==", "dev": true, "bin": { "updates": "bin/updates.js" @@ -8916,6 +9003,14 @@ "node": ">= 4" } }, + "node_modules/uuid": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.0.tgz", + "integrity": "sha512-MXcSTerfPa4uqyzStbRoTgt5XIe3x5+42+q1sDuy3R5MDk66URdLMOZe5aPX/SQd+kuYAh0FdP/pO28IkQyTeg==", + "bin": { + "uuid": "dist/bin/uuid" + } + }, "node_modules/v8-compile-cache": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", @@ -8942,15 +9037,15 @@ } }, "node_modules/vite": { - "version": "3.1.8", - "resolved": "https://registry.npmjs.org/vite/-/vite-3.1.8.tgz", - "integrity": "sha512-m7jJe3nufUbuOfotkntGFupinL/fmuTNuQmiVE7cH2IZMuf4UbfbGYMUT3jVWgGYuRVLY9j8NnrRqgw5rr5QTg==", + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vite/-/vite-3.2.4.tgz", + "integrity": "sha512-Z2X6SRAffOUYTa+sLy3NQ7nlHFU100xwanq1WDwqaiFiCe+25zdxP1TfCS5ojPV2oDDcXudHIoPnI1Z/66B7Yw==", "dev": true, "dependencies": { "esbuild": "^0.15.9", - "postcss": "^8.4.16", + "postcss": "^8.4.18", "resolve": "^1.22.1", - "rollup": "~2.78.0" + "rollup": "^2.79.1" }, "bin": { "vite": "bin/vite.js" @@ -8962,12 +9057,17 @@ "fsevents": "~2.3.2" }, "peerDependencies": { + "@types/node": ">= 14", "less": "*", "sass": "*", "stylus": "*", + "sugarss": "*", "terser": "^5.4.0" }, "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, "less": { "optional": true }, @@ -8977,40 +9077,31 @@ "stylus": { "optional": true }, + "sugarss": { + "optional": true + }, "terser": { "optional": true } } }, - "node_modules/vite/node_modules/rollup": { - "version": "2.78.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.78.1.tgz", - "integrity": "sha512-VeeCgtGi4P+o9hIg+xz4qQpRl6R401LWEXBmxYKOV4zlF82lyhgh2hTZnheFUbANE8l2A41F458iwj2vEYaXJg==", - "dev": true, - "bin": { - "rollup": "dist/bin/rollup" - }, - "engines": { - "node": ">=10.0.0" - }, - "optionalDependencies": { - "fsevents": "~2.3.2" - } - }, "node_modules/vitest": { - "version": "0.24.3", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-0.24.3.tgz", - "integrity": "sha512-aM0auuPPgMSstWvr851hB74g/LKaKBzSxcG3da7ejfZbx08Y21JpZmbmDYrMTCGhVZKqTGwzcnLMwyfz2WzkhQ==", + "version": "0.25.2", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-0.25.2.tgz", + "integrity": "sha512-qqkzfzglEFbQY7IGkgSJkdOhoqHjwAao/OrphnHboeYHC5JzsVFoLCaB2lnAy8krhj7sbrFTVRApzpkTOeuDWQ==", "dev": true, "dependencies": { "@types/chai": "^4.3.3", "@types/chai-subset": "^1.3.3", "@types/node": "*", + "acorn": "^8.8.0", + "acorn-walk": "^8.2.0", "chai": "^4.3.6", "debug": "^4.3.4", "local-pkg": "^0.4.2", + "source-map": "^0.6.1", "strip-literal": "^0.4.2", - "tinybench": "^2.3.0", + "tinybench": "^2.3.1", "tinypool": "^0.3.0", "tinyspy": "^1.0.2", "vite": "^3.0.0" @@ -9066,15 +9157,15 @@ } }, "node_modules/vue": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/vue/-/vue-3.2.41.tgz", - "integrity": "sha512-uuuvnrDXEeZ9VUPljgHkqB5IaVO8SxhPpqF2eWOukVrBnRBx2THPSGQBnVRt0GrIG1gvCmFXMGbd7FqcT1ixNQ==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.2.45.tgz", + "integrity": "sha512-9Nx/Mg2b2xWlXykmCwiTUCWHbWIj53bnkizBxKai1g61f2Xit700A1ljowpTIM11e3uipOeiPcSqnmBg6gyiaA==", "dependencies": { - "@vue/compiler-dom": "3.2.41", - "@vue/compiler-sfc": "3.2.41", - "@vue/runtime-dom": "3.2.41", - "@vue/server-renderer": "3.2.41", - "@vue/shared": "3.2.41" + "@vue/compiler-dom": "3.2.45", + "@vue/compiler-sfc": "3.2.45", + "@vue/runtime-dom": "3.2.45", + "@vue/server-renderer": "3.2.45", + "@vue/shared": "3.2.45" } }, "node_modules/vue-bar-graph": { @@ -9111,9 +9202,9 @@ } }, "node_modules/vue-loader": { - "version": "17.0.0", - "resolved": "https://registry.npmjs.org/vue-loader/-/vue-loader-17.0.0.tgz", - "integrity": "sha512-OWSXjrzIvbF2LtOUmxT3HYgwwubbfFelN8PAP9R9dwpIkj48TVioHhWWSx7W7fk+iF5cgg3CBJRxwTdtLU4Ecg==", + "version": "17.0.1", + "resolved": "https://registry.npmjs.org/vue-loader/-/vue-loader-17.0.1.tgz", + "integrity": "sha512-/OOyugJnImKCkAKrAvdsWMuwoCqGxWT5USLsjohzWbMgOwpA5wQmzQiLMzZd7DjhIfunzAGIApTOgIylz/kwcg==", "dependencies": { "chalk": "^4.1.0", "hash-sum": "^2.0.0", @@ -9121,6 +9212,14 @@ }, "peerDependencies": { "webpack": "^4.1.0 || ^5.0.0-0" + }, + "peerDependenciesMeta": { + "@vue/compiler-sfc": { + "optional": true + }, + "vue": { + "optional": true + } } }, "node_modules/vue3-calendar-heatmap": { @@ -9138,15 +9237,15 @@ } }, "node_modules/w3c-xmlserializer": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-3.0.0.tgz", - "integrity": "sha512-3WFqGEgSXIyGhOmAFtlicJNMjEps8b1MG31NCA0/vOF9+nKMUW1ckhi9cnNHmf88Rzw5V+dwIwsm2C7X8k9aQg==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-4.0.0.tgz", + "integrity": "sha512-d+BFHzbiCx6zGfz0HyQ6Rg69w9k19nviJspaj4yNscGjrHu94sVP+aRm75yEbCh+r2/yR+7q6hux9LVtbuTGBw==", "dev": true, "dependencies": { "xml-name-validator": "^4.0.0" }, "engines": { - "node": ">=12" + "node": ">=14" } }, "node_modules/watchpack": { @@ -9171,9 +9270,9 @@ } }, "node_modules/webpack": { - "version": "5.74.0", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.74.0.tgz", - "integrity": "sha512-A2InDwnhhGN4LYctJj6M1JEaGL7Luj6LOmyBHjcI8529cm5p6VXiTIW2sn6ffvEAKmveLzvu4jrihwXtPojlAA==", + "version": "5.75.0", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.75.0.tgz", + "integrity": "sha512-piaIaoVJlqMsPtX/+3KTTO6jfvrSYgauFVdt8cr9LTHKmcq/AMd4mhzsiP7ZF/PGRNPGA8336jldh9l2Kt2ogQ==", "dependencies": { "@types/eslint-scope": "^3.7.3", "@types/estree": "^0.0.51", @@ -9217,43 +9316,41 @@ } }, "node_modules/webpack-cli": { - "version": "4.10.0", - "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-4.10.0.tgz", - "integrity": "sha512-NLhDfH/h4O6UOy+0LSso42xvYypClINuMNBVVzX4vX98TmTaTUxwRbXdhucbFMd2qLaCTcLq/PdYrvi8onw90w==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-5.0.0.tgz", + "integrity": "sha512-AACDTo20yG+xn6HPW5xjbn2Be4KUzQPebWXsDMHwPPyKh9OnTOJgZN2Nc+g/FZKV3ObRTYsGvibAvc+5jAUrVA==", "dependencies": { "@discoveryjs/json-ext": "^0.5.0", - "@webpack-cli/configtest": "^1.2.0", - "@webpack-cli/info": "^1.5.0", - "@webpack-cli/serve": "^1.7.0", + "@webpack-cli/configtest": "^2.0.0", + "@webpack-cli/info": "^2.0.0", + "@webpack-cli/serve": "^2.0.0", "colorette": "^2.0.14", - "commander": "^7.0.0", + "commander": "^9.4.1", "cross-spawn": "^7.0.3", + "envinfo": "^7.7.3", "fastest-levenshtein": "^1.0.12", "import-local": "^3.0.2", - "interpret": "^2.2.0", - "rechoir": "^0.7.0", + "interpret": "^3.1.1", + "rechoir": "^0.8.0", "webpack-merge": "^5.7.3" }, "bin": { "webpack-cli": "bin/cli.js" }, "engines": { - "node": ">=10.13.0" + "node": ">=14.15.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/webpack" }, "peerDependencies": { - "webpack": "4.x.x || 5.x.x" + "webpack": "5.x.x" }, "peerDependenciesMeta": { "@webpack-cli/generators": { "optional": true }, - "@webpack-cli/migrate": { - "optional": true - }, "webpack-bundle-analyzer": { "optional": true }, @@ -9263,11 +9360,11 @@ } }, "node_modules/webpack-cli/node_modules/commander": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", - "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==", + "version": "9.4.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-9.4.1.tgz", + "integrity": "sha512-5EEkTNyHNGFPD2H+c/dXXfQZYa/scCKasxWcXJaWnNJ99pnQN9Vnmqow+p+PlFPE63Q6mThaZws1T+HxfpgtPw==", "engines": { - "node": ">= 10" + "node": "^12.20.0 || >=14" } }, "node_modules/webpack-merge": { @@ -9627,9 +9724,9 @@ } }, "node_modules/ws": { - "version": "8.9.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.9.0.tgz", - "integrity": "sha512-Ja7nszREasGaYUYCI2k4lCKIRTt+y7XuqVoHR44YpI49TtryyqbqvDMn5eqfW7e6HzTukDRIsXqzVHScqRcafg==", + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", + "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==", "dev": true, "engines": { "node": ">=10.0.0" @@ -9836,14 +9933,64 @@ } }, "@babel/parser": { - "version": "7.19.6", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.19.6.tgz", - "integrity": "sha512-h1IUp81s2JYJ3mRkdxJgs4UvmSsRvDrx5ICSJbPvtWYv5i1nTBGcBpnog+89rAFMwvvru6E5NUHdBe01UeSzYA==" + "version": "7.20.3", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.20.3.tgz", + "integrity": "sha512-OP/s5a94frIPXwjzEcv5S/tpQfc6XhxYUnmWpgdqMWGgYCuErA3SzozaRAMQgSZWKeTJxht9aWAkUY+0UzvOFg==" }, "@braintree/sanitize-url": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-6.0.1.tgz", - "integrity": "sha512-zr9Qs9KFQiEvMWdZesjcmRJlUck5NR+eKGS1uyKk+oYTWwlYrsoPEi6VmG6/TzBD1hKCGEimrhTgGS6hvn/xIQ==" + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@braintree/sanitize-url/-/sanitize-url-6.0.2.tgz", + "integrity": "sha512-Tbsj02wXCbqGmzdnXNk0SOF19ChhRU70BsroIi4Pm6Ehp56in6vch94mfbdQ17DozxkL3BAVjbZ4Qc1a0HFRAg==" + }, + "@citation-js/core": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/@citation-js/core/-/core-0.6.1.tgz", + "integrity": "sha512-zvVxsAP4ciVHiZ60TmKTfjui4m6xeISSp/rtIhOcvZxZ70bBfkt83+kGnuI4xRlhB/oUrZN2fC9BSRKdivSobQ==", + "requires": { + "@citation-js/date": "^0.5.0", + "@citation-js/name": "^0.4.2", + "fetch-ponyfill": "^7.1.0", + "sync-fetch": "^0.4.1" + } + }, + "@citation-js/date": { + "version": "0.5.1", + "resolved": "https://registry.npmjs.org/@citation-js/date/-/date-0.5.1.tgz", + "integrity": "sha512-1iDKAZ4ie48PVhovsOXQ+C6o55dWJloXqtznnnKy6CltJBQLIuLLuUqa8zlIvma0ZigjVjgDUhnVaNU1MErtZw==" + }, + "@citation-js/name": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@citation-js/name/-/name-0.4.2.tgz", + "integrity": "sha512-brSPsjs2fOVzSnARLKu0qncn6suWjHVQtrqSUrnqyaRH95r/Ad4wPF5EsoWr+Dx8HzkCGb/ogmoAzfCsqlTwTQ==" + }, + "@citation-js/plugin-bibtex": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/@citation-js/plugin-bibtex/-/plugin-bibtex-0.6.1.tgz", + "integrity": "sha512-JMw9h9MUXH7YWvgN0j+A5xI4Fw3cHYcDMzpweeAcXBfjfnC6q30Dyvs2YxfUxNEKvWDgRQjAiNNIzgWXs9uK1Q==", + "requires": { + "@citation-js/date": "^0.5.0", + "@citation-js/name": "^0.4.2", + "moo": "^0.5.1" + } + }, + "@citation-js/plugin-csl": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/@citation-js/plugin-csl/-/plugin-csl-0.6.4.tgz", + "integrity": "sha512-RG4NrFIx0CZTfNeMCC8CL7UGFRiUv5/bNd/Nc6Q/NHx0cS/tYDQcKt0M24dpOI7PAZwVoddbDW4Iakn6nS4QsQ==", + "requires": { + "@citation-js/date": "^0.5.0", + "citeproc": "^2.4.6" + } + }, + "@citation-js/plugin-software-formats": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@citation-js/plugin-software-formats/-/plugin-software-formats-0.6.0.tgz", + "integrity": "sha512-l0Vp2h9UNlqsGMgrJulA92csgu8l3WhhBC0F2nFl76aTMOrMzC9/DX1G2Ob5tUQvPfuy4B5ZZsYPJNTJdtPVhw==", + "requires": { + "@citation-js/date": "^0.5.0", + "@citation-js/name": "^0.4.2", + "js-yaml": "^4.0.0" + } }, "@claviska/jquery-minicolors": { "version": "2.3.6", @@ -9864,15 +10011,15 @@ "integrity": "sha512-dBVuXR082gk3jsFp7Rd/JI4kytwGHecnCoTtXFb7DB6CNHp4rg5k1bhg0nWdLGLnOV71lmDzGQaLMy8iPLY0pw==" }, "@esbuild/android-arm": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.15.12.tgz", - "integrity": "sha512-IC7TqIqiyE0MmvAhWkl/8AEzpOtbhRNDo7aph47We1NbE5w2bt/Q+giAhe0YYeVpYnIhGMcuZY92qDK6dQauvA==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.15.14.tgz", + "integrity": "sha512-+Rb20XXxRGisNu2WmNKk+scpanb7nL5yhuI1KR9wQFiC43ddPj/V1fmNyzlFC9bKiG4mYzxW7egtoHVcynr+OA==", "optional": true }, "@esbuild/linux-loong64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.15.12.tgz", - "integrity": "sha512-tZEowDjvU7O7I04GYvWQOS4yyP9E/7YlsB0jjw1Ycukgr2ycEzKyIk5tms5WnLBymaewc6VmRKnn5IJWgK4eFw==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.15.14.tgz", + "integrity": "sha512-eQi9rosGNVQFJyJWV0HCA5WZae/qWIQME7s8/j8DMvnylfBv62Pbu+zJ2eUDqNf2O4u3WB+OEXyfkpBoe194sg==", "optional": true }, "@eslint/eslintrc": { @@ -9913,14 +10060,14 @@ } }, "@humanwhocodes/config-array": { - "version": "0.11.6", - "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.6.tgz", - "integrity": "sha512-jJr+hPTJYKyDILJfhNSHsjiwXYf26Flsz8DvNndOsHs5pwSnpGUEy8yzF0JYhCEvTDdV2vuOK5tt8BVhwO5/hg==", + "version": "0.11.7", + "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.11.7.tgz", + "integrity": "sha512-kBbPWzN8oVMLb0hOUYXhmxggL/1cJE6ydvjDIGi9EnAGUyA7cLVKQg+d/Dsm+KZwx2czGHrCmMVLiyg8s5JPKw==", "dev": true, "requires": { "@humanwhocodes/object-schema": "^1.2.1", "debug": "^4.1.1", - "minimatch": "^3.0.4" + "minimatch": "^3.0.5" } }, "@humanwhocodes/module-importer": { @@ -10029,13 +10176,13 @@ } }, "@playwright/test": { - "version": "1.27.1", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.27.1.tgz", - "integrity": "sha512-mrL2q0an/7tVqniQQF6RBL2saskjljXzqNcCOVMUjRIgE6Y38nCNaP+Dc2FBW06bcpD3tqIws/HT9qiMHbNU0A==", + "version": "1.28.0", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.28.0.tgz", + "integrity": "sha512-vrHs5DFTPwYox5SGKq/7TDn/S4q6RA1zArd7uhO6EyP9hj3XgZBBM12ktMbnDQNxh/fL1IUKsTNLxihmsU38lQ==", "dev": true, "requires": { "@types/node": "*", - "playwright-core": "1.27.1" + "playwright-core": "1.28.0" } }, "@popperjs/core": { @@ -10044,17 +10191,17 @@ "integrity": "sha512-50/17A98tWUfQ176raKiOGXuYpLyyVMkxxG6oylzL3BPOlA6ADGdK7EYunSa4I064xerltq9TGXs8HmOk5E+vw==" }, "@primer/octicons": { - "version": "17.7.0", - "resolved": "https://registry.npmjs.org/@primer/octicons/-/octicons-17.7.0.tgz", - "integrity": "sha512-J5cVJDhExmqLGLWu8zHTOqcC8g1rQL7QzQZdbvHxW85u8ya82GtF5F68uHMDI5En3fsMlbkkF8Rz6dCaV3r+KA==", + "version": "17.9.0", + "resolved": "https://registry.npmjs.org/@primer/octicons/-/octicons-17.9.0.tgz", + "integrity": "sha512-B6y3VxPrF6U+GUjZR883NsstI7v/Qcup9puDG+fOJvCm8b7UXNl46TbRrctMCZnYlyIzUF3/SgjJhr5od/Y6sw==", "requires": { "object-assign": "^4.1.1" } }, "@rollup/plugin-commonjs": { - "version": "20.0.0", - "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-20.0.0.tgz", - "integrity": "sha512-5K0g5W2Ol8hAcTHqcTBHiA7M58tfmYi1o9KxeJuuRNpGaTa5iLjcyemBitCBcKXaHamOBBEH2dGom6v6Unmqjg==", + "version": "22.0.2", + "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-22.0.2.tgz", + "integrity": "sha512-//NdP6iIwPbMTcazYsiBMbJW7gfmpHom33u1beiIoHDEM0Q9clvtQB1T0efvMqHeKsGohiHo97BCPCkBXdscwg==", "dev": true, "requires": { "@rollup/pluginutils": "^3.1.0", @@ -10115,13 +10262,14 @@ } }, "@stoplight/json": { - "version": "3.17.0", - "resolved": "https://registry.npmjs.org/@stoplight/json/-/json-3.17.0.tgz", - "integrity": "sha512-WW0z2bb0D4t8FTl+zNTCu46J8lEOsrUhBPgwEYQ3Ri2Y0MiRE4U1/9ZV8Ki+pIJznZgY9i42bbFwOBxyZn5/6w==", + "version": "3.20.1", + "resolved": "https://registry.npmjs.org/@stoplight/json/-/json-3.20.1.tgz", + "integrity": "sha512-FXfud+uWgIj1xv6nUO9WnmgmnVikaxJcbtR4XQt4C42n5c2qua3U05Z/3B57hP5TJRSj+tpn9ID6/bFeyYYlEg==", "dev": true, "requires": { - "@stoplight/ordered-object-literal": "^1.0.2", - "@stoplight/types": "^12.3.0", + "@stoplight/ordered-object-literal": "^1.0.3", + "@stoplight/path": "^1.3.2", + "@stoplight/types": "^13.6.0", "jsonc-parser": "~2.2.1", "lodash": "^4.17.21", "safe-stable-stringify": "^1.1" @@ -10146,22 +10294,21 @@ } }, "@stoplight/json-ref-resolver": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/@stoplight/json-ref-resolver/-/json-ref-resolver-3.1.3.tgz", - "integrity": "sha512-SgoKXwVnlpIZUyAFX4W79eeuTWvXmNlMfICZixL16GZXnkjcW+uZnfmAU0ZIjcnaTgaI4mjfxn8LAP2KR6Cr0A==", + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/@stoplight/json-ref-resolver/-/json-ref-resolver-3.1.4.tgz", + "integrity": "sha512-842JVmMsi++qpDuIX+JpQvK7YY8FXEZZb+/z4xuRfStOAVEryJT/tbgGOWxniSdxEl9Eni5D/I2afMyy6BuiNw==", "dev": true, "requires": { "@stoplight/json": "^3.17.0", "@stoplight/path": "^1.3.2", - "@stoplight/types": "^12.3.0", - "@types/urijs": "^1.19.16", + "@stoplight/types": "^12.3.0 || ^13.0.0", + "@types/urijs": "^1.19.19", "dependency-graph": "~0.11.0", "fast-memoize": "^2.5.2", "immer": "^9.0.6", - "lodash.get": "^4.4.2", - "lodash.set": "^4.3.2", + "lodash": "^4.17.21", "tslib": "^2.3.1", - "urijs": "^1.19.6" + "urijs": "^1.19.11" } }, "@stoplight/ordered-object-literal": { @@ -10177,22 +10324,21 @@ "dev": true }, "@stoplight/spectral-cli": { - "version": "6.5.1", - "resolved": "https://registry.npmjs.org/@stoplight/spectral-cli/-/spectral-cli-6.5.1.tgz", - "integrity": "sha512-+qpwsDG2jQ4ULQmegBWonI3UnF6tUh351WDnV1GU8acl8eaeKbS+ZUNBgoP2f9tnMTfITdctVRFEGC3D6P7f9g==", + "version": "6.6.0", + "resolved": "https://registry.npmjs.org/@stoplight/spectral-cli/-/spectral-cli-6.6.0.tgz", + "integrity": "sha512-z46fnrvraaWMio8Y9RYYkLO+XdmtxOWpy5qNJF3CsmWua0FZ4iOTryb5Cm3GkB0wEtqxNUCBUHvoo4hS6Noyqg==", "dev": true, "requires": { - "@rollup/plugin-commonjs": "^20.0.0", - "@stoplight/json": "3.17.0", + "@stoplight/json": "~3.20.1", "@stoplight/path": "1.3.2", - "@stoplight/spectral-core": "^1.5.1", - "@stoplight/spectral-parsers": "^1.0.1", - "@stoplight/spectral-ref-resolver": "1.0.1", - "@stoplight/spectral-ruleset-bundler": "^1.0.0", - "@stoplight/spectral-ruleset-migrator": "^1.5.0", + "@stoplight/spectral-core": "^1.15.1", + "@stoplight/spectral-parsers": "^1.0.2", + "@stoplight/spectral-ref-resolver": "1.0.2", + "@stoplight/spectral-ruleset-bundler": "^1.4.0", + "@stoplight/spectral-ruleset-migrator": "^1.9.0", "@stoplight/spectral-rulesets": ">=1", - "@stoplight/spectral-runtime": "^1.1.0", - "@stoplight/types": "12.3.0", + "@stoplight/spectral-runtime": "^1.1.2", + "@stoplight/types": "^13.6.0", "chalk": "4.1.2", "cliui": "7.0.4", "eol": "0.9.1", @@ -10232,9 +10378,9 @@ } }, "@stoplight/spectral-core": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/@stoplight/spectral-core/-/spectral-core-1.15.0.tgz", - "integrity": "sha512-+DwK8SmnujMZJaxJeNU11vWY+DFOnt4oQM1TzAuvufdd3Y6Lsno88Jl31OaR1M9Fn7l/u3v1anBB/SSl/fI5rQ==", + "version": "1.15.1", + "resolved": "https://registry.npmjs.org/@stoplight/spectral-core/-/spectral-core-1.15.1.tgz", + "integrity": "sha512-IZV8L1Hyz9759KdqJIA90W5uvurHplMmaPPIZjQzG2Bq/39kN/sbLA/Js8uOf3xB9cHBbG599t4AB+uGsI8t0g==", "dev": true, "requires": { "@stoplight/better-ajv-errors": "1.0.3", @@ -10249,7 +10395,6 @@ "ajv": "^8.6.0", "ajv-errors": "~3.0.0", "ajv-formats": "~2.1.0", - "blueimp-md5": "2.18.0", "es-aggregate-error": "^1.0.7", "jsonpath-plus": "7.1.0", "lodash": "~4.17.21", @@ -10261,20 +10406,6 @@ "tslib": "^2.3.0" }, "dependencies": { - "@stoplight/json": { - "version": "3.20.1", - "resolved": "https://registry.npmjs.org/@stoplight/json/-/json-3.20.1.tgz", - "integrity": "sha512-FXfud+uWgIj1xv6nUO9WnmgmnVikaxJcbtR4XQt4C42n5c2qua3U05Z/3B57hP5TJRSj+tpn9ID6/bFeyYYlEg==", - "dev": true, - "requires": { - "@stoplight/ordered-object-literal": "^1.0.3", - "@stoplight/path": "^1.3.2", - "@stoplight/types": "^13.6.0", - "jsonc-parser": "~2.2.1", - "lodash": "^4.17.21", - "safe-stable-stringify": "^1.1" - } - }, "@stoplight/types": { "version": "13.6.0", "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.6.0.tgz", @@ -10316,32 +10447,6 @@ "ajv-formats": "~2.1.0", "lodash": "~4.17.21", "tslib": "^2.3.0" - }, - "dependencies": { - "@stoplight/json": { - "version": "3.20.1", - "resolved": "https://registry.npmjs.org/@stoplight/json/-/json-3.20.1.tgz", - "integrity": "sha512-FXfud+uWgIj1xv6nUO9WnmgmnVikaxJcbtR4XQt4C42n5c2qua3U05Z/3B57hP5TJRSj+tpn9ID6/bFeyYYlEg==", - "dev": true, - "requires": { - "@stoplight/ordered-object-literal": "^1.0.3", - "@stoplight/path": "^1.3.2", - "@stoplight/types": "^13.6.0", - "jsonc-parser": "~2.2.1", - "lodash": "^4.17.21", - "safe-stable-stringify": "^1.1" - } - }, - "@stoplight/types": { - "version": "13.7.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.7.0.tgz", - "integrity": "sha512-7ePIccfTxjEhruv8VrkDv5whP5qd9ijRzAWEbjYpUYnDfaqPTfq8/wMMjMCAKIecboxsAVD9LZy/3puXddGsDQ==", - "dev": true, - "requires": { - "@types/json-schema": "^7.0.4", - "utility-types": "^3.10.0" - } - } } }, "@stoplight/spectral-parsers": { @@ -10354,51 +10459,25 @@ "@stoplight/types": "^13.6.0", "@stoplight/yaml": "~4.2.3", "tslib": "^2.3.1" - }, - "dependencies": { - "@stoplight/json": { - "version": "3.20.1", - "resolved": "https://registry.npmjs.org/@stoplight/json/-/json-3.20.1.tgz", - "integrity": "sha512-FXfud+uWgIj1xv6nUO9WnmgmnVikaxJcbtR4XQt4C42n5c2qua3U05Z/3B57hP5TJRSj+tpn9ID6/bFeyYYlEg==", - "dev": true, - "requires": { - "@stoplight/ordered-object-literal": "^1.0.3", - "@stoplight/path": "^1.3.2", - "@stoplight/types": "^13.6.0", - "jsonc-parser": "~2.2.1", - "lodash": "^4.17.21", - "safe-stable-stringify": "^1.1" - } - }, - "@stoplight/types": { - "version": "13.7.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.7.0.tgz", - "integrity": "sha512-7ePIccfTxjEhruv8VrkDv5whP5qd9ijRzAWEbjYpUYnDfaqPTfq8/wMMjMCAKIecboxsAVD9LZy/3puXddGsDQ==", - "dev": true, - "requires": { - "@types/json-schema": "^7.0.4", - "utility-types": "^3.10.0" - } - } } }, "@stoplight/spectral-ref-resolver": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@stoplight/spectral-ref-resolver/-/spectral-ref-resolver-1.0.1.tgz", - "integrity": "sha512-0tY7nTOccvTsa3c4QbSWfJ8wGfPO1RXvmKnmBjuyLfoTMNuhkHPII9gKhCjygsshzsBLxs2IyRHZYhWYVnEbCA==", + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@stoplight/spectral-ref-resolver/-/spectral-ref-resolver-1.0.2.tgz", + "integrity": "sha512-ah6NIB/O1EdEaEu89So3LmtbKRXPVnSElgQ7oBRE9S4/VOedSqyXn+qqMd40tGnO2CsKgZaFUYXdSEHOshpHYw==", "dev": true, "requires": { "@stoplight/json-ref-readers": "1.2.2", - "@stoplight/json-ref-resolver": "3.1.3", - "@stoplight/spectral-runtime": "^1.0.0", + "@stoplight/json-ref-resolver": "~3.1.4", + "@stoplight/spectral-runtime": "^1.1.2", "dependency-graph": "0.11.0", "tslib": "^2.3.1" } }, "@stoplight/spectral-ruleset-bundler": { - "version": "1.3.3", - "resolved": "https://registry.npmjs.org/@stoplight/spectral-ruleset-bundler/-/spectral-ruleset-bundler-1.3.3.tgz", - "integrity": "sha512-hfHl7XZeF/wWMpSrsLqLnH2GevRHjSIqtBL2aRjO2SjMCTbO9LVz80p4sYaxrCcu4wQ6K71gMZXsG687+3fAeg==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@stoplight/spectral-ruleset-bundler/-/spectral-ruleset-bundler-1.4.0.tgz", + "integrity": "sha512-aYDI4a145IXED+6jvRjj9Ha0fnB+s54cr8KbQbPCEyhCHW1cP8UGVeOuwAfk+9C4ZIg40OuYrugN5EhA35oQtA==", "dev": true, "requires": { "@rollup/plugin-commonjs": "~22.0.2", @@ -10417,64 +10496,12 @@ "rollup": "~2.79.0", "tslib": "^2.3.1", "validate-npm-package-name": "3.0.0" - }, - "dependencies": { - "@rollup/plugin-commonjs": { - "version": "22.0.2", - "resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-22.0.2.tgz", - "integrity": "sha512-//NdP6iIwPbMTcazYsiBMbJW7gfmpHom33u1beiIoHDEM0Q9clvtQB1T0efvMqHeKsGohiHo97BCPCkBXdscwg==", - "dev": true, - "requires": { - "@rollup/pluginutils": "^3.1.0", - "commondir": "^1.0.1", - "estree-walker": "^2.0.1", - "glob": "^7.1.6", - "is-reference": "^1.2.1", - "magic-string": "^0.25.7", - "resolve": "^1.17.0" - } - }, - "@rollup/pluginutils": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-3.1.0.tgz", - "integrity": "sha512-GksZ6pr6TpIjHm8h9lSQ8pi8BE9VeubNT0OMJ3B5uZJ8pz73NPiqOtCog/x2/QzM1ENChPKxMDhiQuRHsqc+lg==", - "dev": true, - "requires": { - "@types/estree": "0.0.39", - "estree-walker": "^1.0.1", - "picomatch": "^2.2.2" - }, - "dependencies": { - "estree-walker": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-1.0.1.tgz", - "integrity": "sha512-1fMXF3YP4pZZVozF8j/ZLfvnR8NSIljt56UhbZ5PeeDmmGHpgpdwQt7ITlGvYaQukCvuBRMLEiKiYC+oeIg4cg==", - "dev": true - } - } - }, - "@stoplight/types": { - "version": "13.7.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.7.0.tgz", - "integrity": "sha512-7ePIccfTxjEhruv8VrkDv5whP5qd9ijRzAWEbjYpUYnDfaqPTfq8/wMMjMCAKIecboxsAVD9LZy/3puXddGsDQ==", - "dev": true, - "requires": { - "@types/json-schema": "^7.0.4", - "utility-types": "^3.10.0" - } - }, - "@types/estree": { - "version": "0.0.39", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-0.0.39.tgz", - "integrity": "sha512-EYNwp3bU+98cpU4lAWYYL7Zz+2gryWH1qbdDTidVd6hkiR6weksdbMadyXKXNPEkQFhXM+hVO9ZygomHXp+AIw==", - "dev": true - } } }, "@stoplight/spectral-ruleset-migrator": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@stoplight/spectral-ruleset-migrator/-/spectral-ruleset-migrator-1.8.0.tgz", - "integrity": "sha512-zg6RPF+d8uS7zAp5TzUph3hQG4sgGcG5Fsw8Zx24H1REyuSkjiIfyee2Kf13c3BcIlTXvnFc4csz2rNXpZO7Ug==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@stoplight/spectral-ruleset-migrator/-/spectral-ruleset-migrator-1.9.0.tgz", + "integrity": "sha512-hPSjgXsTxMQ5UV1hfkVVPknhqRjmjSnCZD5jideM4rRU5NS1fj2Pse1CiXBsRChsuAGi/2s0Ke5uuOmFFsHrxQ==", "dev": true, "requires": { "@stoplight/json": "~3.20.1", @@ -10491,32 +10518,6 @@ "reserved": "0.1.2", "tslib": "^2.3.1", "validate-npm-package-name": "3.0.0" - }, - "dependencies": { - "@stoplight/json": { - "version": "3.20.1", - "resolved": "https://registry.npmjs.org/@stoplight/json/-/json-3.20.1.tgz", - "integrity": "sha512-FXfud+uWgIj1xv6nUO9WnmgmnVikaxJcbtR4XQt4C42n5c2qua3U05Z/3B57hP5TJRSj+tpn9ID6/bFeyYYlEg==", - "dev": true, - "requires": { - "@stoplight/ordered-object-literal": "^1.0.3", - "@stoplight/path": "^1.3.2", - "@stoplight/types": "^13.6.0", - "jsonc-parser": "~2.2.1", - "lodash": "^4.17.21", - "safe-stable-stringify": "^1.1" - } - }, - "@stoplight/types": { - "version": "13.7.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.7.0.tgz", - "integrity": "sha512-7ePIccfTxjEhruv8VrkDv5whP5qd9ijRzAWEbjYpUYnDfaqPTfq8/wMMjMCAKIecboxsAVD9LZy/3puXddGsDQ==", - "dev": true, - "requires": { - "@types/json-schema": "^7.0.4", - "utility-types": "^3.10.0" - } - } } }, "@stoplight/spectral-rulesets": { @@ -10539,18 +10540,6 @@ "json-schema-traverse": "^1.0.0", "lodash": "~4.17.21", "tslib": "^2.3.0" - }, - "dependencies": { - "@stoplight/types": { - "version": "13.7.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.7.0.tgz", - "integrity": "sha512-7ePIccfTxjEhruv8VrkDv5whP5qd9ijRzAWEbjYpUYnDfaqPTfq8/wMMjMCAKIecboxsAVD9LZy/3puXddGsDQ==", - "dev": true, - "requires": { - "@types/json-schema": "^7.0.4", - "utility-types": "^3.10.0" - } - } } }, "@stoplight/spectral-runtime": { @@ -10566,12 +10555,24 @@ "lodash": "^4.17.21", "node-fetch": "^2.6.7", "tslib": "^2.3.1" + }, + "dependencies": { + "@stoplight/types": { + "version": "12.5.0", + "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-12.5.0.tgz", + "integrity": "sha512-dwqYcDrGmEyUv5TWrDam5TGOxU72ufyQ7hnOIIDdmW5ezOwZaBFoR5XQ9AsH49w7wgvOqB2Bmo799pJPWnpCbg==", + "dev": true, + "requires": { + "@types/json-schema": "^7.0.4", + "utility-types": "^3.10.0" + } + } } }, "@stoplight/types": { - "version": "12.3.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-12.3.0.tgz", - "integrity": "sha512-hgzUR1z5BlYvIzUeFK5pjs5JXSvEutA9Pww31+dVicBlunsG1iXopDx/cvfBY7rHOrgtZDuvyeK4seqkwAZ6Cg==", + "version": "13.8.0", + "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.8.0.tgz", + "integrity": "sha512-5glKswz7y9aACh+a+JegID+4xX//4TsIdv7iPl29hWnOoWrnlPbg3Gjc4nYUXXgMSaSlSsA15JU/0+rE89fR4A==", "dev": true, "requires": { "@types/json-schema": "^7.0.4", @@ -10588,18 +10589,6 @@ "@stoplight/types": "^13.0.0", "@stoplight/yaml-ast-parser": "0.0.48", "tslib": "^2.2.0" - }, - "dependencies": { - "@stoplight/types": { - "version": "13.7.0", - "resolved": "https://registry.npmjs.org/@stoplight/types/-/types-13.7.0.tgz", - "integrity": "sha512-7ePIccfTxjEhruv8VrkDv5whP5qd9ijRzAWEbjYpUYnDfaqPTfq8/wMMjMCAKIecboxsAVD9LZy/3puXddGsDQ==", - "dev": true, - "requires": { - "@types/json-schema": "^7.0.4", - "utility-types": "^3.10.0" - } - } } }, "@stoplight/yaml-ast-parser": { @@ -10626,9 +10615,9 @@ "dev": true }, "@types/chai": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.3.tgz", - "integrity": "sha512-hC7OMnszpxhZPduX+m+nrx+uFoLkWOMiR4oa/AZF3MuSETYTZmFfJAHqZEM8MVlvfG7BEUcgvtwoCTxBp6hm3g==", + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.4.tgz", + "integrity": "sha512-KnRanxnpfpjUTqTCXslZSEdLfXExwgNxYPdiO2WGUj8+HDjFi8R3k5RVKPeSCzLjCcshCAtVO2QBbVuAV4kTnw==", "dev": true }, "@types/chai-subset": { @@ -10658,9 +10647,9 @@ } }, "@types/eslint": { - "version": "8.4.7", - "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.4.7.tgz", - "integrity": "sha512-ehM7cCt2RSFs42mb+lcmhFT9ouIlV92PuaeRGn8N8c98oMjG4Z5pJHA9b1QiCcuqnbPSHcyfiD3mlhqMaHsQIw==", + "version": "8.4.10", + "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.4.10.tgz", + "integrity": "sha512-Sl/HOqN8NKPmhWo2VBEPm0nvHnu2LL3v9vKo8MEq0EtbJ4eVzGPl41VNPvn5E1i5poMk4/XD8UriLHpJvEP/Nw==", "requires": { "@types/estree": "*", "@types/json-schema": "*" @@ -10703,9 +10692,9 @@ "dev": true }, "@types/node": { - "version": "18.11.4", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.4.tgz", - "integrity": "sha512-BxcJpBu8D3kv/GZkx/gSMz6VnTJREBj/4lbzYOQueUOELkt8WrO6zAcSPmp9uRPEW/d+lUO8QK0W2xnS1hEU0A==" + "version": "18.11.9", + "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.9.tgz", + "integrity": "sha512-CRpX21/kGdzjOpFsZSkcrXMGIBWMGNIHXXBVFSH+ggkftxg+XYP20TESbh+zFvFj3EQOl5byk0HTRn1IL6hbqg==" }, "@types/normalize-package-data": { "version": "2.4.1", @@ -10734,36 +10723,36 @@ "dev": true }, "@vue/compiler-core": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.2.41.tgz", - "integrity": "sha512-oA4mH6SA78DT+96/nsi4p9DX97PHcNROxs51lYk7gb9Z4BPKQ3Mh+BLn6CQZBw857Iuhu28BfMSRHAlPvD4vlw==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-core/-/compiler-core-3.2.45.tgz", + "integrity": "sha512-rcMj7H+PYe5wBV3iYeUgbCglC+pbpN8hBLTJvRiK2eKQiWqu+fG9F+8sW99JdL4LQi7Re178UOxn09puSXvn4A==", "requires": { "@babel/parser": "^7.16.4", - "@vue/shared": "3.2.41", + "@vue/shared": "3.2.45", "estree-walker": "^2.0.2", "source-map": "^0.6.1" } }, "@vue/compiler-dom": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.2.41.tgz", - "integrity": "sha512-xe5TbbIsonjENxJsYRbDJvthzqxLNk+tb3d/c47zgREDa/PCp6/Y4gC/skM4H6PIuX5DAxm7fFJdbjjUH2QTMw==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-dom/-/compiler-dom-3.2.45.tgz", + "integrity": "sha512-tyYeUEuKqqZO137WrZkpwfPCdiiIeXYCcJ8L4gWz9vqaxzIQRccTSwSWZ/Axx5YR2z+LvpUbmPNXxuBU45lyRw==", "requires": { - "@vue/compiler-core": "3.2.41", - "@vue/shared": "3.2.41" + "@vue/compiler-core": "3.2.45", + "@vue/shared": "3.2.45" } }, "@vue/compiler-sfc": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.2.41.tgz", - "integrity": "sha512-+1P2m5kxOeaxVmJNXnBskAn3BenbTmbxBxWOtBq3mQTCokIreuMULFantBUclP0+KnzNCMOvcnKinqQZmiOF8w==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-sfc/-/compiler-sfc-3.2.45.tgz", + "integrity": "sha512-1jXDuWah1ggsnSAOGsec8cFjT/K6TMZ0sPL3o3d84Ft2AYZi2jWJgRMjw4iaK0rBfA89L5gw427H4n1RZQBu6Q==", "requires": { "@babel/parser": "^7.16.4", - "@vue/compiler-core": "3.2.41", - "@vue/compiler-dom": "3.2.41", - "@vue/compiler-ssr": "3.2.41", - "@vue/reactivity-transform": "3.2.41", - "@vue/shared": "3.2.41", + "@vue/compiler-core": "3.2.45", + "@vue/compiler-dom": "3.2.45", + "@vue/compiler-ssr": "3.2.45", + "@vue/reactivity-transform": "3.2.45", + "@vue/shared": "3.2.45", "estree-walker": "^2.0.2", "magic-string": "^0.25.7", "postcss": "^8.1.10", @@ -10771,66 +10760,66 @@ } }, "@vue/compiler-ssr": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.2.41.tgz", - "integrity": "sha512-Y5wPiNIiaMz/sps8+DmhaKfDm1xgj6GrH99z4gq2LQenfVQcYXmHIOBcs5qPwl7jaW3SUQWjkAPKMfQemEQZwQ==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/compiler-ssr/-/compiler-ssr-3.2.45.tgz", + "integrity": "sha512-6BRaggEGqhWht3lt24CrIbQSRD5O07MTmd+LjAn5fJj568+R9eUD2F7wMQJjX859seSlrYog7sUtrZSd7feqrQ==", "requires": { - "@vue/compiler-dom": "3.2.41", - "@vue/shared": "3.2.41" + "@vue/compiler-dom": "3.2.45", + "@vue/shared": "3.2.45" } }, "@vue/reactivity": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.2.41.tgz", - "integrity": "sha512-9JvCnlj8uc5xRiQGZ28MKGjuCoPhhTwcoAdv3o31+cfGgonwdPNuvqAXLhlzu4zwqavFEG5tvaoINQEfxz+l6g==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/reactivity/-/reactivity-3.2.45.tgz", + "integrity": "sha512-PRvhCcQcyEVohW0P8iQ7HDcIOXRjZfAsOds3N99X/Dzewy8TVhTCT4uXpAHfoKjVTJRA0O0K+6QNkDIZAxNi3A==", "requires": { - "@vue/shared": "3.2.41" + "@vue/shared": "3.2.45" } }, "@vue/reactivity-transform": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/reactivity-transform/-/reactivity-transform-3.2.41.tgz", - "integrity": "sha512-mK5+BNMsL4hHi+IR3Ft/ho6Za+L3FA5j8WvreJ7XzHrqkPq8jtF/SMo7tuc9gHjLDwKZX1nP1JQOKo9IEAn54A==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/reactivity-transform/-/reactivity-transform-3.2.45.tgz", + "integrity": "sha512-BHVmzYAvM7vcU5WmuYqXpwaBHjsS8T63jlKGWVtHxAHIoMIlmaMyurUSEs1Zcg46M4AYT5MtB1U274/2aNzjJQ==", "requires": { "@babel/parser": "^7.16.4", - "@vue/compiler-core": "3.2.41", - "@vue/shared": "3.2.41", + "@vue/compiler-core": "3.2.45", + "@vue/shared": "3.2.45", "estree-walker": "^2.0.2", "magic-string": "^0.25.7" } }, "@vue/runtime-core": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.2.41.tgz", - "integrity": "sha512-0LBBRwqnI0p4FgIkO9q2aJBBTKDSjzhnxrxHYengkAF6dMOjeAIZFDADAlcf2h3GDALWnblbeprYYpItiulSVQ==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/runtime-core/-/runtime-core-3.2.45.tgz", + "integrity": "sha512-gzJiTA3f74cgARptqzYswmoQx0fIA+gGYBfokYVhF8YSXjWTUA2SngRzZRku2HbGbjzB6LBYSbKGIaK8IW+s0A==", "requires": { - "@vue/reactivity": "3.2.41", - "@vue/shared": "3.2.41" + "@vue/reactivity": "3.2.45", + "@vue/shared": "3.2.45" } }, "@vue/runtime-dom": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.2.41.tgz", - "integrity": "sha512-U7zYuR1NVIP8BL6jmOqmapRAHovEFp7CSw4pR2FacqewXNGqZaRfHoNLQsqQvVQ8yuZNZtxSZy0FFyC70YXPpA==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/runtime-dom/-/runtime-dom-3.2.45.tgz", + "integrity": "sha512-cy88YpfP5Ue2bDBbj75Cb4bIEZUMM/mAkDMfqDTpUYVgTf/kuQ2VQ8LebuZ8k6EudgH8pYhsGWHlY0lcxlvTwA==", "requires": { - "@vue/runtime-core": "3.2.41", - "@vue/shared": "3.2.41", + "@vue/runtime-core": "3.2.45", + "@vue/shared": "3.2.45", "csstype": "^2.6.8" } }, "@vue/server-renderer": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.2.41.tgz", - "integrity": "sha512-7YHLkfJdTlsZTV0ae5sPwl9Gn/EGr2hrlbcS/8naXm2CDpnKUwC68i1wGlrYAfIgYWL7vUZwk2GkYLQH5CvFig==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/server-renderer/-/server-renderer-3.2.45.tgz", + "integrity": "sha512-ebiMq7q24WBU1D6uhPK//2OTR1iRIyxjF5iVq/1a5I1SDMDyDu4Ts6fJaMnjrvD3MqnaiFkKQj+LKAgz5WIK3g==", "requires": { - "@vue/compiler-ssr": "3.2.41", - "@vue/shared": "3.2.41" + "@vue/compiler-ssr": "3.2.45", + "@vue/shared": "3.2.45" } }, "@vue/shared": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.2.41.tgz", - "integrity": "sha512-W9mfWLHmJhkfAmV+7gDjcHeAWALQtgGT3JErxULl0oz6R6+3ug91I7IErs93eCFhPCZPHBs4QJS7YWEV7A3sxw==" + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/@vue/shared/-/shared-3.2.45.tgz", + "integrity": "sha512-Ewzq5Yhimg7pSztDV+RH1UDKBzmtqieXQlpTVm2AwraoRL/Rks96mvd8Vgi7Lj+h+TH8dv7mXD3FRZR3TUvbSg==" }, "@webassemblyjs/ast": { "version": "1.11.1", @@ -10964,23 +10953,21 @@ } }, "@webpack-cli/configtest": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-1.2.0.tgz", - "integrity": "sha512-4FB8Tj6xyVkyqjj1OaTqCjXYULB9FMkqQ8yGrZjRDrYh0nOE+7Lhs45WioWQQMV+ceFlE368Ukhe6xdvJM9Egg==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-2.0.0.tgz", + "integrity": "sha512-war4OU8NGjBqU3DP3bx6ciODXIh7dSXcpQq+P4K2Tqyd8L5OjZ7COx9QXx/QdCIwL2qoX09Wr4Cwf7uS4qdEng==", "requires": {} }, "@webpack-cli/info": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@webpack-cli/info/-/info-1.5.0.tgz", - "integrity": "sha512-e8tSXZpw2hPl2uMJY6fsMswaok5FdlGNRTktvFk2sD8RjH0hE2+XistawJx1vmKteh4NmGmNUrp+Tb2w+udPcQ==", - "requires": { - "envinfo": "^7.7.3" - } + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@webpack-cli/info/-/info-2.0.0.tgz", + "integrity": "sha512-NNxDgbo4VOkNhOlTgY0Elhz3vKpOJq4/PKeKg7r8cmYM+GQA9vDofLYyup8jS6EpUvhNmR30cHTCEIyvXpskwA==", + "requires": {} }, "@webpack-cli/serve": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/@webpack-cli/serve/-/serve-1.7.0.tgz", - "integrity": "sha512-oxnCNGj88fL+xzV+dacXs44HcDwf1ovs3AuEzvP7mqXw7fQntqIhQ1BRmynh4qEKQSSSRSWVyXRjmTbZIX9V2Q==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@webpack-cli/serve/-/serve-2.0.0.tgz", + "integrity": "sha512-Rumq5mHvGXamnOh3O8yLk1sjx8dB30qF1OeR6VC00DIR6SLJ4bwwUGKC4pE7qBFoQyyh0H9sAg3fikYgAqVR0w==", "requires": {} }, "@xtuc/ieee754": { @@ -11058,9 +11045,9 @@ } }, "ajv": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz", - "integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==", + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.2.tgz", + "integrity": "sha512-E4bfmKAhGiSTvMfL1Myyycaub+cUEU2/IvpylXkUu7CHBkBj1f/ikdzbD7YQ6FKUbixDxeYvB/xY4fvyroDlQg==", "requires": { "fast-deep-equal": "^3.1.1", "json-schema-traverse": "^1.0.0", @@ -11114,8 +11101,7 @@ "argparse": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" }, "array-find-index": { "version": "1.0.2", @@ -11123,15 +11109,15 @@ "integrity": "sha512-M1HQyIXcBGtVywBt8WVdim+lrNaK7VHp99Qt5pSNziXznKHViIBbXWtfRTpEFpF/c4FdfxNAsCCwPp5phBYJtw==" }, "array-includes": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.5.tgz", - "integrity": "sha512-iSDYZMMyTPkiFasVqfuAQnWAYcvO/SeBSCGKePoEthjp4LEMTe4uLc7b025o4jAZpHhihh8xPo99TNWUWWkGDQ==", + "version": "3.1.6", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.6.tgz", + "integrity": "sha512-sgTbLvL6cNnw24FnbaDyjmvddQ2ML8arZsgaJhoABMoplz/4QRhtrYS+alr1BUM1Bwp6dhx8vVCBSLG+StwOFw==", "dev": true, "requires": { "call-bind": "^1.0.2", "define-properties": "^1.1.4", - "es-abstract": "^1.19.5", - "get-intrinsic": "^1.1.1", + "es-abstract": "^1.20.4", + "get-intrinsic": "^1.1.3", "is-string": "^1.0.7" } }, @@ -11142,14 +11128,14 @@ "dev": true }, "array.prototype.flat": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.0.tgz", - "integrity": "sha512-12IUEkHsAhA4DY5s0FPgNXIdc8VRSqD9Zp78a5au9abH/SOBrsp082JOWFNTjkMozh8mqcdiKuaLGhPeYztxSw==", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.1.tgz", + "integrity": "sha512-roTU0KWIOmJ4DRLmwKd19Otg0/mT3qPNt0Qb3GWW8iObuZXxrjB/pzn0R3hqpRSWg4HCwqx+0vwOnWnvlOyeIA==", "dev": true, "requires": { "call-bind": "^1.0.2", - "define-properties": "^1.1.3", - "es-abstract": "^1.19.2", + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4", "es-shim-unscopables": "^1.0.0" } }, @@ -11206,17 +11192,16 @@ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" }, + "base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" + }, "big.js": { "version": "5.2.2", "resolved": "https://registry.npmjs.org/big.js/-/big.js-5.2.2.tgz", "integrity": "sha512-vyL2OymJxmarO8gxMr0mhChsO9QGwhynfuu4+MHTAW6czfq9humCB7rKpUjDd9YUiDPU4mzpyupFSvOClAwbmQ==" }, - "blueimp-md5": { - "version": "2.18.0", - "resolved": "https://registry.npmjs.org/blueimp-md5/-/blueimp-md5-2.18.0.tgz", - "integrity": "sha512-vE52okJvzsVWhcgUHOv+69OG3Mdg151xyn41aVQN/5W5S+S43qZhxECtYLAEHMSFWX6Mv5IZrzj3T5+JqXfj5Q==", - "dev": true - }, "boolbase": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", @@ -11251,6 +11236,15 @@ "update-browserslist-db": "^1.0.9" } }, + "buffer": { + "version": "5.7.1", + "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", + "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", + "requires": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, "buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -11308,19 +11302,19 @@ } }, "caniuse-lite": { - "version": "1.0.30001423", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001423.tgz", - "integrity": "sha512-09iwWGOlifvE1XuHokFMP7eR38a0JnajoyL3/i87c8ZjRWRrdKo1fqjNfugfBD0UDBIOz0U+jtNhJ0EPm1VleQ==" + "version": "1.0.30001431", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001431.tgz", + "integrity": "sha512-zBUoFU0ZcxpvSt9IU66dXVT/3ctO1cy4y9cscs1szkPlcWb6pasYM144GqrUygUbT+k7cmUCW61cvskjcv0enQ==" }, "chai": { - "version": "4.3.6", - "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.6.tgz", - "integrity": "sha512-bbcp3YfHCUzMOvKqsztczerVgBKSsEijCySNlHHbX3VG1nskvqjz5Rfso1gGwD6w6oOV3eI60pKuMOV5MV7p3Q==", + "version": "4.3.7", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.7.tgz", + "integrity": "sha512-HLnAzZ2iupm25PlN0xFreAlBA5zaBSv3og0DdeGA4Ar6h6rJ3A0rolRUKJhSF2V10GZKDgWF/VmAEsNWjCRB+A==", "dev": true, "requires": { "assertion-error": "^1.1.0", "check-error": "^1.0.2", - "deep-eql": "^3.0.1", + "deep-eql": "^4.1.2", "get-func-name": "^2.0.0", "loupe": "^2.3.1", "pathval": "^1.1.1", @@ -11348,11 +11342,16 @@ "integrity": "sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg==" }, "ci-info": { - "version": "3.5.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.5.0.tgz", - "integrity": "sha512-yH4RezKOGlOhxkmhbeNuC4eYZKAUsEaGtBuBzDDP1eFUKiccDWzBABxBfOx31IDwDIXMTxWuwAxUGModvkbuVw==", + "version": "3.6.1", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.6.1.tgz", + "integrity": "sha512-up5ggbaDqOqJ4UqLKZ2naVkyqSJQgJi5lwD6b6mM748ysrghDBX0bx/qJTUHzw7zu6Mq4gycviSF5hJnwceD8w==", "dev": true }, + "citeproc": { + "version": "2.4.62", + "resolved": "https://registry.npmjs.org/citeproc/-/citeproc-2.4.62.tgz", + "integrity": "sha512-l3uFfSEwNZp/jlz/TpgyBs85kOww6VlQHbAth0cpbgOn6iulZd+QlFY43LrRelzcYt3FZHTZ3soDyd8lNmkqdw==" + }, "clean-regexp": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/clean-regexp/-/clean-regexp-1.0.0.tgz", @@ -11415,9 +11414,9 @@ } }, "codemirror": { - "version": "5.65.9", - "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-5.65.9.tgz", - "integrity": "sha512-19Jox5sAKpusTDgqgKB5dawPpQcY+ipQK7xoEI+MVucEF9qqFaXpeqY1KaoyGBso/wHQoDa4HMMxMjdsS3Zzzw==" + "version": "5.65.10", + "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-5.65.10.tgz", + "integrity": "sha512-IXAG5wlhbgcTJ6rZZcmi4+sjWIbJqIGfeg3tNa3yX84Jb3T4huS5qzQAo/cUisc1l3bI47WZodpyf7cYcocDKg==" }, "codemirror-spell-checker": { "version": "1.1.2", @@ -11491,9 +11490,9 @@ "dev": true }, "cosmiconfig": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.0.1.tgz", - "integrity": "sha512-a1YWNUV2HwGimB7dU2s1wUMurNKjpx60HxBB6xUM8Re+2s1g1IIfJvFR0/iCF+XHdE0GMTKTuLR32UQff4TEyQ==", + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-7.1.0.tgz", + "integrity": "sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA==", "dev": true, "requires": { "@types/parse-json": "^4.0.0", @@ -11513,6 +11512,12 @@ "which": "^2.0.1" } }, + "css-color-names": { + "version": "0.0.4", + "resolved": "https://registry.npmjs.org/css-color-names/-/css-color-names-0.0.4.tgz", + "integrity": "sha512-zj5D7X1U2h2zsXOAM8EyUREBnnts6H+Jm+d1M2DbiQQcUtnqgQsMrdo8JW9R80YFUmIdBZeMu5wvYM7hcgWP/Q==", + "dev": true + }, "css-functions-list": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/css-functions-list/-/css-functions-list-3.1.0.tgz", @@ -11520,18 +11525,18 @@ "dev": true }, "css-loader": { - "version": "6.7.1", - "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-6.7.1.tgz", - "integrity": "sha512-yB5CNFa14MbPJcomwNh3wLThtkZgcNyI2bNMRt8iE5Z8Vwl7f8vQXFAzn2HDOJvtDq2NTZBUGMSUNNyrv3/+cw==", + "version": "6.7.2", + "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-6.7.2.tgz", + "integrity": "sha512-oqGbbVcBJkm8QwmnNzrFrWTnudnRZC+1eXikLJl0n4ljcfotgRifpg2a1lKy8jTrc4/d9A/ap1GFq1jDKG7J+Q==", "requires": { "icss-utils": "^5.1.0", - "postcss": "^8.4.7", + "postcss": "^8.4.18", "postcss-modules-extract-imports": "^3.0.0", "postcss-modules-local-by-default": "^4.0.0", "postcss-modules-scope": "^3.0.0", "postcss-modules-values": "^4.0.0", "postcss-value-parser": "^4.2.0", - "semver": "^7.3.5" + "semver": "^7.3.8" } }, "css-select": { @@ -11547,6 +11552,12 @@ "nth-check": "^2.0.1" } }, + "css-shorthand-properties": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/css-shorthand-properties/-/css-shorthand-properties-1.1.1.tgz", + "integrity": "sha512-Md+Juc7M3uOdbAFwOYlTrccIZ7oCFuzrhKYQjdeUEW/sE1hv17Jp/Bws+ReOPpGVBTYCBoYo+G17V5Qo8QQ75A==", + "dev": true + }, "css-tree": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-2.2.1.tgz", @@ -11557,6 +11568,25 @@ "source-map-js": "^1.0.1" } }, + "css-values": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/css-values/-/css-values-0.1.0.tgz", + "integrity": "sha512-hQ6JSn4t/70aOCvdlP9zTOsFFUifMSKWz3PX7rz5NZl+uEHCqTFVJJvfP07isErCGEVHYoc8Orja8wLKZRvOeg==", + "dev": true, + "requires": { + "css-color-names": "0.0.4", + "ends-with": "^0.2.0", + "postcss-value-parser": "^3.3.0" + }, + "dependencies": { + "postcss-value-parser": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-3.3.1.tgz", + "integrity": "sha512-pISE66AbVkp4fDQ7VHBwRNXzAAKJjw4Vw7nWI/+Q3vuly7SNfgYXvm6i5IgFylHGK5sP/xHAbB7N49OS4gWNyQ==", + "dev": true + } + } + }, "css-what": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz", @@ -12207,9 +12237,9 @@ "dev": true }, "decamelize-keys": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/decamelize-keys/-/decamelize-keys-1.1.0.tgz", - "integrity": "sha512-ocLWuYzRPoS9bfiSdDd3cxvrzovVMZnRDVEzAs+hWIVXGDbHxWMECij2OBuyB/An0FFW/nLuq6Kv1i/YC5Qfzg==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/decamelize-keys/-/decamelize-keys-1.1.1.tgz", + "integrity": "sha512-WiPxgEirIV0/eIOMcnFBA3/IJZAZqKnwAwWyvvdi4lsr1WCN22nhdf/3db3DoZcUjTV2SqfzIwNyp6y2xs3nmg==", "dev": true, "requires": { "decamelize": "^1.1.0", @@ -12231,9 +12261,9 @@ "dev": true }, "deep-eql": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-3.0.1.tgz", - "integrity": "sha512-+QeIQyN5ZuO+3Uk5DYh6/1eKO0m0YmJFGNmFHGACpf1ClL1nmlV/p4gNgbl2pJGxgXb4faqo6UE+M5ACEMyVcw==", + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.2.tgz", + "integrity": "sha512-gT18+YW4CcW/DBNTwAmqTtkJh7f9qqScu2qFVlx7kCoeY9tlBu9cUcr7+I+Z/noG8INehS3xQgLpTtd/QUTn4w==", "dev": true, "requires": { "type-detect": "^4.0.0" @@ -12486,6 +12516,12 @@ "resolved": "https://registry.npmjs.org/emojis-list/-/emojis-list-3.0.0.tgz", "integrity": "sha512-/kyM18EfinwXZbno9FyUGeFh87KC8HRQBQGildHZbEuRyWFOmv1U10o9BBp8XVZDVNNuQKyIGIu5ZYAAXJ0V2Q==" }, + "ends-with": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/ends-with/-/ends-with-0.2.0.tgz", + "integrity": "sha512-lRppY4dK3VkqBdR242sKcAJeYc8Gf/DhoX9AWvWI2RzccmLnqBQfwm2k4oSDv5MPDjUqawCauXhZkyWxkVhRsg==", + "dev": true + }, "enhanced-resolve": { "version": "5.10.0", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.10.0.tgz", @@ -12563,17 +12599,17 @@ } }, "es-aggregate-error": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/es-aggregate-error/-/es-aggregate-error-1.0.8.tgz", - "integrity": "sha512-AKUb5MKLWMozPlFRHOKqWD7yta5uaEhH21qwtnf6FlKjNjTJOoqFi0/G14+FfSkIQhhu6X68Af4xgRC6y8qG4A==", + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/es-aggregate-error/-/es-aggregate-error-1.0.9.tgz", + "integrity": "sha512-fvnX40sb538wdU6r4s35cq4EY6Lr09Upj40BEVem4LEsuW8XgQep9yD5Q1U2KftokNp1rWODFJ2qwZSsAjFpbg==", "dev": true, "requires": { "define-properties": "^1.1.4", - "es-abstract": "^1.19.5", + "es-abstract": "^1.20.4", "function-bind": "^1.1.1", "functions-have-names": "^1.2.3", - "get-intrinsic": "^1.1.1", - "globalthis": "^1.0.2", + "get-intrinsic": "^1.1.3", + "globalthis": "^1.0.3", "has-property-descriptors": "^1.0.0" } }, @@ -12603,116 +12639,116 @@ } }, "esbuild": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.15.12.tgz", - "integrity": "sha512-PcT+/wyDqJQsRVhaE9uX/Oq4XLrFh0ce/bs2TJh4CSaw9xuvI+xFrH2nAYOADbhQjUgAhNWC5LKoUsakm4dxng==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.15.14.tgz", + "integrity": "sha512-pJN8j42fvWLFWwSMG4luuupl2Me7mxciUOsMegKvwCmhEbJ2covUdFnihxm0FMIBV+cbwbtMoHgMCCI+pj1btQ==", "requires": { - "@esbuild/android-arm": "0.15.12", - "@esbuild/linux-loong64": "0.15.12", - "esbuild-android-64": "0.15.12", - "esbuild-android-arm64": "0.15.12", - "esbuild-darwin-64": "0.15.12", - "esbuild-darwin-arm64": "0.15.12", - "esbuild-freebsd-64": "0.15.12", - "esbuild-freebsd-arm64": "0.15.12", - "esbuild-linux-32": "0.15.12", - "esbuild-linux-64": "0.15.12", - "esbuild-linux-arm": "0.15.12", - "esbuild-linux-arm64": "0.15.12", - "esbuild-linux-mips64le": "0.15.12", - "esbuild-linux-ppc64le": "0.15.12", - "esbuild-linux-riscv64": "0.15.12", - "esbuild-linux-s390x": "0.15.12", - "esbuild-netbsd-64": "0.15.12", - "esbuild-openbsd-64": "0.15.12", - "esbuild-sunos-64": "0.15.12", - "esbuild-windows-32": "0.15.12", - "esbuild-windows-64": "0.15.12", - "esbuild-windows-arm64": "0.15.12" + "@esbuild/android-arm": "0.15.14", + "@esbuild/linux-loong64": "0.15.14", + "esbuild-android-64": "0.15.14", + "esbuild-android-arm64": "0.15.14", + "esbuild-darwin-64": "0.15.14", + "esbuild-darwin-arm64": "0.15.14", + "esbuild-freebsd-64": "0.15.14", + "esbuild-freebsd-arm64": "0.15.14", + "esbuild-linux-32": "0.15.14", + "esbuild-linux-64": "0.15.14", + "esbuild-linux-arm": "0.15.14", + "esbuild-linux-arm64": "0.15.14", + "esbuild-linux-mips64le": "0.15.14", + "esbuild-linux-ppc64le": "0.15.14", + "esbuild-linux-riscv64": "0.15.14", + "esbuild-linux-s390x": "0.15.14", + "esbuild-netbsd-64": "0.15.14", + "esbuild-openbsd-64": "0.15.14", + "esbuild-sunos-64": "0.15.14", + "esbuild-windows-32": "0.15.14", + "esbuild-windows-64": "0.15.14", + "esbuild-windows-arm64": "0.15.14" } }, "esbuild-android-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-android-64/-/esbuild-android-64-0.15.12.tgz", - "integrity": "sha512-MJKXwvPY9g0rGps0+U65HlTsM1wUs9lbjt5CU19RESqycGFDRijMDQsh68MtbzkqWSRdEtiKS1mtPzKneaAI0Q==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-android-64/-/esbuild-android-64-0.15.14.tgz", + "integrity": "sha512-HuilVIb4rk9abT4U6bcFdU35UHOzcWVGLSjEmC58OVr96q5UiRqzDtWjPlCMugjhgUGKEs8Zf4ueIvYbOStbIg==", "optional": true }, "esbuild-android-arm64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-android-arm64/-/esbuild-android-arm64-0.15.12.tgz", - "integrity": "sha512-Hc9SEcZbIMhhLcvhr1DH+lrrec9SFTiRzfJ7EGSBZiiw994gfkVV6vG0sLWqQQ6DD7V4+OggB+Hn0IRUdDUqvA==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-android-arm64/-/esbuild-android-arm64-0.15.14.tgz", + "integrity": "sha512-/QnxRVxsR2Vtf3XottAHj7hENAMW2wCs6S+OZcAbc/8nlhbAL/bCQRCVD78VtI5mdwqWkVi3wMqM94kScQCgqg==", "optional": true }, "esbuild-darwin-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-darwin-64/-/esbuild-darwin-64-0.15.12.tgz", - "integrity": "sha512-qkmqrTVYPFiePt5qFjP8w/S+GIUMbt6k8qmiPraECUWfPptaPJUGkCKrWEfYFRWB7bY23FV95rhvPyh/KARP8Q==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-darwin-64/-/esbuild-darwin-64-0.15.14.tgz", + "integrity": "sha512-ToNuf1uifu8hhwWvoZJGCdLIX/1zpo8cOGnT0XAhDQXiKOKYaotVNx7pOVB1f+wHoWwTLInrOmh3EmA7Fd+8Vg==", "optional": true }, "esbuild-darwin-arm64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.15.12.tgz", - "integrity": "sha512-z4zPX02tQ41kcXMyN3c/GfZpIjKoI/BzHrdKUwhC/Ki5BAhWv59A9M8H+iqaRbwpzYrYidTybBwiZAIWCLJAkw==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.15.14.tgz", + "integrity": "sha512-KgGP+y77GszfYJgceO0Wi/PiRtYo5y2Xo9rhBUpxTPaBgWDJ14gqYN0+NMbu+qC2fykxXaipHxN4Scaj9tUS1A==", "optional": true }, "esbuild-freebsd-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-freebsd-64/-/esbuild-freebsd-64-0.15.12.tgz", - "integrity": "sha512-XFL7gKMCKXLDiAiBjhLG0XECliXaRLTZh6hsyzqUqPUf/PY4C6EJDTKIeqqPKXaVJ8+fzNek88285krSz1QECw==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-64/-/esbuild-freebsd-64-0.15.14.tgz", + "integrity": "sha512-xr0E2n5lyWw3uFSwwUXHc0EcaBDtsal/iIfLioflHdhAe10KSctV978Te7YsfnsMKzcoGeS366+tqbCXdqDHQA==", "optional": true }, "esbuild-freebsd-arm64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.15.12.tgz", - "integrity": "sha512-jwEIu5UCUk6TjiG1X+KQnCGISI+ILnXzIzt9yDVrhjug2fkYzlLbl0K43q96Q3KB66v6N1UFF0r5Ks4Xo7i72g==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.15.14.tgz", + "integrity": "sha512-8XH96sOQ4b1LhMlO10eEWOjEngmZ2oyw3pW4o8kvBcpF6pULr56eeYVP5radtgw54g3T8nKHDHYEI5AItvskZg==", "optional": true }, "esbuild-linux-32": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-32/-/esbuild-linux-32-0.15.12.tgz", - "integrity": "sha512-uSQuSEyF1kVzGzuIr4XM+v7TPKxHjBnLcwv2yPyCz8riV8VUCnO/C4BF3w5dHiVpCd5Z1cebBtZJNlC4anWpwA==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-32/-/esbuild-linux-32-0.15.14.tgz", + "integrity": "sha512-6ssnvwaTAi8AzKN8By2V0nS+WF5jTP7SfuK6sStGnDP7MCJo/4zHgM9oE1eQTS2jPmo3D673rckuCzRlig+HMA==", "optional": true }, "esbuild-linux-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.15.12.tgz", - "integrity": "sha512-QcgCKb7zfJxqT9o5z9ZUeGH1k8N6iX1Y7VNsEi5F9+HzN1OIx7ESxtQXDN9jbeUSPiRH1n9cw6gFT3H4qbdvcA==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-64/-/esbuild-linux-64-0.15.14.tgz", + "integrity": "sha512-ONySx3U0wAJOJuxGUlXBWxVKFVpWv88JEv0NZ6NlHknmDd1yCbf4AEdClSgLrqKQDXYywmw4gYDvdLsS6z0hcw==", "optional": true }, "esbuild-linux-arm": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-arm/-/esbuild-linux-arm-0.15.12.tgz", - "integrity": "sha512-Wf7T0aNylGcLu7hBnzMvsTfEXdEdJY/hY3u36Vla21aY66xR0MS5I1Hw8nVquXjTN0A6fk/vnr32tkC/C2lb0A==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm/-/esbuild-linux-arm-0.15.14.tgz", + "integrity": "sha512-D2LImAIV3QzL7lHURyCHBkycVFbKwkDb1XEUWan+2fb4qfW7qAeUtul7ZIcIwFKZgPcl+6gKZmvLgPSj26RQ2Q==", "optional": true }, "esbuild-linux-arm64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-arm64/-/esbuild-linux-arm64-0.15.12.tgz", - "integrity": "sha512-HtNq5xm8fUpZKwWKS2/YGwSfTF+339L4aIA8yphNKYJckd5hVdhfdl6GM2P3HwLSCORS++++7++//ApEwXEuAQ==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-arm64/-/esbuild-linux-arm64-0.15.14.tgz", + "integrity": "sha512-kle2Ov6a1e5AjlHlMQl1e+c4myGTeggrRzArQFmWp6O6JoqqB9hT+B28EW4tjFWgV/NxUq46pWYpgaWXsXRPAg==", "optional": true }, "esbuild-linux-mips64le": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.15.12.tgz", - "integrity": "sha512-Qol3+AvivngUZkTVFgLpb0H6DT+N5/zM3V1YgTkryPYFeUvuT5JFNDR3ZiS6LxhyF8EE+fiNtzwlPqMDqVcc6A==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.15.14.tgz", + "integrity": "sha512-FVdMYIzOLXUq+OE7XYKesuEAqZhmAIV6qOoYahvUp93oXy0MOVTP370ECbPfGXXUdlvc0TNgkJa3YhEwyZ6MRA==", "optional": true }, "esbuild-linux-ppc64le": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.15.12.tgz", - "integrity": "sha512-4D8qUCo+CFKaR0cGXtGyVsOI7w7k93Qxb3KFXWr75An0DHamYzq8lt7TNZKoOq/Gh8c40/aKaxvcZnTgQ0TJNg==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.15.14.tgz", + "integrity": "sha512-2NzH+iuzMDA+jjtPjuIz/OhRDf8tzbQ1tRZJI//aT25o1HKc0reMMXxKIYq/8nSHXiJSnYV4ODzTiv45s+h73w==", "optional": true }, "esbuild-linux-riscv64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-riscv64/-/esbuild-linux-riscv64-0.15.12.tgz", - "integrity": "sha512-G9w6NcuuCI6TUUxe6ka0enjZHDnSVK8bO+1qDhMOCtl7Tr78CcZilJj8SGLN00zO5iIlwNRZKHjdMpfFgNn1VA==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-riscv64/-/esbuild-linux-riscv64-0.15.14.tgz", + "integrity": "sha512-VqxvutZNlQxmUNS7Ac+aczttLEoHBJ9e3OYGqnULrfipRvG97qLrAv9EUY9iSrRKBqeEbSvS9bSfstZqwz0T4Q==", "optional": true }, "esbuild-linux-s390x": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-linux-s390x/-/esbuild-linux-s390x-0.15.12.tgz", - "integrity": "sha512-Lt6BDnuXbXeqSlVuuUM5z18GkJAZf3ERskGZbAWjrQoi9xbEIsj/hEzVnSAFLtkfLuy2DE4RwTcX02tZFunXww==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-linux-s390x/-/esbuild-linux-s390x-0.15.14.tgz", + "integrity": "sha512-+KVHEUshX5n6VP6Vp/AKv9fZIl5kr2ph8EUFmQUJnDpHwcfTSn2AQgYYm0HTBR2Mr4d0Wlr0FxF/Cs5pbFgiOw==", "optional": true }, "esbuild-loader": { @@ -12729,39 +12765,39 @@ } }, "esbuild-netbsd-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-netbsd-64/-/esbuild-netbsd-64-0.15.12.tgz", - "integrity": "sha512-jlUxCiHO1dsqoURZDQts+HK100o0hXfi4t54MNRMCAqKGAV33JCVvMplLAa2FwviSojT/5ZG5HUfG3gstwAG8w==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-netbsd-64/-/esbuild-netbsd-64-0.15.14.tgz", + "integrity": "sha512-6D/dr17piEgevIm1xJfZP2SjB9Z+g8ERhNnBdlZPBWZl+KSPUKLGF13AbvC+nzGh8IxOH2TyTIdRMvKMP0nEzQ==", "optional": true }, "esbuild-openbsd-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-openbsd-64/-/esbuild-openbsd-64-0.15.12.tgz", - "integrity": "sha512-1o1uAfRTMIWNOmpf8v7iudND0L6zRBYSH45sofCZywrcf7NcZA+c7aFsS1YryU+yN7aRppTqdUK1PgbZVaB1Dw==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-openbsd-64/-/esbuild-openbsd-64-0.15.14.tgz", + "integrity": "sha512-rREQBIlMibBetgr2E9Lywt2Qxv2ZdpmYahR4IUlAQ1Efv/A5gYdO0/VIN3iowDbCNTLxp0bb57Vf0LFcffD6kA==", "optional": true }, "esbuild-sunos-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-sunos-64/-/esbuild-sunos-64-0.15.12.tgz", - "integrity": "sha512-nkl251DpoWoBO9Eq9aFdoIt2yYmp4I3kvQjba3jFKlMXuqQ9A4q+JaqdkCouG3DHgAGnzshzaGu6xofGcXyPXg==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-sunos-64/-/esbuild-sunos-64-0.15.14.tgz", + "integrity": "sha512-DNVjSp/BY4IfwtdUAvWGIDaIjJXY5KI4uD82+15v6k/w7px9dnaDaJJ2R6Mu+KCgr5oklmFc0KjBjh311Gxl9Q==", "optional": true }, "esbuild-windows-32": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-windows-32/-/esbuild-windows-32-0.15.12.tgz", - "integrity": "sha512-WlGeBZHgPC00O08luIp5B2SP4cNCp/PcS+3Pcg31kdcJPopHxLkdCXtadLU9J82LCfw4TVls21A6lilQ9mzHrw==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-windows-32/-/esbuild-windows-32-0.15.14.tgz", + "integrity": "sha512-pHBWrcA+/oLgvViuG9FO3kNPO635gkoVrRQwe6ZY1S0jdET07xe2toUvQoJQ8KT3/OkxqUasIty5hpuKFLD+eg==", "optional": true }, "esbuild-windows-64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.15.12.tgz", - "integrity": "sha512-VActO3WnWZSN//xjSfbiGOSyC+wkZtI8I4KlgrTo5oHJM6z3MZZBCuFaZHd8hzf/W9KPhF0lY8OqlmWC9HO5AA==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-windows-64/-/esbuild-windows-64-0.15.14.tgz", + "integrity": "sha512-CszIGQVk/P8FOS5UgAH4hKc9zOaFo69fe+k1rqgBHx3CSK3Opyk5lwYriIamaWOVjBt7IwEP6NALz+tkVWdFog==", "optional": true }, "esbuild-windows-arm64": { - "version": "0.15.12", - "resolved": "https://registry.npmjs.org/esbuild-windows-arm64/-/esbuild-windows-arm64-0.15.12.tgz", - "integrity": "sha512-Of3MIacva1OK/m4zCNIvBfz8VVROBmQT+gRX6pFTLPngFYcj6TFH/12VveAqq1k9VB2l28EoVMNMUCcmsfwyuA==", + "version": "0.15.14", + "resolved": "https://registry.npmjs.org/esbuild-windows-arm64/-/esbuild-windows-arm64-0.15.14.tgz", + "integrity": "sha512-KW9W4psdZceaS9A7Jsgl4WialOznSURvqX/oHZk3gOP7KbjtHLSsnmSvNdzagGJfxbAe30UVGXRe8q8nDsOSQw==", "optional": true }, "escalade": { @@ -12835,9 +12871,9 @@ } }, "eslint": { - "version": "8.26.0", - "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.26.0.tgz", - "integrity": "sha512-kzJkpaw1Bfwheq4VXUezFriD1GxszX6dUekM7Z3aC2o4hju+tsR/XyTC3RcoSD7jmy9VkPU3+N6YjVU2e96Oyg==", + "version": "8.28.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-8.28.0.tgz", + "integrity": "sha512-S27Di+EVyMxcHiwDrFzk8dJYAaD+/5SoWKxL1ri/71CRHsnJnRDPNt2Kzj24+MT9FDupf4aqqyqPrvI8MvQ4VQ==", "dev": true, "requires": { "@eslint/eslintrc": "^1.3.3", @@ -13004,31 +13040,33 @@ "requires": {} }, "eslint-plugin-unicorn": { - "version": "44.0.2", - "resolved": "https://registry.npmjs.org/eslint-plugin-unicorn/-/eslint-plugin-unicorn-44.0.2.tgz", - "integrity": "sha512-GLIDX1wmeEqpGaKcnMcqRvMVsoabeF0Ton0EX4Th5u6Kmf7RM9WBl705AXFEsns56ESkEs0uyelLuUTvz9Tr0w==", + "version": "45.0.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-unicorn/-/eslint-plugin-unicorn-45.0.0.tgz", + "integrity": "sha512-iP8cMRxXKHonKioOhnCoCcqVhoqhAp6rB+nsoLjXFDxTHz3btWMAp8xwzjHA0B1K6YV/U/Yvqn1bUXZt8sJPuQ==", "dev": true, "requires": { "@babel/helper-validator-identifier": "^7.19.1", - "ci-info": "^3.4.0", + "ci-info": "^3.6.1", "clean-regexp": "^1.0.0", "eslint-utils": "^3.0.0", "esquery": "^1.4.0", "indent-string": "^4.0.0", "is-builtin-module": "^3.2.0", + "jsesc": "3.0.2", "lodash": "^4.17.21", "pluralize": "^8.0.0", "read-pkg-up": "^7.0.1", "regexp-tree": "^0.1.24", + "regjsparser": "0.9.1", "safe-regex": "^2.1.1", - "semver": "^7.3.7", + "semver": "^7.3.8", "strip-indent": "^3.0.0" } }, "eslint-plugin-vue": { - "version": "9.6.0", - "resolved": "https://registry.npmjs.org/eslint-plugin-vue/-/eslint-plugin-vue-9.6.0.tgz", - "integrity": "sha512-zzySkJgVbFCylnG2+9MDF7N+2Rjze2y0bF8GyUNpFOnT8mCMfqqtLDJkHBuYu9N/psW1A6DVbQhPkP92E+qakA==", + "version": "9.7.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-vue/-/eslint-plugin-vue-9.7.0.tgz", + "integrity": "sha512-DrOO3WZCZEwcLsnd3ohFwqCoipGRSTKTBTnLwdhqAbYZtzWl0o7D+D8ZhlmiZvABKTEl8AFsqH1GHGdybyoQmw==", "dev": true, "requires": { "eslint-utils": "^3.0.0", @@ -13074,9 +13112,9 @@ "dev": true }, "espree": { - "version": "9.4.0", - "resolved": "https://registry.npmjs.org/espree/-/espree-9.4.0.tgz", - "integrity": "sha512-DQmnRpLj7f6TgN/NYb0MTzJXL+vJF9h3pHy4JhCIs3zwcgez8xmGg3sXHcEO97BrmO2OSvCwMdfdlyl+E9KjOw==", + "version": "9.4.1", + "resolved": "https://registry.npmjs.org/espree/-/espree-9.4.1.tgz", + "integrity": "sha512-XwctdmTO6SIvCzd9810yyNzIrOrqNYV9Koizx4C/mRhf9uq0o4yHoCEU/670pOxOL/MSraektvSAji79kX90Vg==", "dev": true, "requires": { "acorn": "^8.8.0", @@ -13134,6 +13172,11 @@ "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", "integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==" }, + "fast-clone": { + "version": "1.5.13", + "resolved": "https://registry.npmjs.org/fast-clone/-/fast-clone-1.5.13.tgz", + "integrity": "sha512-0ez7coyFBQFjZtId+RJqJ+EQs61w9xARfqjqK0AD9vIUkSxWD4HvPt80+5evebZ1tTnv1GYKrPTipx7kOW5ipA==" + }, "fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -13191,6 +13234,14 @@ "reusify": "^1.0.4" } }, + "fetch-ponyfill": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/fetch-ponyfill/-/fetch-ponyfill-7.1.0.tgz", + "integrity": "sha512-FhbbL55dj/qdVO3YNK7ZEkshvj3eQ7EuIGV2I6ic/2YiocvyWv+7jg2s4AyS0wdRU75s3tA8ZxI/xPigb0v5Aw==", + "requires": { + "node-fetch": "~2.6.1" + } + }, "file-entry-cache": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", @@ -13456,9 +13507,9 @@ } }, "globals": { - "version": "13.17.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-13.17.0.tgz", - "integrity": "sha512-1C+6nQRb1GwGMKm2dH/E7enFAMxGTmGI7/dEdhy/DNelv85w9B72t3uc5frtMNXIbzrarJJ/lTCjcaZwbLJmyw==", + "version": "13.18.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-13.18.0.tgz", + "integrity": "sha512-/mR4KI8Ps2spmoc0Ulu9L7agOF0du1CZNQ3dke8yItYlyKNmGrkONemBbd6V8UTc1Wgcqn21t3WYB7dbRmh6/A==", "dev": true, "requires": { "type-fest": "^0.20.2" @@ -13640,6 +13691,11 @@ "integrity": "sha512-soFhflCVWLfRNOPU3iv5Z9VUdT44xFRbzjLsEzSr5AQmgqPMTHdU3PMT1Cf1ssx8fLNJDA1juftYl+PUcv3MqA==", "requires": {} }, + "ieee754": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", + "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==" + }, "ignore": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.2.0.tgz", @@ -13732,9 +13788,9 @@ "integrity": "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg==" }, "interpret": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/interpret/-/interpret-2.2.0.tgz", - "integrity": "sha512-Ju0Bz/cEia55xDwUWEa8+olFpCiQoypjnQySseKtmjNrnps3P+xfpUmGr90T7yjlVJmOtybRvPXhKMbHr+fWnw==" + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/interpret/-/interpret-3.1.1.tgz", + "integrity": "sha512-6xwYfHbajpoF0xLW+iwLkhwgvLoZDfjYfoFNu8ftMoXINzwuymNLd9u/KmwtdT2GbR+/Cz66otEGEVVUHX9QLQ==" }, "ip": { "version": "1.1.8", @@ -13991,24 +14047,23 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "dev": true, "requires": { "argparse": "^2.0.1" } }, "jsdom": { - "version": "20.0.1", - "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-20.0.1.tgz", - "integrity": "sha512-pksjj7Rqoa+wdpkKcLzQRHhJCEE42qQhl/xLMUKHgoSejaKOdaXEAnqs6uDNwMl/fciHTzKeR8Wm8cw7N+g98A==", + "version": "20.0.3", + "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-20.0.3.tgz", + "integrity": "sha512-SYhBvTh89tTfCD/CRdSOm13mOBa42iTaTyfyEWBdKcGdPxPtLFBXuHR8XHb33YNYaP+lLbmSvBTsnoesCNJEsQ==", "dev": true, "requires": { "abab": "^2.0.6", - "acorn": "^8.8.0", + "acorn": "^8.8.1", "acorn-globals": "^7.0.0", "cssom": "^0.5.0", "cssstyle": "^2.3.0", "data-urls": "^3.0.2", - "decimal.js": "^10.4.1", + "decimal.js": "^10.4.2", "domexception": "^4.0.0", "escodegen": "^2.0.0", "form-data": "^4.0.0", @@ -14021,12 +14076,12 @@ "saxes": "^6.0.0", "symbol-tree": "^3.2.4", "tough-cookie": "^4.1.2", - "w3c-xmlserializer": "^3.0.0", + "w3c-xmlserializer": "^4.0.0", "webidl-conversions": "^7.0.0", "whatwg-encoding": "^2.0.0", "whatwg-mimetype": "^3.0.0", "whatwg-url": "^11.0.0", - "ws": "^8.9.0", + "ws": "^8.11.0", "xml-name-validator": "^4.0.0" } }, @@ -14036,6 +14091,12 @@ "integrity": "sha512-NFbZTr1t13fPKw53swmZFKwBkEDWDnno7uLJk+a+Rw9tGDTkGgnGdZJ8A/o3gR1+XaAXmSsbpfIBIBgqRBZWDA==", "dev": true }, + "jsesc": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.0.2.tgz", + "integrity": "sha512-xKqzzWXDttJuOcawBt4KnKHHIf5oQ/Cxax+0PWFG+DFDgHNAdi+TXECADI+RYiFUMmx8792xsMbbgXj4CwnP4g==", + "dev": true + }, "json-parse-even-better-errors": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", @@ -14113,9 +14174,9 @@ "integrity": "sha512-pJiBpiXMbt7dkzXe8Ghj/u4FfXOOa98fPW+bihOJ4SjnoijweJrNThJfd3ifXpXhREjpoF2mZVH1GfS9LV3kHQ==" }, "known-css-properties": { - "version": "0.25.0", - "resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.25.0.tgz", - "integrity": "sha512-b0/9J1O9Jcyik1GC6KC42hJ41jKwdO/Mq8Mdo5sYN+IuRTXs2YFHZC3kZSx6ueusqa95x3wLYe/ytKjbAfGixA==", + "version": "0.26.0", + "resolved": "https://registry.npmjs.org/known-css-properties/-/known-css-properties-0.26.0.tgz", + "integrity": "sha512-5FZRzrZzNTBruuurWpvZnvP9pum+fe0HcK8z/ooo+U+Hmp4vtbyp1/QDsqmufirXy4egGzbaH/y2uCZf+6W5Kg==", "dev": true }, "less": { @@ -14222,9 +14283,9 @@ "integrity": "sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==" }, "loader-utils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.3.tgz", - "integrity": "sha512-THWqIsn8QRnvLl0shHYVBN9syumU8pYWEHPTmkiVGd+7K5eFNVSY6AJhRvgGF70gg1Dz+l/k8WicvFCxdEs60A==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/loader-utils/-/loader-utils-2.0.4.tgz", + "integrity": "sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw==", "requires": { "big.js": "^5.2.2", "emojis-list": "^3.0.0", @@ -14256,24 +14317,12 @@ "resolved": "https://registry.npmjs.org/lodash._reinterpolate/-/lodash._reinterpolate-3.0.0.tgz", "integrity": "sha512-xYHt68QRoYGjeeM/XOE1uJtvXQAgvszfBhjV4yvsQH0u2i9I6cI6c6/eG4Hh3UAOVn0y/xAXwmTzEay49Q//HA==" }, - "lodash.get": { - "version": "4.4.2", - "resolved": "https://registry.npmjs.org/lodash.get/-/lodash.get-4.4.2.tgz", - "integrity": "sha512-z+Uw/vLuy6gQe8cfaFWD7p0wVv8fJl3mbzXh33RS+0oW2wvUqiRXiQ69gLWSLpgB5/6sU+r6BlQR0MBILadqTQ==", - "dev": true - }, "lodash.merge": { "version": "4.6.2", "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", "dev": true }, - "lodash.set": { - "version": "4.3.2", - "resolved": "https://registry.npmjs.org/lodash.set/-/lodash.set-4.3.2.tgz", - "integrity": "sha512-4hNPN5jlm/N/HLMCO43v8BXKq9Z7QdAGc/VGrRD61w8gN9g/6jF9A4L1pbUgBLCffi0w9VsXfTOij5x8iTyFvg==", - "dev": true - }, "lodash.template": { "version": "4.5.0", "resolved": "https://registry.npmjs.org/lodash.template/-/lodash.template-4.5.0.tgz", @@ -14304,9 +14353,9 @@ "dev": true }, "loupe": { - "version": "2.3.4", - "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.4.tgz", - "integrity": "sha512-OvKfgCC2Ndby6aSTREl5aCCPTNIzlDfQZvZxNUrBrihDhL3xcrYegTblhmEiCrg2kKQz4XsFIaemE5BF4ybSaQ==", + "version": "2.3.6", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.6.tgz", + "integrity": "sha512-RaPMZKiMy8/JruncMU5Bt6na1eftNoo++R4Y+N2FrxkDVTrGvcyzFTsaGif4QTeKESheMGegbhw6iUAq+5A8zA==", "dev": true, "requires": { "get-func-name": "^2.0.0" @@ -14445,9 +14494,9 @@ "dev": true }, "marked": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/marked/-/marked-4.1.1.tgz", - "integrity": "sha512-0cNMnTcUJPxbA6uWmCmjWz4NJRe/0Xfk2NhXCUHjew9qJzFN20krFnsUe7QynwqOwa5m1fZ4UDg0ycKFVC0ccw==" + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/marked/-/marked-4.2.3.tgz", + "integrity": "sha512-slWRdJkbTZ+PjkyJnE30Uid64eHwbwa1Q25INCAYfZlK4o6ylagBy/Le9eWntqJFoFT93ikUKMv47GZ4gTwHkw==" }, "mathml-tag-names": { "version": "2.1.3", @@ -14542,19 +14591,23 @@ "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==" }, "mermaid": { - "version": "9.1.7", - "resolved": "https://registry.npmjs.org/mermaid/-/mermaid-9.1.7.tgz", - "integrity": "sha512-MRVHXy5FLjnUQUG7YS3UN9jEN6FXCJbFCXVGJQjVIbiR6Vhw0j/6pLIjqsiah9xoHmQU6DEaKOvB3S1g/1nBPA==", + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/mermaid/-/mermaid-9.2.2.tgz", + "integrity": "sha512-6s7eKMqFJGS+0MYjmx8f6ZigqKBJVoSx5ql2gw6a4Aa+WJ49QiEJg7gPwywaBg3DZMs79UP7trESp4+jmaQccw==", "requires": { "@braintree/sanitize-url": "^6.0.0", "d3": "^7.0.0", "dagre": "^0.8.5", "dagre-d3": "^0.6.4", "dompurify": "2.4.0", + "fast-clone": "^1.5.13", "graphlib": "^2.1.8", "khroma": "^2.0.0", - "moment-mini": "2.24.0", - "stylis": "^4.0.10" + "lodash": "^4.17.21", + "moment-mini": "^2.24.0", + "non-layered-tidy-tree-layout": "^2.0.2", + "stylis": "^4.1.2", + "uuid": "^9.0.0" } }, "micromatch": { @@ -14592,9 +14645,9 @@ "dev": true }, "mini-css-extract-plugin": { - "version": "2.6.1", - "resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-2.6.1.tgz", - "integrity": "sha512-wd+SD57/K6DiV7jIR34P+s3uckTRuQvx0tKPcvjFlrEylk6P4mQ2KSWk1hblj1Kxaqok7LogKOieygXqBczNlg==", + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-2.7.0.tgz", + "integrity": "sha512-auqtVo8KhTScMsba7MbijqZTfibbXiBNlPAQbsVt7enQfcDYLdgG57eGxMqwVU3mfeWANY4F1wUg+rMF+ycZgw==", "requires": { "schema-utils": "^4.0.0" } @@ -14625,9 +14678,9 @@ } }, "moment-mini": { - "version": "2.24.0", - "resolved": "https://registry.npmjs.org/moment-mini/-/moment-mini-2.24.0.tgz", - "integrity": "sha512-9ARkWHBs+6YJIvrIp0Ik5tyTTtP9PoV0Ssu2Ocq5y9v8+NOOpWiRshAp8c4rZVWTOe+157on/5G+zj5pwIQFEQ==" + "version": "2.29.4", + "resolved": "https://registry.npmjs.org/moment-mini/-/moment-mini-2.29.4.tgz", + "integrity": "sha512-uhXpYwHFeiTbY9KSgPPRoo1nt8OxNVdMVoTBYHfSEKeRkIkwGpO+gERmhuhBtzfaeOyTkykSrm2+noJBgqt3Hg==" }, "monaco-editor": { "version": "0.34.1", @@ -14642,6 +14695,11 @@ "loader-utils": "^2.0.2" } }, + "moo": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/moo/-/moo-0.5.2.tgz", + "integrity": "sha512-iSAJLHYKnX41mKcJKjqvnAN9sf0LMDTXDEvFv+ffuRR9a1MIuXLjMNL6EsnDHSkKLTWNqQQ5uo61P4EbU4NU+Q==" + }, "ms": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", @@ -14660,9 +14718,9 @@ "dev": true }, "needle": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/needle/-/needle-3.1.0.tgz", - "integrity": "sha512-gCE9weDhjVGCRqS8dwDR/D3GTAeyXLXuqp7I8EzH6DllZGXSUyxuqqLh+YX9rMAWaaTFyVAg6rHGL25dqvczKw==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/needle/-/needle-3.2.0.tgz", + "integrity": "sha512-oUvzXnyLiVyVGoianLijF9O/RecZUf7TkBfimjGrLM4eQhXyeJwM6GeAWccwfQ9aa4gMCZKqhAOuLaMIcQxajQ==", "optional": true, "requires": { "debug": "^3.2.6", @@ -14719,7 +14777,6 @@ "version": "2.6.7", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", - "dev": true, "requires": { "whatwg-url": "^5.0.0" }, @@ -14727,20 +14784,17 @@ "tr46": { "version": "0.0.3", "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "dev": true + "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==" }, "webidl-conversions": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "dev": true + "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==" }, "whatwg-url": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "dev": true, "requires": { "tr46": "~0.0.3", "webidl-conversions": "^3.0.0" @@ -14753,6 +14807,11 @@ "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.6.tgz", "integrity": "sha512-PiVXnNuFm5+iYkLBNeq5211hvO38y63T0i2KKh2KnUs3RpzJ+JtODFjkD8yjLwnDkTYF1eKXheUwdssR+NRZdg==" }, + "non-layered-tidy-tree-layout": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/non-layered-tidy-tree-layout/-/non-layered-tidy-tree-layout-2.0.2.tgz", + "integrity": "sha512-gkXMxRzUH+PB0ax9dUN0yYF0S25BqeAYqhgMaLUFmpXLEk7Fcu8f4emJuOAY0V8kjDICxROIKsTAKsV/v355xw==" + }, "normalize-package-data": { "version": "2.5.0", "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", @@ -14824,14 +14883,14 @@ } }, "object.values": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.5.tgz", - "integrity": "sha512-QUZRW0ilQ3PnPpbNtgdNV1PDbEqLIiSFB3l+EnGtBQ/8SUTLj1PZwtQHABZtLgwpJZTSZhuGLOGk57Drx2IvYg==", + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.1.6.tgz", + "integrity": "sha512-FVVTkD1vENCsAcwNs9k6jea2uHC/X0+JcjG8YA60FN5CMaJmG95wT9jek/xX9nornqGRrBkKtzuAu2wuHpKqvw==", "dev": true, "requires": { "call-bind": "^1.0.2", - "define-properties": "^1.1.3", - "es-abstract": "^1.19.1" + "define-properties": "^1.1.4", + "es-abstract": "^1.20.4" } }, "once": { @@ -15066,9 +15125,9 @@ } }, "playwright-core": { - "version": "1.27.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.27.1.tgz", - "integrity": "sha512-9EmeXDncC2Pmp/z+teoVYlvmPWUC6ejSSYZUln7YaP89Z6lpAaiaAnqroUt/BoLo8tn7WYShcfaCh+xofZa44Q==", + "version": "1.28.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.28.0.tgz", + "integrity": "sha512-nJLknd28kPBiCNTbqpu6Wmkrh63OEqJSFw9xOfL9qxfNwody7h6/L3O2dZoWQ6Oxcm0VOHjWmGiCUGkc0X3VZA==", "dev": true }, "pluralize": { @@ -15084,9 +15143,9 @@ "dev": true }, "postcss": { - "version": "8.4.18", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.18.tgz", - "integrity": "sha512-Wi8mWhncLJm11GATDaQKobXSNEYGUHeQLiQqDFG1qQ5UTDPTEvKw0Xt5NsTpktGTwLps3ByrWsBrG0rB8YQ9oA==", + "version": "8.4.19", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.19.tgz", + "integrity": "sha512-h+pbPsyhlYj6N2ozBmHhHrs9DzGmbaarbLvWipMRO7RLS+v4onj26MPFXA5OBYFxyqYhUJK456SwDcY9H2/zsA==", "requires": { "nanoid": "^3.3.4", "picocolors": "^1.0.0", @@ -15152,9 +15211,9 @@ "requires": {} }, "postcss-selector-parser": { - "version": "6.0.10", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.10.tgz", - "integrity": "sha512-IQ7TZdoaqbT+LCpShg46jnZVlhWD2w6iQYAcYXfHARZ7X1t/UGhhceQDs5X0cGqKvYlHNOuv7Oa1xmb0oQuA3w==", + "version": "6.0.11", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.0.11.tgz", + "integrity": "sha512-zbARubNdogI9j7WY4nQJBiNqQf3sLS3wCP4WfOidu+p28LofJqDH1tcXypGrcmMHhDk2t9wGhCsYe/+szLTy1g==", "requires": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" @@ -15380,11 +15439,11 @@ } }, "rechoir": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.7.1.tgz", - "integrity": "sha512-/njmZ8s1wVeR6pjTZ+0nCnv8SpZNRMT2D1RLOJQESlYFDBvwpTA4KWJpZ+sBJ4+vhjILRcK7JIFdGCdxEAAitg==", + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.8.0.tgz", + "integrity": "sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ==", "requires": { - "resolve": "^1.9.0" + "resolve": "^1.20.0" } }, "redent": { @@ -15420,6 +15479,23 @@ "integrity": "sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==", "dev": true }, + "regjsparser": { + "version": "0.9.1", + "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.9.1.tgz", + "integrity": "sha512-dQUtn90WanSNl+7mQKcXAgZxvUe7Z0SqXlgzv0za4LwiUhyzBC58yQO3liFoUgu8GiJVInAhJjkj1N0EtQ5nkQ==", + "dev": true, + "requires": { + "jsesc": "~0.5.0" + }, + "dependencies": { + "jsesc": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-0.5.0.tgz", + "integrity": "sha512-uZz5UnB7u4T9LvwmFqXii7pZSouaRPorGs5who1Ip7VO0wxanFvBL7GkM6dTHlgX+jhBApRetaWpnDabOeTcnA==", + "dev": true + } + } + }, "require-directory": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", @@ -15647,6 +15723,15 @@ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==" }, + "shortcss": { + "version": "0.1.3", + "resolved": "https://registry.npmjs.org/shortcss/-/shortcss-0.1.3.tgz", + "integrity": "sha512-MIOoTd99CIGTrAuGiMUx9VZrnrZmWzEHuKbGM/w+ia/w98cezhlN9w4aQOVSxswdoqkUnWrMw3tThOi3sevZAg==", + "dev": true, + "requires": { + "css-shorthand-properties": "^1.0.0" + } + }, "side-channel": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.0.4.tgz", @@ -15854,25 +15939,25 @@ } }, "string.prototype.trimend": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.5.tgz", - "integrity": "sha512-I7RGvmjV4pJ7O3kdf+LXFpVfdNOxtCW/2C8f6jNiW4+PQchwxkCDzlk1/7p+Wl4bqFIZeF47qAHXLuHHWKAxog==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.6.tgz", + "integrity": "sha512-JySq+4mrPf9EsDBEDYMOb/lM7XQLulwg5R/m1r0PXEFqrV0qHvl58sdTilSXtKOflCsK2E8jxf+GKC0T07RWwQ==", "dev": true, "requires": { "call-bind": "^1.0.2", "define-properties": "^1.1.4", - "es-abstract": "^1.19.5" + "es-abstract": "^1.20.4" } }, "string.prototype.trimstart": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.5.tgz", - "integrity": "sha512-THx16TJCGlsN0o6dl2o6ncWUsdgnLRSA23rRE5pyGBw/mLr3Ej/R2LaqCtgP8VNMGZsvMWnf9ooZPyY2bHvUFg==", + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.6.tgz", + "integrity": "sha512-omqjMDaY92pbn5HOX7f9IccLA+U1tA9GvtU4JrodiXFfYB7jPzzHpRzpglLAjtUV6bB557zwClJezTqnAiYnQA==", "dev": true, "requires": { "call-bind": "^1.0.2", "define-properties": "^1.1.4", - "es-abstract": "^1.19.5" + "es-abstract": "^1.20.4" } }, "strip-ansi": { @@ -15920,15 +16005,15 @@ "dev": true }, "stylelint": { - "version": "14.14.0", - "resolved": "https://registry.npmjs.org/stylelint/-/stylelint-14.14.0.tgz", - "integrity": "sha512-yUI+4xXfPHVnueYddSQ/e1GuEA/2wVhWQbGj16AmWLtQJtn28lVxfS4b0CsWyVRPgd3Auzi0NXOthIEUhtQmmA==", + "version": "14.15.0", + "resolved": "https://registry.npmjs.org/stylelint/-/stylelint-14.15.0.tgz", + "integrity": "sha512-JOgDAo5QRsqiOZPZO+B9rKJvBm64S0xasbuRPAbPs6/vQDgDCnZLIiw6XcAS6GQKk9k1sBWR6rmH3Mfj8OknKg==", "dev": true, "requires": { "@csstools/selector-specificity": "^2.0.2", "balanced-match": "^2.0.0", "colord": "^2.9.3", - "cosmiconfig": "^7.0.1", + "cosmiconfig": "^7.1.0", "css-functions-list": "^3.1.0", "debug": "^4.3.4", "fast-glob": "^3.2.12", @@ -15942,13 +16027,13 @@ "import-lazy": "^4.0.0", "imurmurhash": "^0.1.4", "is-plain-object": "^5.0.0", - "known-css-properties": "^0.25.0", + "known-css-properties": "^0.26.0", "mathml-tag-names": "^2.1.3", "meow": "^9.0.0", "micromatch": "^4.0.5", "normalize-path": "^3.0.0", "picocolors": "^1.0.0", - "postcss": "^8.4.17", + "postcss": "^8.4.19", "postcss-media-query-parser": "^0.2.3", "postcss-resolve-nested-selector": "^0.1.1", "postcss-safe-parser": "^6.0.0", @@ -15960,7 +16045,7 @@ "style-search": "^0.1.0", "supports-hyperlinks": "^2.3.0", "svg-tags": "^1.0.0", - "table": "^6.8.0", + "table": "^6.8.1", "v8-compile-cache": "^2.3.0", "write-file-atomic": "^4.0.2" }, @@ -15995,10 +16080,20 @@ "stylelint-config-recommended": "^9.0.0" } }, + "stylelint-declaration-strict-value": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/stylelint-declaration-strict-value/-/stylelint-declaration-strict-value-1.9.1.tgz", + "integrity": "sha512-iIkMh2ukIfSTtJoEDgGq5cqUyYWP8NExPk2YSGcePtFikb7KmJoSi0QYajiZRxge/PTbYspci7nIcrtArJlAsw==", + "dev": true, + "requires": { + "css-values": "^0.1.0", + "shortcss": "^0.1.3" + } + }, "stylis": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.1.2.tgz", - "integrity": "sha512-Nn2CCrG2ZaFziDxaZPN43CXqn+j7tcdjPFCkRBkFue8QYXC2HdEwnw5TCBo4yQZ2WxKYeSi0fdoOrtEqgDrXbA==" + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/stylis/-/stylis-4.1.3.tgz", + "integrity": "sha512-GP6WDNWf+o403jrEp9c5jibKavrtLW+/qYGhFxFrG8maXhwTBI7gLLhiBb0o7uFccWN+EOS9aMO6cGHWAO07OA==" }, "superstruct": { "version": "0.10.13", @@ -16035,9 +16130,9 @@ "dev": true }, "svgo": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/svgo/-/svgo-3.0.0.tgz", - "integrity": "sha512-mSqPn6RDeNqJvCeqHERlfWJjd4crP/2PgFelil9WpTwC4D3okAUopPsH3lnEyl7ONXfDVyISOihDjO0uK8YVAA==", + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/svgo/-/svgo-3.0.2.tgz", + "integrity": "sha512-Z706C1U2pb1+JGP48fbazf3KxHrWOsLme6Rv7imFBn5EnuanDW1GPaA/P1/dvObE670JDePC3mnj0k0B7P0jjQ==", "dev": true, "requires": { "@trysound/sax": "0.2.0", @@ -16057,9 +16152,9 @@ } }, "swagger-ui-dist": { - "version": "4.15.0", - "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-4.15.0.tgz", - "integrity": "sha512-vAsIdNHraLuBRm1vrxcMaLk/y/PGBTvHLf4lQGQ3LaEXkORtIxw11sBMpYJL3keOLaFJ1OqNXuURd6eShoFLZQ==" + "version": "4.15.5", + "resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-4.15.5.tgz", + "integrity": "sha512-V3eIa28lwB6gg7/wfNvAbjwJYmDXy1Jo1POjyTzlB6wPcHiGlRxq39TSjYGVjQrUSAzpv+a7nzp7mDxgNy57xA==" }, "symbol-tree": { "version": "3.2.4", @@ -16067,10 +16162,19 @@ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==", "dev": true }, + "sync-fetch": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/sync-fetch/-/sync-fetch-0.4.2.tgz", + "integrity": "sha512-vilDD6yTGwyUjm7/W5WUUOCw1GH1aV591zC21XhbV6MJNZqfZcNMs9DVPHzy1UAmQ2GAg6S03F5TQ3paegKSdg==", + "requires": { + "buffer": "^5.7.1", + "node-fetch": "^2.6.1" + } + }, "table": { - "version": "6.8.0", - "resolved": "https://registry.npmjs.org/table/-/table-6.8.0.tgz", - "integrity": "sha512-s/fitrbVeEyHKFa7mFdkuQMWlH1Wgw/yEXMt5xACT4ZpzWFluehAxRtUUQKPuWhaLAWhFcVx6w3oC8VKaUfPGA==", + "version": "6.8.1", + "resolved": "https://registry.npmjs.org/table/-/table-6.8.1.tgz", + "integrity": "sha512-Y4X9zqrCftUhMeH2EptSSERdVKt/nEdijTOacGD/97EKjhQ/Qs8RTlEGABSJNNN8lac9kheH+af7yAkEWlgneA==", "dev": true, "requires": { "ajv": "^8.0.1", @@ -16259,9 +16363,9 @@ } }, "tslib": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.0.tgz", - "integrity": "sha512-d6xOpEDfsi2CZVlPQzGeux8XMwLT9hssAsaPYExaQMuYskwb+x1x7J371tWlbBdWHroy99KnVB6qIkUbs5X3UQ==" + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz", + "integrity": "sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==" }, "type-check": { "version": "0.4.0", @@ -16334,9 +16438,9 @@ } }, "updates": { - "version": "13.1.10", - "resolved": "https://registry.npmjs.org/updates/-/updates-13.1.10.tgz", - "integrity": "sha512-YSt1ncMoBXAQZndhLwiywvEGHXmA4424SlAf2HMUDuf8qE9Tlqj0s6IANb388HrjkybdZJkaadLSg/hkigwnuQ==", + "version": "13.2.1", + "resolved": "https://registry.npmjs.org/updates/-/updates-13.2.1.tgz", + "integrity": "sha512-d+nIbU2fl/PDEvUkbQch4uRdkXt9AQoPlH6b/FPTOAzF9voGbXgZNNxgO79Jeish24ZMfOqUl5lJcKSwMO2RJQ==", "dev": true }, "uri-js": { @@ -16374,6 +16478,11 @@ "integrity": "sha512-O11mqxmi7wMKCo6HKFt5AhO4BwY3VV68YU07tgxfz8zJTIxr4BpsezN49Ffwy9j3ZpwwJp4fkRwjRzq3uWE6Rg==", "dev": true }, + "uuid": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.0.tgz", + "integrity": "sha512-MXcSTerfPa4uqyzStbRoTgt5XIe3x5+42+q1sDuy3R5MDk66URdLMOZe5aPX/SQd+kuYAh0FdP/pO28IkQyTeg==" + }, "v8-compile-cache": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz", @@ -16400,43 +16509,35 @@ } }, "vite": { - "version": "3.1.8", - "resolved": "https://registry.npmjs.org/vite/-/vite-3.1.8.tgz", - "integrity": "sha512-m7jJe3nufUbuOfotkntGFupinL/fmuTNuQmiVE7cH2IZMuf4UbfbGYMUT3jVWgGYuRVLY9j8NnrRqgw5rr5QTg==", + "version": "3.2.4", + "resolved": "https://registry.npmjs.org/vite/-/vite-3.2.4.tgz", + "integrity": "sha512-Z2X6SRAffOUYTa+sLy3NQ7nlHFU100xwanq1WDwqaiFiCe+25zdxP1TfCS5ojPV2oDDcXudHIoPnI1Z/66B7Yw==", "dev": true, "requires": { "esbuild": "^0.15.9", "fsevents": "~2.3.2", - "postcss": "^8.4.16", + "postcss": "^8.4.18", "resolve": "^1.22.1", - "rollup": "~2.78.0" - }, - "dependencies": { - "rollup": { - "version": "2.78.1", - "resolved": "https://registry.npmjs.org/rollup/-/rollup-2.78.1.tgz", - "integrity": "sha512-VeeCgtGi4P+o9hIg+xz4qQpRl6R401LWEXBmxYKOV4zlF82lyhgh2hTZnheFUbANE8l2A41F458iwj2vEYaXJg==", - "dev": true, - "requires": { - "fsevents": "~2.3.2" - } - } + "rollup": "^2.79.1" } }, "vitest": { - "version": "0.24.3", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-0.24.3.tgz", - "integrity": "sha512-aM0auuPPgMSstWvr851hB74g/LKaKBzSxcG3da7ejfZbx08Y21JpZmbmDYrMTCGhVZKqTGwzcnLMwyfz2WzkhQ==", + "version": "0.25.2", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-0.25.2.tgz", + "integrity": "sha512-qqkzfzglEFbQY7IGkgSJkdOhoqHjwAao/OrphnHboeYHC5JzsVFoLCaB2lnAy8krhj7sbrFTVRApzpkTOeuDWQ==", "dev": true, "requires": { "@types/chai": "^4.3.3", "@types/chai-subset": "^1.3.3", "@types/node": "*", + "acorn": "^8.8.0", + "acorn-walk": "^8.2.0", "chai": "^4.3.6", "debug": "^4.3.4", "local-pkg": "^0.4.2", + "source-map": "^0.6.1", "strip-literal": "^0.4.2", - "tinybench": "^2.3.0", + "tinybench": "^2.3.1", "tinypool": "^0.3.0", "tinyspy": "^1.0.2", "vite": "^3.0.0" @@ -16453,15 +16554,15 @@ } }, "vue": { - "version": "3.2.41", - "resolved": "https://registry.npmjs.org/vue/-/vue-3.2.41.tgz", - "integrity": "sha512-uuuvnrDXEeZ9VUPljgHkqB5IaVO8SxhPpqF2eWOukVrBnRBx2THPSGQBnVRt0GrIG1gvCmFXMGbd7FqcT1ixNQ==", + "version": "3.2.45", + "resolved": "https://registry.npmjs.org/vue/-/vue-3.2.45.tgz", + "integrity": "sha512-9Nx/Mg2b2xWlXykmCwiTUCWHbWIj53bnkizBxKai1g61f2Xit700A1ljowpTIM11e3uipOeiPcSqnmBg6gyiaA==", "requires": { - "@vue/compiler-dom": "3.2.41", - "@vue/compiler-sfc": "3.2.41", - "@vue/runtime-dom": "3.2.41", - "@vue/server-renderer": "3.2.41", - "@vue/shared": "3.2.41" + "@vue/compiler-dom": "3.2.45", + "@vue/compiler-sfc": "3.2.45", + "@vue/runtime-dom": "3.2.45", + "@vue/server-renderer": "3.2.45", + "@vue/shared": "3.2.45" } }, "vue-bar-graph": { @@ -16489,9 +16590,9 @@ } }, "vue-loader": { - "version": "17.0.0", - "resolved": "https://registry.npmjs.org/vue-loader/-/vue-loader-17.0.0.tgz", - "integrity": "sha512-OWSXjrzIvbF2LtOUmxT3HYgwwubbfFelN8PAP9R9dwpIkj48TVioHhWWSx7W7fk+iF5cgg3CBJRxwTdtLU4Ecg==", + "version": "17.0.1", + "resolved": "https://registry.npmjs.org/vue-loader/-/vue-loader-17.0.1.tgz", + "integrity": "sha512-/OOyugJnImKCkAKrAvdsWMuwoCqGxWT5USLsjohzWbMgOwpA5wQmzQiLMzZd7DjhIfunzAGIApTOgIylz/kwcg==", "requires": { "chalk": "^4.1.0", "hash-sum": "^2.0.0", @@ -16507,9 +16608,9 @@ } }, "w3c-xmlserializer": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-3.0.0.tgz", - "integrity": "sha512-3WFqGEgSXIyGhOmAFtlicJNMjEps8b1MG31NCA0/vOF9+nKMUW1ckhi9cnNHmf88Rzw5V+dwIwsm2C7X8k9aQg==", + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-4.0.0.tgz", + "integrity": "sha512-d+BFHzbiCx6zGfz0HyQ6Rg69w9k19nviJspaj4yNscGjrHu94sVP+aRm75yEbCh+r2/yR+7q6hux9LVtbuTGBw==", "dev": true, "requires": { "xml-name-validator": "^4.0.0" @@ -16531,9 +16632,9 @@ "dev": true }, "webpack": { - "version": "5.74.0", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.74.0.tgz", - "integrity": "sha512-A2InDwnhhGN4LYctJj6M1JEaGL7Luj6LOmyBHjcI8529cm5p6VXiTIW2sn6ffvEAKmveLzvu4jrihwXtPojlAA==", + "version": "5.75.0", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.75.0.tgz", + "integrity": "sha512-piaIaoVJlqMsPtX/+3KTTO6jfvrSYgauFVdt8cr9LTHKmcq/AMd4mhzsiP7ZF/PGRNPGA8336jldh9l2Kt2ogQ==", "requires": { "@types/eslint-scope": "^3.7.3", "@types/estree": "^0.0.51", @@ -16620,28 +16721,29 @@ } }, "webpack-cli": { - "version": "4.10.0", - "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-4.10.0.tgz", - "integrity": "sha512-NLhDfH/h4O6UOy+0LSso42xvYypClINuMNBVVzX4vX98TmTaTUxwRbXdhucbFMd2qLaCTcLq/PdYrvi8onw90w==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-5.0.0.tgz", + "integrity": "sha512-AACDTo20yG+xn6HPW5xjbn2Be4KUzQPebWXsDMHwPPyKh9OnTOJgZN2Nc+g/FZKV3ObRTYsGvibAvc+5jAUrVA==", "requires": { "@discoveryjs/json-ext": "^0.5.0", - "@webpack-cli/configtest": "^1.2.0", - "@webpack-cli/info": "^1.5.0", - "@webpack-cli/serve": "^1.7.0", + "@webpack-cli/configtest": "^2.0.0", + "@webpack-cli/info": "^2.0.0", + "@webpack-cli/serve": "^2.0.0", "colorette": "^2.0.14", - "commander": "^7.0.0", + "commander": "^9.4.1", "cross-spawn": "^7.0.3", + "envinfo": "^7.7.3", "fastest-levenshtein": "^1.0.12", "import-local": "^3.0.2", - "interpret": "^2.2.0", - "rechoir": "^0.7.0", + "interpret": "^3.1.1", + "rechoir": "^0.8.0", "webpack-merge": "^5.7.3" }, "dependencies": { "commander": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz", - "integrity": "sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw==" + "version": "9.4.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-9.4.1.tgz", + "integrity": "sha512-5EEkTNyHNGFPD2H+c/dXXfQZYa/scCKasxWcXJaWnNJ99pnQN9Vnmqow+p+PlFPE63Q6mThaZws1T+HxfpgtPw==" } } }, @@ -16845,9 +16947,9 @@ } }, "ws": { - "version": "8.9.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.9.0.tgz", - "integrity": "sha512-Ja7nszREasGaYUYCI2k4lCKIRTt+y7XuqVoHR44YpI49TtryyqbqvDMn5eqfW7e6HzTukDRIsXqzVHScqRcafg==", + "version": "8.11.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", + "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==", "dev": true, "requires": {} }, diff --git a/package.json b/package.json index 035f3fd0b0..15c2601cd7 100644 --- a/package.json +++ b/package.json @@ -7,12 +7,16 @@ "node": ">= 14.0.0" }, "dependencies": { + "@citation-js/core": "0.6.1", + "@citation-js/plugin-bibtex": "0.6.1", + "@citation-js/plugin-csl": "0.6.4", + "@citation-js/plugin-software-formats": "0.6.0", "@claviska/jquery-minicolors": "2.3.6", "@mcaptcha/vanilla-glue": "0.1.0-alpha-3", - "@primer/octicons": "17.7.0", - "@vue/compiler-sfc": "3.2.41", + "@primer/octicons": "17.9.0", + "@vue/compiler-sfc": "3.2.45", "add-asset-webpack-plugin": "2.0.1", - "css-loader": "6.7.1", + "css-loader": "6.7.2", "dropzone": "6.0.0-beta.2", "easymde": "2.18.0", "esbuild-loader": "2.20.0", @@ -25,45 +29,46 @@ "less": "4.1.3", "less-loader": "11.1.0", "license-checker-webpack-plugin": "0.2.1", - "mermaid": "9.1.7", - "mini-css-extract-plugin": "2.6.1", + "mermaid": "9.2.2", + "mini-css-extract-plugin": "2.7.0", "monaco-editor": "0.34.1", "monaco-editor-webpack-plugin": "7.0.1", "pretty-ms": "8.0.0", "sortablejs": "1.15.0", - "swagger-ui-dist": "4.15.0", + "swagger-ui-dist": "4.15.5", "tippy.js": "6.3.7", "tributejs": "5.1.3", "uint8-to-base64": "0.2.0", - "vue": "3.2.41", + "vue": "3.2.45", "vue-bar-graph": "2.0.0", - "vue-loader": "17.0.0", + "vue-loader": "17.0.1", "vue3-calendar-heatmap": "2.0.0", - "webpack": "5.74.0", - "webpack-cli": "4.10.0", + "webpack": "5.75.0", + "webpack-cli": "5.0.0", "workbox-routing": "6.5.4", "workbox-strategies": "6.5.4", "worker-loader": "3.0.8", "wrap-ansi": "8.0.1" }, "devDependencies": { - "@playwright/test": "1.27.1", + "@playwright/test": "1.28.0", "@rollup/pluginutils": "5.0.2", - "@stoplight/spectral-cli": "6.5.1", - "eslint": "8.26.0", + "@stoplight/spectral-cli": "6.6.0", + "eslint": "8.28.0", "eslint-plugin-import": "2.26.0", "eslint-plugin-jquery": "1.5.1", "eslint-plugin-sonarjs": "0.16.0", - "eslint-plugin-unicorn": "44.0.2", - "eslint-plugin-vue": "9.6.0", - "jsdom": "20.0.1", + "eslint-plugin-unicorn": "45.0.0", + "eslint-plugin-vue": "9.7.0", + "jsdom": "20.0.3", "markdownlint-cli": "0.32.2", "postcss-less": "6.0.0", - "stylelint": "14.14.0", + "stylelint": "14.15.0", "stylelint-config-standard": "29.0.0", - "svgo": "3.0.0", - "updates": "13.1.10", - "vitest": "0.24.3" + "stylelint-declaration-strict-value": "1.9.1", + "svgo": "3.0.2", + "updates": "13.2.1", + "vitest": "0.25.2" }, "browserslist": [ "defaults", diff --git a/public/img/svg/gitea-matrix.svg b/public/img/svg/gitea-matrix.svg new file mode 100644 index 0000000000..cc5e08d3c7 --- /dev/null +++ b/public/img/svg/gitea-matrix.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/img/svg/octicon-arrow-down-left.svg b/public/img/svg/octicon-arrow-down-left.svg new file mode 100644 index 0000000000..f02bd330c9 --- /dev/null +++ b/public/img/svg/octicon-arrow-down-left.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/img/svg/octicon-arrow-down-right.svg b/public/img/svg/octicon-arrow-down-right.svg new file mode 100644 index 0000000000..dff9d36c1b --- /dev/null +++ b/public/img/svg/octicon-arrow-down-right.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/img/svg/octicon-arrow-up-left.svg b/public/img/svg/octicon-arrow-up-left.svg new file mode 100644 index 0000000000..0f5a452b8a --- /dev/null +++ b/public/img/svg/octicon-arrow-up-left.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/img/svg/octicon-arrow-up-right.svg b/public/img/svg/octicon-arrow-up-right.svg new file mode 100644 index 0000000000..896c9b60b4 --- /dev/null +++ b/public/img/svg/octicon-arrow-up-right.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/img/svg/octicon-clock-fill.svg b/public/img/svg/octicon-clock-fill.svg new file mode 100644 index 0000000000..5fcfb477c4 --- /dev/null +++ b/public/img/svg/octicon-clock-fill.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/img/svg/octicon-issue-tracked-by.svg b/public/img/svg/octicon-issue-tracked-by.svg new file mode 100644 index 0000000000..d4352a9430 --- /dev/null +++ b/public/img/svg/octicon-issue-tracked-by.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/img/svg/octicon-issue-tracked-in.svg b/public/img/svg/octicon-issue-tracked-in.svg new file mode 100644 index 0000000000..8910bd7a24 --- /dev/null +++ b/public/img/svg/octicon-issue-tracked-in.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/img/svg/octicon-project-roadmap.svg b/public/img/svg/octicon-project-roadmap.svg new file mode 100644 index 0000000000..afc3b223bd --- /dev/null +++ b/public/img/svg/octicon-project-roadmap.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/img/svg/octicon-project-symlink.svg b/public/img/svg/octicon-project-symlink.svg new file mode 100644 index 0000000000..2c889a090c --- /dev/null +++ b/public/img/svg/octicon-project-symlink.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/img/svg/octicon-skip-fill.svg b/public/img/svg/octicon-skip-fill.svg new file mode 100644 index 0000000000..6606a56df9 --- /dev/null +++ b/public/img/svg/octicon-skip-fill.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/routers/api/packages/api.go b/routers/api/packages/api.go index 6f53bc4ae0..b523725c48 100644 --- a/routers/api/packages/api.go +++ b/routers/api/packages/api.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package packages @@ -40,7 +39,9 @@ func reqPackageAccess(accessMode perm.AccessMode) func(ctx *context.Context) { } } -func Routes(ctx gocontext.Context) *web.Route { +// CommonRoutes provide endpoints for most package managers (except containers - see below) +// These are mounted on `/api/packages` (not `/api/v1/packages`) +func CommonRoutes(ctx gocontext.Context) *web.Route { r := web.NewRoute() r.Use(context.PackageContexter(ctx)) @@ -179,6 +180,7 @@ func Routes(ctx gocontext.Context) *web.Route { r.Group("/maven", func() { r.Put("/*", reqPackageAccess(perm.AccessModeWrite), maven.UploadPackageFile) r.Get("/*", maven.DownloadPackageFile) + r.Head("/*", maven.ProvidePackageFileHeader) }, reqPackageAccess(perm.AccessModeRead)) r.Group("/nuget", func() { r.Group("", func() { // Needs to be unauthenticated for the NuGet client. @@ -301,6 +303,9 @@ func Routes(ctx gocontext.Context) *web.Route { return r } +// ContainerRoutes provides endpoints that implement the OCI API to serve containers +// These have to be mounted on `/v2/...` to comply with the OCI spec: +// https://github.com/opencontainers/distribution-spec/blob/main/spec.md func ContainerRoutes(ctx gocontext.Context) *web.Route { r := web.NewRoute() diff --git a/routers/api/packages/composer/api.go b/routers/api/packages/composer/api.go index ed52d16513..a3bcf80417 100644 --- a/routers/api/packages/composer/api.go +++ b/routers/api/packages/composer/api.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package composer diff --git a/routers/api/packages/composer/composer.go b/routers/api/packages/composer/composer.go index 86ef7cbd9a..c6e0593b42 100644 --- a/routers/api/packages/composer/composer.go +++ b/routers/api/packages/composer/composer.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package composer @@ -184,7 +183,10 @@ func DownloadPackageFile(ctx *context.Context) { } defer s.Close() - ctx.ServeContent(pf.Name, s, pf.CreatedUnix.AsLocalTime()) + ctx.ServeContent(s, &context.ServeHeaderOptions{ + Filename: pf.Name, + LastModified: pf.CreatedUnix.AsLocalTime(), + }) } // UploadPackage creates a new package @@ -235,16 +237,20 @@ func UploadPackage(ctx *context.Context) { PackageFileInfo: packages_service.PackageFileInfo{ Filename: strings.ToLower(fmt.Sprintf("%s.%s.zip", strings.ReplaceAll(cp.Name, "/", "-"), cp.Version)), }, - Data: buf, - IsLead: true, + Creator: ctx.Doer, + Data: buf, + IsLead: true, }, ) if err != nil { - if err == packages_model.ErrDuplicatePackageVersion { + switch err { + case packages_model.ErrDuplicatePackageVersion: apiError(ctx, http.StatusBadRequest, err) - return + case packages_service.ErrQuotaTotalCount, packages_service.ErrQuotaTypeSize, packages_service.ErrQuotaTotalSize: + apiError(ctx, http.StatusForbidden, err) + default: + apiError(ctx, http.StatusInternalServerError, err) } - apiError(ctx, http.StatusInternalServerError, err) return } diff --git a/routers/api/packages/conan/auth.go b/routers/api/packages/conan/auth.go index 00855a97a4..f3adaf7bee 100644 --- a/routers/api/packages/conan/auth.go +++ b/routers/api/packages/conan/auth.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package conan @@ -31,7 +30,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS return nil } - u, err := user_model.GetUserByID(uid) + u, err := user_model.GetUserByID(req.Context(), uid) if err != nil { log.Error("GetUserByID: %v", err) return nil diff --git a/routers/api/packages/conan/conan.go b/routers/api/packages/conan/conan.go index dd078d6ad3..d538cc7d39 100644 --- a/routers/api/packages/conan/conan.go +++ b/routers/api/packages/conan/conan.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package conan @@ -348,8 +347,9 @@ func uploadFile(ctx *context.Context, fileFilter container.Set[string], fileKey Filename: strings.ToLower(filename), CompositeKey: fileKey, }, - Data: buf, - IsLead: isConanfileFile, + Creator: ctx.Doer, + Data: buf, + IsLead: isConanfileFile, Properties: map[string]string{ conan_module.PropertyRecipeUser: rref.User, conan_module.PropertyRecipeChannel: rref.Channel, @@ -416,11 +416,14 @@ func uploadFile(ctx *context.Context, fileFilter container.Set[string], fileKey pfci, ) if err != nil { - if err == packages_model.ErrDuplicatePackageFile { + switch err { + case packages_model.ErrDuplicatePackageFile: apiError(ctx, http.StatusBadRequest, err) - return + case packages_service.ErrQuotaTotalCount, packages_service.ErrQuotaTypeSize, packages_service.ErrQuotaTotalSize: + apiError(ctx, http.StatusForbidden, err) + default: + apiError(ctx, http.StatusInternalServerError, err) } - apiError(ctx, http.StatusInternalServerError, err) return } @@ -473,7 +476,10 @@ func downloadFile(ctx *context.Context, fileFilter container.Set[string], fileKe } defer s.Close() - ctx.ServeContent(pf.Name, s, pf.CreatedUnix.AsLocalTime()) + ctx.ServeContent(s, &context.ServeHeaderOptions{ + Filename: pf.Name, + LastModified: pf.CreatedUnix.AsLocalTime(), + }) } // DeleteRecipeV1 deletes the requested recipe(s) @@ -600,7 +606,7 @@ func DeletePackageV2(ctx *context.Context) { } func deleteRecipeOrPackage(apictx *context.Context, rref *conan_module.RecipeReference, ignoreRecipeRevision bool, pref *conan_module.PackageReference, ignorePackageRevision bool) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -672,7 +678,7 @@ func deleteRecipeOrPackage(apictx *context.Context, rref *conan_module.RecipeRef } if versionDeleted { - notification.NotifyPackageDelete(apictx.Doer, pd) + notification.NotifyPackageDelete(apictx, apictx.Doer, pd) } return nil diff --git a/routers/api/packages/conan/search.go b/routers/api/packages/conan/search.go index 39dd6362aa..2bcf9df162 100644 --- a/routers/api/packages/conan/search.go +++ b/routers/api/packages/conan/search.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package conan diff --git a/routers/api/packages/container/auth.go b/routers/api/packages/container/auth.go index 770068a3bf..e134f74c8f 100644 --- a/routers/api/packages/container/auth.go +++ b/routers/api/packages/container/auth.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package container @@ -35,7 +34,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS return user_model.NewGhostUser() } - u, err := user_model.GetUserByID(uid) + u, err := user_model.GetUserByID(req.Context(), uid) if err != nil { log.Error("GetUserByID: %v", err) return nil diff --git a/routers/api/packages/container/blob.go b/routers/api/packages/container/blob.go index 8a9cbd4a15..fd5819d506 100644 --- a/routers/api/packages/container/blob.go +++ b/routers/api/packages/container/blob.go @@ -1,14 +1,16 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package container import ( "context" "encoding/hex" + "errors" "fmt" + "os" "strings" + "sync" "code.gitea.io/gitea/models/db" packages_model "code.gitea.io/gitea/models/packages" @@ -16,9 +18,12 @@ import ( "code.gitea.io/gitea/modules/log" packages_module "code.gitea.io/gitea/modules/packages" container_module "code.gitea.io/gitea/modules/packages/container" + "code.gitea.io/gitea/modules/util" packages_service "code.gitea.io/gitea/services/packages" ) +var uploadVersionMutex sync.Mutex + // saveAsPackageBlob creates a package blob from an upload // The uploaded blob gets stored in a special upload version to link them to the package/image func saveAsPackageBlob(hsr packages_module.HashedSizeReader, pi *packages_service.PackageInfo) (*packages_model.PackageBlob, error) { @@ -28,7 +33,12 @@ func saveAsPackageBlob(hsr packages_module.HashedSizeReader, pi *packages_servic contentStore := packages_module.NewContentStore() - err := db.WithTx(func(ctx context.Context) error { + var uploadVersion *packages_model.PackageVersion + + // FIXME: Replace usage of mutex with database transaction + // https://github.com/go-gitea/gitea/pull/21862 + uploadVersionMutex.Lock() + err := db.WithTx(db.DefaultContext, func(ctx context.Context) error { created := true p := &packages_model.Package{ OwnerID: pi.Owner.ID, @@ -68,11 +78,30 @@ func saveAsPackageBlob(hsr packages_module.HashedSizeReader, pi *packages_servic } } + uploadVersion = pv + + return nil + }) + uploadVersionMutex.Unlock() + if err != nil { + return nil, err + } + + err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { pb, exists, err = packages_model.GetOrInsertBlob(ctx, pb) if err != nil { log.Error("Error inserting package blob: %v", err) return err } + // FIXME: Workaround to be removed in v1.20 + // https://github.com/go-gitea/gitea/issues/19586 + if exists { + err = contentStore.Has(packages_module.BlobHash256Key(pb.HashSHA256)) + if err != nil && (errors.Is(err, util.ErrNotExist) || errors.Is(err, os.ErrNotExist)) { + log.Debug("Package registry inconsistent: blob %s does not exist on file system", pb.HashSHA256) + exists = false + } + } if !exists { if err := contentStore.Save(packages_module.BlobHash256Key(pb.HashSHA256), hsr, hsr.Size()); err != nil { log.Error("Error saving package blob in content store: %v", err) @@ -83,7 +112,7 @@ func saveAsPackageBlob(hsr packages_module.HashedSizeReader, pi *packages_servic filename := strings.ToLower(fmt.Sprintf("sha256_%s", pb.HashSHA256)) pf := &packages_model.PackageFile{ - VersionID: pv.ID, + VersionID: uploadVersion.ID, BlobID: pb.ID, Name: filename, LowerName: filename, @@ -117,7 +146,7 @@ func saveAsPackageBlob(hsr packages_module.HashedSizeReader, pi *packages_servic } func deleteBlob(ownerID int64, image, digest string) error { - return db.WithTx(func(ctx context.Context) error { + return db.WithTx(db.DefaultContext, func(ctx context.Context) error { pfds, err := container_model.GetContainerBlobs(ctx, &container_model.BlobSearchOptions{ OwnerID: ownerID, Image: image, diff --git a/routers/api/packages/container/container.go b/routers/api/packages/container/container.go index 5bc64e1b29..cbbdf8eb88 100644 --- a/routers/api/packages/container/container.go +++ b/routers/api/packages/container/container.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package container @@ -10,6 +9,7 @@ import ( "io" "net/http" "net/url" + "os" "regexp" "strconv" "strings" @@ -24,6 +24,7 @@ import ( container_module "code.gitea.io/gitea/modules/packages/container" "code.gitea.io/gitea/modules/packages/container/oci" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/routers/api/packages/helper" packages_service "code.gitea.io/gitea/services/packages" container_service "code.gitea.io/gitea/services/packages/container" @@ -193,7 +194,7 @@ func InitiateUploadBlob(ctx *context.Context) { mount := ctx.FormTrim("mount") from := ctx.FormTrim("from") if mount != "" { - blob, _ := container_model.GetContainerBlob(ctx, &container_model.BlobSearchOptions{ + blob, _ := workaroundGetContainerBlob(ctx, &container_model.BlobSearchOptions{ Image: from, Digest: mount, }) @@ -406,7 +407,7 @@ func getBlobFromContext(ctx *context.Context) (*packages_model.PackageFileDescri return nil, container_model.ErrContainerBlobNotExist } - return container_model.GetContainerBlob(ctx, &container_model.BlobSearchOptions{ + return workaroundGetContainerBlob(ctx, &container_model.BlobSearchOptions{ OwnerID: ctx.Package.Owner.ID, Image: ctx.Params("image"), Digest: digest, @@ -548,7 +549,7 @@ func getManifestFromContext(ctx *context.Context) (*packages_model.PackageFileDe return nil, container_model.ErrContainerBlobNotExist } - return container_model.GetContainerBlob(ctx, opts) + return workaroundGetContainerBlob(ctx, opts) } // https://github.com/opencontainers/distribution-spec/blob/main/spec.md#checking-if-content-exists-in-the-registry @@ -688,3 +689,23 @@ func GetTagList(ctx *context.Context) { Tags: tags, }) } + +// FIXME: Workaround to be removed in v1.20 +// https://github.com/go-gitea/gitea/issues/19586 +func workaroundGetContainerBlob(ctx *context.Context, opts *container_model.BlobSearchOptions) (*packages_model.PackageFileDescriptor, error) { + blob, err := container_model.GetContainerBlob(ctx, opts) + if err != nil { + return nil, err + } + + err = packages_module.NewContentStore().Has(packages_module.BlobHash256Key(blob.Blob.HashSHA256)) + if err != nil { + if errors.Is(err, util.ErrNotExist) || errors.Is(err, os.ErrNotExist) { + log.Debug("Package registry inconsistent: blob %s does not exist on file system", blob.Blob.HashSHA256) + return nil, container_model.ErrContainerBlobNotExist + } + return nil, err + } + + return blob, nil +} diff --git a/routers/api/packages/container/errors.go b/routers/api/packages/container/errors.go index 0efbb081ca..1a9b0f32d2 100644 --- a/routers/api/packages/container/errors.go +++ b/routers/api/packages/container/errors.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package container diff --git a/routers/api/packages/container/manifest.go b/routers/api/packages/container/manifest.go index 8beed3dbb7..350933f3d2 100644 --- a/routers/api/packages/container/manifest.go +++ b/routers/api/packages/container/manifest.go @@ -1,13 +1,14 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package container import ( "context" + "errors" "fmt" "io" + "os" "strings" "code.gitea.io/gitea/models/db" @@ -19,6 +20,7 @@ import ( packages_module "code.gitea.io/gitea/modules/packages" container_module "code.gitea.io/gitea/modules/packages/container" "code.gitea.io/gitea/modules/packages/container/oci" + "code.gitea.io/gitea/modules/util" packages_service "code.gitea.io/gitea/services/packages" ) @@ -77,7 +79,7 @@ func processImageManifest(mci *manifestCreationInfo, buf *packages_module.Hashed return err } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -190,7 +192,7 @@ func processImageManifestIndex(mci *manifestCreationInfo, buf *packages_module.H return err } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -403,6 +405,15 @@ func createManifestBlob(ctx context.Context, mci *manifestCreationInfo, pv *pack log.Error("Error inserting package blob: %v", err) return nil, false, "", err } + // FIXME: Workaround to be removed in v1.20 + // https://github.com/go-gitea/gitea/issues/19586 + if exists { + err = packages_module.NewContentStore().Has(packages_module.BlobHash256Key(pb.HashSHA256)) + if err != nil && (errors.Is(err, util.ErrNotExist) || errors.Is(err, os.ErrNotExist)) { + log.Debug("Package registry inconsistent: blob %s does not exist on file system", pb.HashSHA256) + exists = false + } + } if !exists { contentStore := packages_module.NewContentStore() if err := contentStore.Save(packages_module.BlobHash256Key(pb.HashSHA256), buf, buf.Size()); err != nil { diff --git a/routers/api/packages/generic/generic.go b/routers/api/packages/generic/generic.go index 81891bec26..5fba02cacd 100644 --- a/routers/api/packages/generic/generic.go +++ b/routers/api/packages/generic/generic.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package generic @@ -53,7 +52,10 @@ func DownloadPackageFile(ctx *context.Context) { } defer s.Close() - ctx.ServeContent(pf.Name, s, pf.CreatedUnix.AsLocalTime()) + ctx.ServeContent(s, &context.ServeHeaderOptions{ + Filename: pf.Name, + LastModified: pf.CreatedUnix.AsLocalTime(), + }) } // UploadPackage uploads the specific generic package. @@ -104,16 +106,20 @@ func UploadPackage(ctx *context.Context) { PackageFileInfo: packages_service.PackageFileInfo{ Filename: filename, }, - Data: buf, - IsLead: true, + Creator: ctx.Doer, + Data: buf, + IsLead: true, }, ) if err != nil { - if err == packages_model.ErrDuplicatePackageFile { + switch err { + case packages_model.ErrDuplicatePackageFile: apiError(ctx, http.StatusConflict, err) - return + case packages_service.ErrQuotaTotalCount, packages_service.ErrQuotaTypeSize, packages_service.ErrQuotaTotalSize: + apiError(ctx, http.StatusForbidden, err) + default: + apiError(ctx, http.StatusInternalServerError, err) } - apiError(ctx, http.StatusInternalServerError, err) return } diff --git a/routers/api/packages/helm/helm.go b/routers/api/packages/helm/helm.go index 9c85e0874f..af863bc4b9 100644 --- a/routers/api/packages/helm/helm.go +++ b/routers/api/packages/helm/helm.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package helm @@ -23,7 +22,7 @@ import ( "code.gitea.io/gitea/routers/api/packages/helper" packages_service "code.gitea.io/gitea/services/packages" - "gopkg.in/yaml.v2" + "gopkg.in/yaml.v3" ) func apiError(ctx *context.Context, status int, obj interface{}) { @@ -138,7 +137,10 @@ func DownloadPackageFile(ctx *context.Context) { } defer s.Close() - ctx.ServeContent(pf.Name, s, pf.CreatedUnix.AsLocalTime()) + ctx.ServeContent(s, &context.ServeHeaderOptions{ + Filename: pf.Name, + LastModified: pf.CreatedUnix.AsLocalTime(), + }) } // UploadPackage creates a new package @@ -186,17 +188,21 @@ func UploadPackage(ctx *context.Context) { PackageFileInfo: packages_service.PackageFileInfo{ Filename: createFilename(metadata), }, + Creator: ctx.Doer, Data: buf, IsLead: true, OverwriteExisting: true, }, ) if err != nil { - if err == packages_model.ErrDuplicatePackageVersion { + switch err { + case packages_model.ErrDuplicatePackageVersion: apiError(ctx, http.StatusConflict, err) - return + case packages_service.ErrQuotaTotalCount, packages_service.ErrQuotaTypeSize, packages_service.ErrQuotaTotalSize: + apiError(ctx, http.StatusForbidden, err) + default: + apiError(ctx, http.StatusInternalServerError, err) } - apiError(ctx, http.StatusInternalServerError, err) return } diff --git a/routers/api/packages/helper/helper.go b/routers/api/packages/helper/helper.go index 8cde84023f..660aaec1a3 100644 --- a/routers/api/packages/helper/helper.go +++ b/routers/api/packages/helper/helper.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package helper diff --git a/routers/api/packages/maven/api.go b/routers/api/packages/maven/api.go index b60a317814..167fe42b56 100644 --- a/routers/api/packages/maven/api.go +++ b/routers/api/packages/maven/api.go @@ -1,12 +1,10 @@ // 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. +// SPDX-License-Identifier: MIT package maven import ( "encoding/xml" - "sort" "strings" packages_model "code.gitea.io/gitea/models/packages" @@ -23,12 +21,8 @@ type MetadataResponse struct { Version []string `xml:"versioning>versions>version"` } +// pds is expected to be sorted ascending by CreatedUnix func createMetadataResponse(pds []*packages_model.PackageDescriptor) *MetadataResponse { - sort.Slice(pds, func(i, j int) bool { - // Maven and Gradle order packages by their creation timestamp and not by their version string - return pds[i].Version.CreatedUnix < pds[j].Version.CreatedUnix - }) - var release *packages_model.PackageDescriptor versions := make([]string, 0, len(pds)) diff --git a/routers/api/packages/maven/maven.go b/routers/api/packages/maven/maven.go index bf00c199f5..d0c9983cbf 100644 --- a/routers/api/packages/maven/maven.go +++ b/routers/api/packages/maven/maven.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package maven @@ -9,13 +8,15 @@ import ( "crypto/sha1" "crypto/sha256" "crypto/sha512" + "encoding/hex" "encoding/xml" "errors" - "fmt" "io" "net/http" "path/filepath" "regexp" + "sort" + "strconv" "strings" packages_model "code.gitea.io/gitea/models/packages" @@ -34,6 +35,10 @@ const ( extensionSHA1 = ".sha1" extensionSHA256 = ".sha256" extensionSHA512 = ".sha512" + extensionPom = ".pom" + extensionJar = ".jar" + contentTypeJar = "application/java-archive" + contentTypeXML = "text/xml" ) var ( @@ -49,6 +54,15 @@ func apiError(ctx *context.Context, status int, obj interface{}) { // DownloadPackageFile serves the content of a package func DownloadPackageFile(ctx *context.Context) { + handlePackageFile(ctx, true) +} + +// ProvidePackageFileHeader provides only the headers describing a package +func ProvidePackageFileHeader(ctx *context.Context) { + handlePackageFile(ctx, false) +} + +func handlePackageFile(ctx *context.Context, serveContent bool) { params, err := extractPathParameters(ctx) if err != nil { apiError(ctx, http.StatusBadRequest, err) @@ -58,7 +72,7 @@ func DownloadPackageFile(ctx *context.Context) { if params.IsMeta && params.Version == "" { serveMavenMetadata(ctx, params) } else { - servePackageFile(ctx, params) + servePackageFile(ctx, params, serveContent) } } @@ -82,6 +96,11 @@ func serveMavenMetadata(ctx *context.Context, params parameters) { return } + sort.Slice(pds, func(i, j int) bool { + // Maven and Gradle order packages by their creation timestamp and not by their version string + return pds[i].Version.CreatedUnix < pds[j].Version.CreatedUnix + }) + xmlMetadata, err := xml.Marshal(createMetadataResponse(pds)) if err != nil { apiError(ctx, http.StatusInternalServerError, err) @@ -89,6 +108,9 @@ func serveMavenMetadata(ctx *context.Context, params parameters) { } xmlMetadataWithHeader := append([]byte(xml.Header), xmlMetadata...) + latest := pds[len(pds)-1] + ctx.Resp.Header().Set("Last-Modified", latest.Version.CreatedUnix.Format(http.TimeFormat)) + ext := strings.ToLower(filepath.Ext(params.Filename)) if isChecksumExtension(ext) { var hash []byte @@ -106,14 +128,19 @@ func serveMavenMetadata(ctx *context.Context, params parameters) { tmp := sha512.Sum512(xmlMetadataWithHeader) hash = tmp[:] } - ctx.PlainText(http.StatusOK, fmt.Sprintf("%x", hash)) + ctx.PlainText(http.StatusOK, hex.EncodeToString(hash)) return } - ctx.PlainTextBytes(http.StatusOK, xmlMetadataWithHeader) + ctx.Resp.Header().Set("Content-Length", strconv.Itoa(len(xmlMetadataWithHeader))) + ctx.Resp.Header().Set("Content-Type", contentTypeXML) + + if _, err := ctx.Resp.Write(xmlMetadataWithHeader); err != nil { + log.Error("write bytes failed: %v", err) + } } -func servePackageFile(ctx *context.Context, params parameters) { +func servePackageFile(ctx *context.Context, params parameters, serveContent bool) { packageName := params.GroupID + "-" + params.ArtifactID pv, err := packages_model.GetVersionByNameAndVersion(ctx, ctx.Package.Owner.ID, packages_model.TypeMaven, packageName, params.Version) @@ -165,6 +192,23 @@ func servePackageFile(ctx *context.Context, params parameters) { return } + opts := &context.ServeHeaderOptions{ + ContentLength: &pb.Size, + LastModified: pf.CreatedUnix.AsLocalTime(), + } + switch ext { + case extensionJar: + opts.ContentType = contentTypeJar + case extensionPom: + opts.ContentType = contentTypeXML + } + + if !serveContent { + ctx.SetServeHeaders(opts) + ctx.Status(http.StatusOK) + return + } + s, err := packages_module.NewContentStore().Get(packages_module.BlobHash256Key(pb.HashSHA256)) if err != nil { apiError(ctx, http.StatusInternalServerError, err) @@ -177,7 +221,9 @@ func servePackageFile(ctx *context.Context, params parameters) { } } - ctx.ServeContent(pf.Name, s, pf.CreatedUnix.AsLocalTime()) + opts.Filename = pf.Name + + ctx.ServeContent(s, opts) } // UploadPackageFile adds a file to the package. If the package does not exist, it gets created. @@ -266,13 +312,14 @@ func UploadPackageFile(ctx *context.Context) { PackageFileInfo: packages_service.PackageFileInfo{ Filename: params.Filename, }, + Creator: ctx.Doer, Data: buf, IsLead: false, OverwriteExisting: params.IsMeta, } // If it's the package pom file extract the metadata - if ext == ".pom" { + if ext == extensionPom { pfci.IsLead = true var err error @@ -312,11 +359,14 @@ func UploadPackageFile(ctx *context.Context) { pfci, ) if err != nil { - if err == packages_model.ErrDuplicatePackageFile { + switch err { + case packages_model.ErrDuplicatePackageFile: apiError(ctx, http.StatusBadRequest, err) - return + case packages_service.ErrQuotaTotalCount, packages_service.ErrQuotaTypeSize, packages_service.ErrQuotaTotalSize: + apiError(ctx, http.StatusForbidden, err) + default: + apiError(ctx, http.StatusInternalServerError, err) } - apiError(ctx, http.StatusInternalServerError, err) return } diff --git a/routers/api/packages/npm/api.go b/routers/api/packages/npm/api.go index 490387a0e4..f8d50f03cf 100644 --- a/routers/api/packages/npm/api.go +++ b/routers/api/packages/npm/api.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package npm diff --git a/routers/api/packages/npm/npm.go b/routers/api/packages/npm/npm.go index 82dae0cf43..1a09cb6f36 100644 --- a/routers/api/packages/npm/npm.go +++ b/routers/api/packages/npm/npm.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package npm @@ -103,7 +102,10 @@ func DownloadPackageFile(ctx *context.Context) { } defer s.Close() - ctx.ServeContent(pf.Name, s, pf.CreatedUnix.AsLocalTime()) + ctx.ServeContent(s, &context.ServeHeaderOptions{ + Filename: pf.Name, + LastModified: pf.CreatedUnix.AsLocalTime(), + }) } // DownloadPackageFileByName finds the version and serves the contents of a package @@ -146,7 +148,10 @@ func DownloadPackageFileByName(ctx *context.Context) { } defer s.Close() - ctx.ServeContent(pf.Name, s, pf.CreatedUnix.AsLocalTime()) + ctx.ServeContent(s, &context.ServeHeaderOptions{ + Filename: pf.Name, + LastModified: pf.CreatedUnix.AsLocalTime(), + }) } // UploadPackage creates a new package @@ -180,16 +185,20 @@ func UploadPackage(ctx *context.Context) { PackageFileInfo: packages_service.PackageFileInfo{ Filename: npmPackage.Filename, }, - Data: buf, - IsLead: true, + Creator: ctx.Doer, + Data: buf, + IsLead: true, }, ) if err != nil { - if err == packages_model.ErrDuplicatePackageVersion { + switch err { + case packages_model.ErrDuplicatePackageVersion: apiError(ctx, http.StatusBadRequest, err) - return + case packages_service.ErrQuotaTotalCount, packages_service.ErrQuotaTypeSize, packages_service.ErrQuotaTotalSize: + apiError(ctx, http.StatusForbidden, err) + default: + apiError(ctx, http.StatusInternalServerError, err) } - apiError(ctx, http.StatusInternalServerError, err) return } @@ -351,7 +360,7 @@ func setPackageTag(tag string, pv *packages_model.PackageVersion, deleteOnly boo return errInvalidTagName } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -396,8 +405,9 @@ func setPackageTag(tag string, pv *packages_model.PackageVersion, deleteOnly boo func PackageSearch(ctx *context.Context) { pvs, total, err := packages_model.SearchLatestVersions(ctx, &packages_model.PackageSearchOptions{ - OwnerID: ctx.Package.Owner.ID, - Type: packages_model.TypeNpm, + OwnerID: ctx.Package.Owner.ID, + Type: packages_model.TypeNpm, + IsInternal: util.OptionalBoolFalse, Name: packages_model.SearchValue{ ExactMatch: false, Value: ctx.FormTrim("text"), diff --git a/routers/api/packages/nuget/api_v2.go b/routers/api/packages/nuget/api_v2.go index 60a5d9c0e4..c545d0fc4e 100644 --- a/routers/api/packages/nuget/api_v2.go +++ b/routers/api/packages/nuget/api_v2.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package nuget diff --git a/routers/api/packages/nuget/api_v3.go b/routers/api/packages/nuget/api_v3.go index bb3e447bd6..b5900b6c0b 100644 --- a/routers/api/packages/nuget/api_v3.go +++ b/routers/api/packages/nuget/api_v3.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package nuget diff --git a/routers/api/packages/nuget/auth.go b/routers/api/packages/nuget/auth.go index 1dad452648..890c930184 100644 --- a/routers/api/packages/nuget/auth.go +++ b/routers/api/packages/nuget/auth.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package nuget @@ -30,7 +29,7 @@ func (a *Auth) Verify(req *http.Request, w http.ResponseWriter, store auth.DataS return nil } - u, err := user_model.GetUserByID(token.UID) + u, err := user_model.GetUserByID(req.Context(), token.UID) if err != nil { log.Error("GetUserByID: %v", err) return nil diff --git a/routers/api/packages/nuget/links.go b/routers/api/packages/nuget/links.go index 618b54ae8d..1b02e46184 100644 --- a/routers/api/packages/nuget/links.go +++ b/routers/api/packages/nuget/links.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package nuget diff --git a/routers/api/packages/nuget/nuget.go b/routers/api/packages/nuget/nuget.go index e84aef3160..d6f7d1d7f6 100644 --- a/routers/api/packages/nuget/nuget.go +++ b/routers/api/packages/nuget/nuget.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package nuget @@ -342,7 +341,10 @@ func DownloadPackageFile(ctx *context.Context) { } defer s.Close() - ctx.ServeContent(pf.Name, s, pf.CreatedUnix.AsLocalTime()) + ctx.ServeContent(s, &context.ServeHeaderOptions{ + Filename: pf.Name, + LastModified: pf.CreatedUnix.AsLocalTime(), + }) } // UploadPackage creates a new package with the metadata contained in the uploaded nupgk file @@ -374,16 +376,20 @@ func UploadPackage(ctx *context.Context) { PackageFileInfo: packages_service.PackageFileInfo{ Filename: strings.ToLower(fmt.Sprintf("%s.%s.nupkg", np.ID, np.Version)), }, - Data: buf, - IsLead: true, + Creator: ctx.Doer, + Data: buf, + IsLead: true, }, ) if err != nil { - if err == packages_model.ErrDuplicatePackageVersion { + switch err { + case packages_model.ErrDuplicatePackageVersion: apiError(ctx, http.StatusConflict, err) - return + case packages_service.ErrQuotaTotalCount, packages_service.ErrQuotaTypeSize, packages_service.ErrQuotaTotalSize: + apiError(ctx, http.StatusForbidden, err) + default: + apiError(ctx, http.StatusInternalServerError, err) } - apiError(ctx, http.StatusInternalServerError, err) return } @@ -428,8 +434,9 @@ func UploadSymbolPackage(ctx *context.Context) { PackageFileInfo: packages_service.PackageFileInfo{ Filename: strings.ToLower(fmt.Sprintf("%s.%s.snupkg", np.ID, np.Version)), }, - Data: buf, - IsLead: false, + Creator: ctx.Doer, + Data: buf, + IsLead: false, }, ) if err != nil { @@ -438,6 +445,8 @@ func UploadSymbolPackage(ctx *context.Context) { apiError(ctx, http.StatusNotFound, err) case packages_model.ErrDuplicatePackageFile: apiError(ctx, http.StatusConflict, err) + case packages_service.ErrQuotaTypeSize, packages_service.ErrQuotaTotalSize: + apiError(ctx, http.StatusForbidden, err) default: apiError(ctx, http.StatusInternalServerError, err) } @@ -452,8 +461,9 @@ func UploadSymbolPackage(ctx *context.Context) { Filename: strings.ToLower(pdb.Name), CompositeKey: strings.ToLower(pdb.ID), }, - Data: pdb.Content, - IsLead: false, + Creator: ctx.Doer, + Data: pdb.Content, + IsLead: false, Properties: map[string]string{ nuget_module.PropertySymbolID: strings.ToLower(pdb.ID), }, @@ -463,6 +473,8 @@ func UploadSymbolPackage(ctx *context.Context) { switch err { case packages_model.ErrDuplicatePackageFile: apiError(ctx, http.StatusConflict, err) + case packages_service.ErrQuotaTypeSize, packages_service.ErrQuotaTotalSize: + apiError(ctx, http.StatusForbidden, err) default: apiError(ctx, http.StatusInternalServerError, err) } @@ -552,7 +564,10 @@ func DownloadSymbolFile(ctx *context.Context) { } defer s.Close() - ctx.ServeContent(pf.Name, s, pf.CreatedUnix.AsLocalTime()) + ctx.ServeContent(s, &context.ServeHeaderOptions{ + Filename: pf.Name, + LastModified: pf.CreatedUnix.AsLocalTime(), + }) } // DeletePackage hard deletes the package diff --git a/routers/api/packages/pub/pub.go b/routers/api/packages/pub/pub.go index 9af0ceeb0e..247950a214 100644 --- a/routers/api/packages/pub/pub.go +++ b/routers/api/packages/pub/pub.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package pub @@ -199,16 +198,20 @@ func UploadPackageFile(ctx *context.Context) { PackageFileInfo: packages_service.PackageFileInfo{ Filename: strings.ToLower(pck.Version + ".tar.gz"), }, - Data: buf, - IsLead: true, + Creator: ctx.Doer, + Data: buf, + IsLead: true, }, ) if err != nil { - if err == packages_model.ErrDuplicatePackageVersion { + switch err { + case packages_model.ErrDuplicatePackageVersion: apiError(ctx, http.StatusBadRequest, err) - return + case packages_service.ErrQuotaTotalCount, packages_service.ErrQuotaTypeSize, packages_service.ErrQuotaTotalSize: + apiError(ctx, http.StatusForbidden, err) + default: + apiError(ctx, http.StatusInternalServerError, err) } - apiError(ctx, http.StatusInternalServerError, err) return } @@ -271,5 +274,8 @@ func DownloadPackageFile(ctx *context.Context) { } defer s.Close() - ctx.ServeContent(pf.Name, s, pf.CreatedUnix.AsLocalTime()) + ctx.ServeContent(s, &context.ServeHeaderOptions{ + Filename: pf.Name, + LastModified: pf.CreatedUnix.AsLocalTime(), + }) } diff --git a/routers/api/packages/pypi/pypi.go b/routers/api/packages/pypi/pypi.go index 66380d832c..609c63dc64 100644 --- a/routers/api/packages/pypi/pypi.go +++ b/routers/api/packages/pypi/pypi.go @@ -1,11 +1,10 @@ // 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. +// SPDX-License-Identifier: MIT package pypi import ( - "fmt" + "encoding/hex" "io" "net/http" "regexp" @@ -21,9 +20,11 @@ import ( packages_service "code.gitea.io/gitea/services/packages" ) -// https://www.python.org/dev/peps/pep-0503/#normalized-names -var normalizer = strings.NewReplacer(".", "-", "_", "-") -var nameMatcher = regexp.MustCompile(`\A[a-zA-Z0-9\.\-_]+\z`) +// https://peps.python.org/pep-0426/#name +var ( + normalizer = strings.NewReplacer(".", "-", "_", "-") + nameMatcher = regexp.MustCompile(`\A(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\.\-_]*[a-zA-Z0-9])\z`) +) // https://peps.python.org/pep-0440/#appendix-b-parsing-version-strings-with-regular-expressions var versionMatcher = regexp.MustCompile(`\Av?` + @@ -95,7 +96,10 @@ func DownloadPackageFile(ctx *context.Context) { } defer s.Close() - ctx.ServeContent(pf.Name, s, pf.CreatedUnix.AsLocalTime()) + ctx.ServeContent(s, &context.ServeHeaderOptions{ + Filename: pf.Name, + LastModified: pf.CreatedUnix.AsLocalTime(), + }) } // UploadPackageFile adds a file to the package. If the package does not exist, it gets created. @@ -116,7 +120,7 @@ func UploadPackageFile(ctx *context.Context) { _, _, hashSHA256, _ := buf.Sums() - if !strings.EqualFold(ctx.Req.FormValue("sha256_digest"), fmt.Sprintf("%x", hashSHA256)) { + if !strings.EqualFold(ctx.Req.FormValue("sha256_digest"), hex.EncodeToString(hashSHA256)) { apiError(ctx, http.StatusBadRequest, "hash mismatch") return } @@ -128,7 +132,7 @@ func UploadPackageFile(ctx *context.Context) { packageName := normalizer.Replace(ctx.Req.FormValue("name")) packageVersion := ctx.Req.FormValue("version") - if !nameMatcher.MatchString(packageName) || !versionMatcher.MatchString(packageVersion) { + if !isValidNameAndVersion(packageName, packageVersion) { apiError(ctx, http.StatusBadRequest, "invalid name or version") return } @@ -146,7 +150,7 @@ func UploadPackageFile(ctx *context.Context) { Name: packageName, Version: packageVersion, }, - SemverCompatible: true, + SemverCompatible: false, Creator: ctx.Doer, Metadata: &pypi_module.Metadata{ Author: ctx.Req.FormValue("author"), @@ -162,18 +166,26 @@ func UploadPackageFile(ctx *context.Context) { PackageFileInfo: packages_service.PackageFileInfo{ Filename: fileHeader.Filename, }, - Data: buf, - IsLead: true, + Creator: ctx.Doer, + Data: buf, + IsLead: true, }, ) if err != nil { - if err == packages_model.ErrDuplicatePackageFile { + switch err { + case packages_model.ErrDuplicatePackageFile: apiError(ctx, http.StatusBadRequest, err) - return + case packages_service.ErrQuotaTotalCount, packages_service.ErrQuotaTypeSize, packages_service.ErrQuotaTotalSize: + apiError(ctx, http.StatusForbidden, err) + default: + apiError(ctx, http.StatusInternalServerError, err) } - apiError(ctx, http.StatusInternalServerError, err) return } ctx.Status(http.StatusCreated) } + +func isValidNameAndVersion(packageName, packageVersion string) bool { + return nameMatcher.MatchString(packageName) && versionMatcher.MatchString(packageVersion) +} diff --git a/routers/api/packages/pypi/pypi_test.go b/routers/api/packages/pypi/pypi_test.go new file mode 100644 index 0000000000..3023692177 --- /dev/null +++ b/routers/api/packages/pypi/pypi_test.go @@ -0,0 +1,38 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package pypi + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestIsValidNameAndVersion(t *testing.T) { + // The test cases below were created from the following Python PEPs: + // https://peps.python.org/pep-0426/#name + // https://peps.python.org/pep-0440/#appendix-b-parsing-version-strings-with-regular-expressions + + // Valid Cases + assert.True(t, isValidNameAndVersion("A", "1.0.1")) + assert.True(t, isValidNameAndVersion("Test.Name.1234", "1.0.1")) + assert.True(t, isValidNameAndVersion("test_name", "1.0.1")) + assert.True(t, isValidNameAndVersion("test-name", "1.0.1")) + assert.True(t, isValidNameAndVersion("test-name", "v1.0.1")) + assert.True(t, isValidNameAndVersion("test-name", "2012.4")) + assert.True(t, isValidNameAndVersion("test-name", "1.0.1-alpha")) + assert.True(t, isValidNameAndVersion("test-name", "1.0.1a1")) + assert.True(t, isValidNameAndVersion("test-name", "1.0b2.r345.dev456")) + assert.True(t, isValidNameAndVersion("test-name", "1!1.0.1")) + assert.True(t, isValidNameAndVersion("test-name", "1.0.1+local.1")) + + // Invalid Cases + assert.False(t, isValidNameAndVersion(".test-name", "1.0.1")) + assert.False(t, isValidNameAndVersion("test!name", "1.0.1")) + assert.False(t, isValidNameAndVersion("-test-name", "1.0.1")) + assert.False(t, isValidNameAndVersion("test-name-", "1.0.1")) + assert.False(t, isValidNameAndVersion("test-name", "a1.0.1")) + assert.False(t, isValidNameAndVersion("test-name", "1.0.1aa")) + assert.False(t, isValidNameAndVersion("test-name", "1.0.0-alpha.beta")) +} diff --git a/routers/api/packages/rubygems/rubygems.go b/routers/api/packages/rubygems/rubygems.go index 319c94b91f..c1a10b5e78 100644 --- a/routers/api/packages/rubygems/rubygems.go +++ b/routers/api/packages/rubygems/rubygems.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package rubygems @@ -77,7 +76,9 @@ func enumeratePackages(ctx *context.Context, filename string, pvs []*packages_mo }) } - ctx.SetServeHeaders(filename + ".gz") + ctx.SetServeHeaders(&context.ServeHeaderOptions{ + Filename: filename + ".gz", + }) zw := gzip.NewWriter(ctx.Resp) defer zw.Close() @@ -115,7 +116,9 @@ func ServePackageSpecification(ctx *context.Context) { return } - ctx.SetServeHeaders(filename) + ctx.SetServeHeaders(&context.ServeHeaderOptions{ + Filename: filename, + }) zw := zlib.NewWriter(ctx.Resp) defer zw.Close() @@ -188,7 +191,10 @@ func DownloadPackageFile(ctx *context.Context) { } defer s.Close() - ctx.ServeContent(pf.Name, s, pf.CreatedUnix.AsLocalTime()) + ctx.ServeContent(s, &context.ServeHeaderOptions{ + Filename: pf.Name, + LastModified: pf.CreatedUnix.AsLocalTime(), + }) } // UploadPackageFile adds a file to the package. If the package does not exist, it gets created. @@ -242,16 +248,20 @@ func UploadPackageFile(ctx *context.Context) { PackageFileInfo: packages_service.PackageFileInfo{ Filename: filename, }, - Data: buf, - IsLead: true, + Creator: ctx.Doer, + Data: buf, + IsLead: true, }, ) if err != nil { - if err == packages_model.ErrDuplicatePackageVersion { + switch err { + case packages_model.ErrDuplicatePackageVersion: apiError(ctx, http.StatusBadRequest, err) - return + case packages_service.ErrQuotaTotalCount, packages_service.ErrQuotaTypeSize, packages_service.ErrQuotaTotalSize: + apiError(ctx, http.StatusForbidden, err) + default: + apiError(ctx, http.StatusInternalServerError, err) } - apiError(ctx, http.StatusInternalServerError, err) return } diff --git a/routers/api/packages/vagrant/vagrant.go b/routers/api/packages/vagrant/vagrant.go index 7750e5dc4b..7b76ab79b0 100644 --- a/routers/api/packages/vagrant/vagrant.go +++ b/routers/api/packages/vagrant/vagrant.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package vagrant @@ -193,19 +192,23 @@ func UploadPackageFile(ctx *context.Context) { PackageFileInfo: packages_service.PackageFileInfo{ Filename: strings.ToLower(boxProvider), }, - Data: buf, - IsLead: true, + Creator: ctx.Doer, + Data: buf, + IsLead: true, Properties: map[string]string{ vagrant_module.PropertyProvider: strings.TrimSuffix(boxProvider, ".box"), }, }, ) if err != nil { - if err == packages_model.ErrDuplicatePackageFile { + switch err { + case packages_model.ErrDuplicatePackageFile: apiError(ctx, http.StatusConflict, err) - return + case packages_service.ErrQuotaTotalCount, packages_service.ErrQuotaTypeSize, packages_service.ErrQuotaTotalSize: + apiError(ctx, http.StatusForbidden, err) + default: + apiError(ctx, http.StatusInternalServerError, err) } - apiError(ctx, http.StatusInternalServerError, err) return } @@ -235,5 +238,8 @@ func DownloadPackageFile(ctx *context.Context) { } defer s.Close() - ctx.ServeContent(pf.Name, s, pf.CreatedUnix.AsLocalTime()) + ctx.ServeContent(s, &context.ServeHeaderOptions{ + Filename: pf.Name, + LastModified: pf.CreatedUnix.AsLocalTime(), + }) } diff --git a/routers/api/v1/activitypub/create.go b/routers/api/v1/activitypub/create.go index 38ee898e3b..11dff238f6 100644 --- a/routers/api/v1/activitypub/create.go +++ b/routers/api/v1/activitypub/create.go @@ -135,7 +135,7 @@ func createRepository(ctx context.Context, repository *forgefed.Repository) erro } // Check if repo exists - _, err = repo_model.GetRepositoryByOwnerAndNameCtx(ctx, user.Name, repository.Name.String()) + _, err = repo_model.GetRepositoryByOwnerAndName(ctx, user.Name, repository.Name.String()) if err == nil { return nil } @@ -244,7 +244,7 @@ func createPullRequest(ctx context.Context, ticket *forgefed.Ticket) error { if err != nil { return err } - originRepo, err := repo_model.GetRepositoryByOwnerAndName(originUsername, originReponame) + originRepo, err := repo_model.GetRepositoryByOwnerAndName(ctx, originUsername, originReponame) if err != nil { return err } @@ -252,7 +252,7 @@ func createPullRequest(ctx context.Context, ticket *forgefed.Ticket) error { if err != nil { return err } - targetRepo, err := repo_model.GetRepositoryByOwnerAndName(targetUsername, targetReponame) + targetRepo, err := repo_model.GetRepositoryByOwnerAndName(ctx, targetUsername, targetReponame) if err != nil { return err } @@ -300,7 +300,7 @@ func createComment(ctx context.Context, note *ap.Note) error { if err != nil { return err } - repo, err := repo_model.GetRepositoryByOwnerAndNameCtx(ctx, username, reponame) + repo, err := repo_model.GetRepositoryByOwnerAndName(ctx, username, reponame) if err != nil { return err } @@ -308,7 +308,7 @@ func createComment(ctx context.Context, note *ap.Note) error { if err != nil { return err } - _, err = issues_model.CreateCommentCtx(ctx, &issues_model.CreateCommentOptions{ + _, err = issues_model.CreateComment(ctx, &issues_model.CreateCommentOptions{ Doer: user, Repo: repo, Issue: issue, diff --git a/routers/api/v1/activitypub/person.go b/routers/api/v1/activitypub/person.go index 268e5092b1..d82dd0502a 100644 --- a/routers/api/v1/activitypub/person.go +++ b/routers/api/v1/activitypub/person.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package activitypub @@ -218,7 +217,7 @@ func PersonOutbox(ctx *context.APIContext) { // TODO: Remove this code and implement an ActionStarRepo type, so `GetFeeds` // can handle this with correct pagination and ordering. - stars, err := repo_model.GetStarredRepos(ctx.ContextUser.ID, false, db.ListOptions{Page: 1, PageSize: 1000000}) + stars, err := repo_model.GetStarredRepos(ctx, ctx.ContextUser.ID, false, db.ListOptions{Page: 1, PageSize: 1000000}) if err != nil { ctx.ServerError("Couldn't fetch stars", err) return @@ -339,7 +338,7 @@ func PersonLiked(ctx *context.APIContext) { iri := ctx.ContextUser.GetIRI() - repos, count, err := repo_model.SearchRepository(&repo_model.SearchRepoOptions{ + repos, count, err := repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{ Actor: ctx.Doer, Private: ctx.IsSigned, StarredByID: ctx.ContextUser.ID, diff --git a/routers/api/v1/activitypub/reqsignature.go b/routers/api/v1/activitypub/reqsignature.go index 1d19c1ddb2..8129b4539c 100644 --- a/routers/api/v1/activitypub/reqsignature.go +++ b/routers/api/v1/activitypub/reqsignature.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package activitypub diff --git a/routers/api/v1/admin/adopt.go b/routers/api/v1/admin/adopt.go index 48222f89eb..0e4e498e98 100644 --- a/routers/api/v1/admin/adopt.go +++ b/routers/api/v1/admin/adopt.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/api/v1/admin/cron.go b/routers/api/v1/admin/cron.go index 0c4333b892..cc8c6c9e23 100644 --- a/routers/api/v1/admin/cron.go +++ b/routers/api/v1/admin/cron.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/api/v1/admin/org.go b/routers/api/v1/admin/org.go index 727f3193cf..9d0725e3e8 100644 --- a/routers/api/v1/admin/org.go +++ b/routers/api/v1/admin/org.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/api/v1/admin/repo.go b/routers/api/v1/admin/repo.go index 712ced89c9..83ed06e49b 100644 --- a/routers/api/v1/admin/repo.go +++ b/routers/api/v1/admin/repo.go @@ -1,6 +1,5 @@ // Copyright 2015 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/api/v1/admin/user.go b/routers/api/v1/admin/user.go index 1a4b020011..183ade8a0a 100644 --- a/routers/api/v1/admin/user.go +++ b/routers/api/v1/admin/user.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index 6f8ac7c146..74b4156d17 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2016 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. +// SPDX-License-Identifier: MIT // Package v1 Gitea API. // @@ -68,7 +67,6 @@ import ( gocontext "context" "fmt" "net/http" - "reflect" "strings" "code.gitea.io/gitea/models/organization" @@ -568,14 +566,17 @@ func mustNotBeArchived(ctx *context.APIContext) { } } -// bind binding an obj to a func(ctx *context.APIContext) -func bind(obj interface{}) http.HandlerFunc { - tp := reflect.TypeOf(obj) - for tp.Kind() == reflect.Ptr { - tp = tp.Elem() +func mustEnableAttachments(ctx *context.APIContext) { + if !setting.Attachment.Enabled { + ctx.NotFound() + return } +} + +// bind binding an obj to a func(ctx *context.APIContext) +func bind[T any](obj T) http.HandlerFunc { return web.Wrap(func(ctx *context.APIContext) { - theObj := reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly + theObj := new(T) // create a new form obj for every request but not use obj directly errs := binding.Bind(ctx.Req, theObj) if len(errs) > 0 { ctx.Error(http.StatusUnprocessableEntity, "validationError", fmt.Sprintf("%s: %s", errs[0].FieldNames, errs[0].Error())) @@ -617,7 +618,7 @@ func Routes(ctx gocontext.Context) *web.Route { // setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option AllowedMethods: setting.CORSConfig.Methods, AllowCredentials: setting.CORSConfig.AllowCredentials, - AllowedHeaders: []string{"Authorization", "X-Gitea-OTP"}, + AllowedHeaders: append([]string{"Authorization", "X-Gitea-OTP"}, setting.CORSConfig.Headers...), MaxAge: int(setting.CORSConfig.MaxAge.Seconds()), })) } @@ -906,12 +907,21 @@ func Routes(ctx gocontext.Context) *web.Route { Get(repo.GetIssueCommentReactions). Post(reqToken(), bind(api.EditReactionOption{}), repo.PostIssueCommentReaction). Delete(reqToken(), bind(api.EditReactionOption{}), repo.DeleteIssueCommentReaction) + m.Group("/assets", func() { + m.Combo(""). + Get(repo.ListIssueCommentAttachments). + Post(reqToken(), mustNotBeArchived, repo.CreateIssueCommentAttachment) + m.Combo("/{asset}"). + Get(repo.GetIssueCommentAttachment). + Patch(reqToken(), mustNotBeArchived, bind(api.EditAttachmentOptions{}), repo.EditIssueCommentAttachment). + Delete(reqToken(), mustNotBeArchived, repo.DeleteIssueCommentAttachment) + }, mustEnableAttachments) }) }) m.Group("/{index}", func() { m.Combo("").Get(repo.GetIssue). Patch(reqToken(), bind(api.EditIssueOption{}), repo.EditIssue). - Delete(reqToken(), reqAdmin(), repo.DeleteIssue) + Delete(reqToken(), reqAdmin(), context.ReferencesGitRepo(), repo.DeleteIssue) m.Group("/comments", func() { m.Combo("").Get(repo.ListIssueComments). Post(reqToken(), mustNotBeArchived, bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment) @@ -949,6 +959,15 @@ func Routes(ctx gocontext.Context) *web.Route { Get(repo.GetIssueReactions). Post(reqToken(), bind(api.EditReactionOption{}), repo.PostIssueReaction). Delete(reqToken(), bind(api.EditReactionOption{}), repo.DeleteIssueReaction) + m.Group("/assets", func() { + m.Combo(""). + Get(repo.ListIssueAttachments). + Post(reqToken(), mustNotBeArchived, repo.CreateIssueAttachment) + m.Combo("/{asset}"). + Get(repo.GetIssueAttachment). + Patch(reqToken(), mustNotBeArchived, bind(api.EditAttachmentOptions{}), repo.EditIssueAttachment). + Delete(reqToken(), mustNotBeArchived, repo.DeleteIssueAttachment) + }, mustEnableAttachments) }) }, mustEnableIssuesOrPulls) m.Group("/labels", func() { @@ -1086,6 +1105,7 @@ func Routes(ctx gocontext.Context) *web.Route { }, repoAssignment()) }) + // NOTE: these are Gitea package management API - see packages.CommonRoutes and packages.DockerContainerRoutes for endpoints that implement package manager APIs m.Group("/packages/{username}", func() { m.Group("/{type}/{name}/{version}", func() { m.Get("", packages.GetPackage) diff --git a/routers/api/v1/auth.go b/routers/api/v1/auth.go index becf45f643..e44271ba14 100644 --- a/routers/api/v1/auth.go +++ b/routers/api/v1/auth.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT //go:build !windows diff --git a/routers/api/v1/auth_windows.go b/routers/api/v1/auth_windows.go index d41c4bb223..3514e21baa 100644 --- a/routers/api/v1/auth_windows.go +++ b/routers/api/v1/auth_windows.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package v1 diff --git a/routers/api/v1/misc/markdown.go b/routers/api/v1/misc/markdown.go index eb0b78a5ba..3ff42f08d6 100644 --- a/routers/api/v1/misc/markdown.go +++ b/routers/api/v1/misc/markdown.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package misc diff --git a/routers/api/v1/misc/markdown_test.go b/routers/api/v1/misc/markdown_test.go index 65ce060278..025f2f44b0 100644 --- a/routers/api/v1/misc/markdown_test.go +++ b/routers/api/v1/misc/markdown_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package misc diff --git a/routers/api/v1/misc/nodeinfo.go b/routers/api/v1/misc/nodeinfo.go index bd629b87ca..319c3483e1 100644 --- a/routers/api/v1/misc/nodeinfo.go +++ b/routers/api/v1/misc/nodeinfo.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package misc @@ -42,7 +41,7 @@ func NodeInfo(ctx *context.APIContext) { usersActiveMonth := int(user_model.CountUsers(&user_model.CountUserFilter{LastLoginSince: &timeOneMonthAgo})) usersActiveHalfyear := int(user_model.CountUsers(&user_model.CountUserFilter{LastLoginSince: &timeHaveYearAgo})) - allIssues, _ := issues_model.CountIssues(&issues_model.IssuesOptions{}) + allIssues, _ := issues_model.CountIssues(ctx, &issues_model.IssuesOptions{}) allComments, _ := issues_model.CountComments(&issues_model.FindCommentsOptions{}) nodeInfoUsage = structs.NodeInfoUsage{ diff --git a/routers/api/v1/misc/signing.go b/routers/api/v1/misc/signing.go index 1070cc78cb..2ca9813e15 100644 --- a/routers/api/v1/misc/signing.go +++ b/routers/api/v1/misc/signing.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package misc diff --git a/routers/api/v1/misc/version.go b/routers/api/v1/misc/version.go index b8c7d4f9ad..83fa35219a 100644 --- a/routers/api/v1/misc/version.go +++ b/routers/api/v1/misc/version.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package misc diff --git a/routers/api/v1/notify/notifications.go b/routers/api/v1/notify/notifications.go index 9948f90a12..3b6a9bfdc2 100644 --- a/routers/api/v1/notify/notifications.go +++ b/routers/api/v1/notify/notifications.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package notify diff --git a/routers/api/v1/notify/repo.go b/routers/api/v1/notify/repo.go index f8e1fb0865..a2e72cb48d 100644 --- a/routers/api/v1/notify/repo.go +++ b/routers/api/v1/notify/repo.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package notify @@ -109,7 +108,7 @@ func ListRepoNotifications(ctx *context.APIContext) { } opts.RepoID = ctx.Repo.Repository.ID - totalCount, err := activities_model.CountNotifications(opts) + totalCount, err := activities_model.CountNotifications(ctx, opts) if err != nil { ctx.InternalServerError(err) return @@ -120,7 +119,7 @@ func ListRepoNotifications(ctx *context.APIContext) { ctx.InternalServerError(err) return } - err = nl.LoadAttributes() + err = nl.LoadAttributes(ctx) if err != nil { ctx.InternalServerError(err) return @@ -217,12 +216,12 @@ func ReadRepoNotifications(ctx *context.APIContext) { changed := make([]*structs.NotificationThread, 0, len(nl)) for _, n := range nl { - notif, err := activities_model.SetNotificationStatus(n.ID, ctx.Doer, targetStatus) + notif, err := activities_model.SetNotificationStatus(ctx, n.ID, ctx.Doer, targetStatus) if err != nil { ctx.InternalServerError(err) return } - _ = notif.LoadAttributes() + _ = notif.LoadAttributes(ctx) changed = append(changed, convert.ToNotificationThread(notif)) } ctx.JSON(http.StatusResetContent, changed) diff --git a/routers/api/v1/notify/threads.go b/routers/api/v1/notify/threads.go index 44a1d30a55..47d0e49721 100644 --- a/routers/api/v1/notify/threads.go +++ b/routers/api/v1/notify/threads.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package notify @@ -42,7 +41,7 @@ func GetThread(ctx *context.APIContext) { if n == nil { return } - if err := n.LoadAttributes(); err != nil && !issues_model.IsErrCommentNotExist(err) { + if err := n.LoadAttributes(ctx); err != nil && !issues_model.IsErrCommentNotExist(err) { ctx.InternalServerError(err) return } @@ -89,12 +88,12 @@ func ReadThread(ctx *context.APIContext) { targetStatus = activities_model.NotificationStatusRead } - notif, err := activities_model.SetNotificationStatus(n.ID, ctx.Doer, targetStatus) + notif, err := activities_model.SetNotificationStatus(ctx, n.ID, ctx.Doer, targetStatus) if err != nil { ctx.InternalServerError(err) return } - if err = notif.LoadAttributes(); err != nil && !issues_model.IsErrCommentNotExist(err) { + if err = notif.LoadAttributes(ctx); err != nil && !issues_model.IsErrCommentNotExist(err) { ctx.InternalServerError(err) return } @@ -102,7 +101,7 @@ func ReadThread(ctx *context.APIContext) { } func getThread(ctx *context.APIContext) *activities_model.Notification { - n, err := activities_model.GetNotificationByID(ctx.ParamsInt64(":id")) + n, err := activities_model.GetNotificationByID(ctx, ctx.ParamsInt64(":id")) if err != nil { if db.IsErrNotExist(err) { ctx.Error(http.StatusNotFound, "GetNotificationByID", err) diff --git a/routers/api/v1/notify/user.go b/routers/api/v1/notify/user.go index 1b6706e16f..725eeff017 100644 --- a/routers/api/v1/notify/user.go +++ b/routers/api/v1/notify/user.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package notify @@ -69,7 +68,7 @@ func ListNotifications(ctx *context.APIContext) { return } - totalCount, err := activities_model.CountNotifications(opts) + totalCount, err := activities_model.CountNotifications(ctx, opts) if err != nil { ctx.InternalServerError(err) return @@ -80,7 +79,7 @@ func ListNotifications(ctx *context.APIContext) { ctx.InternalServerError(err) return } - err = nl.LoadAttributes() + err = nl.LoadAttributes(ctx) if err != nil { ctx.InternalServerError(err) return @@ -162,12 +161,12 @@ func ReadNotifications(ctx *context.APIContext) { changed := make([]*structs.NotificationThread, 0, len(nl)) for _, n := range nl { - notif, err := activities_model.SetNotificationStatus(n.ID, ctx.Doer, targetStatus) + notif, err := activities_model.SetNotificationStatus(ctx, n.ID, ctx.Doer, targetStatus) if err != nil { ctx.InternalServerError(err) return } - _ = notif.LoadAttributes() + _ = notif.LoadAttributes(ctx) changed = append(changed, convert.ToNotificationThread(notif)) } diff --git a/routers/api/v1/org/hook.go b/routers/api/v1/org/hook.go index f8ea5a876c..2e9d7c656a 100644 --- a/routers/api/v1/org/hook.go +++ b/routers/api/v1/org/hook.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package org diff --git a/routers/api/v1/org/label.go b/routers/api/v1/org/label.go index a67bd56dfc..c95a6be3d2 100644 --- a/routers/api/v1/org/label.go +++ b/routers/api/v1/org/label.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package org diff --git a/routers/api/v1/org/member.go b/routers/api/v1/org/member.go index 85fe2ded4d..fe07143958 100644 --- a/routers/api/v1/org/member.go +++ b/routers/api/v1/org/member.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package org diff --git a/routers/api/v1/org/org.go b/routers/api/v1/org/org.go index 5a8b253a20..cf985d44fb 100644 --- a/routers/api/v1/org/org.go +++ b/routers/api/v1/org/org.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package org diff --git a/routers/api/v1/org/team.go b/routers/api/v1/org/team.go index f3e7834a49..798b792e71 100644 --- a/routers/api/v1/org/team.go +++ b/routers/api/v1/org/team.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package org @@ -542,12 +541,12 @@ func GetTeamRepos(ctx *context.APIContext) { } repos := make([]*api.Repository, len(teamRepos)) for i, repo := range teamRepos { - access, err := access_model.AccessLevel(ctx.Doer, repo) + access, err := access_model.AccessLevel(ctx, ctx.Doer, repo) if err != nil { ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err) return } - repos[i] = convert.ToRepo(repo, access) + repos[i] = convert.ToRepo(ctx, repo, access) } ctx.SetTotalCountHeader(int64(team.NumRepos)) ctx.JSON(http.StatusOK, repos) @@ -593,13 +592,13 @@ func GetTeamRepo(ctx *context.APIContext) { return } - access, err := access_model.AccessLevel(ctx.Doer, repo) + access, err := access_model.AccessLevel(ctx, ctx.Doer, repo) if err != nil { ctx.Error(http.StatusInternalServerError, "GetTeamRepos", err) return } - ctx.JSON(http.StatusOK, convert.ToRepo(repo, access)) + ctx.JSON(http.StatusOK, convert.ToRepo(ctx, repo, access)) } // getRepositoryByParams get repository by a team's organization ID and repo name @@ -650,7 +649,7 @@ func AddTeamRepository(ctx *context.APIContext) { if ctx.Written() { return } - if access, err := access_model.AccessLevel(ctx.Doer, repo); err != nil { + if access, err := access_model.AccessLevel(ctx, ctx.Doer, repo); err != nil { ctx.Error(http.StatusInternalServerError, "AccessLevel", err) return } else if access < perm.AccessModeAdmin { @@ -700,7 +699,7 @@ func RemoveTeamRepository(ctx *context.APIContext) { if ctx.Written() { return } - if access, err := access_model.AccessLevel(ctx.Doer, repo); err != nil { + if access, err := access_model.AccessLevel(ctx, ctx.Doer, repo); err != nil { ctx.Error(http.StatusInternalServerError, "AccessLevel", err) return } else if access < perm.AccessModeAdmin { diff --git a/routers/api/v1/packages/package.go b/routers/api/v1/packages/package.go index 29fa6c85a5..433a79939c 100644 --- a/routers/api/v1/packages/package.go +++ b/routers/api/v1/packages/package.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package packages diff --git a/routers/api/v1/repo/blob.go b/routers/api/v1/repo/blob.go index 035f2dc1e1..d0004f0686 100644 --- a/routers/api/v1/repo/blob.go +++ b/routers/api/v1/repo/blob.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/branch.go b/routers/api/v1/repo/branch.go index 84a172e92b..3060cf2406 100644 --- a/routers/api/v1/repo/branch.go +++ b/routers/api/v1/repo/branch.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo @@ -252,42 +251,50 @@ func ListBranches(ctx *context.APIContext) { // "200": // "$ref": "#/responses/BranchList" - listOptions := utils.GetListOptions(ctx) - skip, _ := listOptions.GetStartEnd() - branches, totalNumOfBranches, err := ctx.Repo.GitRepo.GetBranches(skip, listOptions.PageSize) - if err != nil { - ctx.Error(http.StatusInternalServerError, "GetBranches", err) - return - } + var totalNumOfBranches int + var apiBranches []*api.Branch - apiBranches := make([]*api.Branch, 0, len(branches)) - for i := range branches { - c, err := branches[i].GetCommit() + listOptions := utils.GetListOptions(ctx) + + if !ctx.Repo.Repository.IsEmpty && ctx.Repo.GitRepo != nil { + skip, _ := listOptions.GetStartEnd() + branches, total, err := ctx.Repo.GitRepo.GetBranches(skip, listOptions.PageSize) if err != nil { - // Skip if this branch doesn't exist anymore. - if git.IsErrNotExist(err) { - totalNumOfBranches-- - continue + ctx.Error(http.StatusInternalServerError, "GetBranches", err) + return + } + + apiBranches = make([]*api.Branch, 0, len(branches)) + for i := range branches { + c, err := branches[i].GetCommit() + if err != nil { + // Skip if this branch doesn't exist anymore. + if git.IsErrNotExist(err) { + total-- + continue + } + ctx.Error(http.StatusInternalServerError, "GetCommit", err) + return } - ctx.Error(http.StatusInternalServerError, "GetCommit", err) - return + branchProtection, err := git_model.GetProtectedBranchBy(ctx, ctx.Repo.Repository.ID, branches[i].Name) + if err != nil { + ctx.Error(http.StatusInternalServerError, "GetProtectedBranchBy", err) + return + } + apiBranch, err := convert.ToBranch(ctx.Repo.Repository, branches[i], c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin()) + if err != nil { + ctx.Error(http.StatusInternalServerError, "convert.ToBranch", err) + return + } + apiBranches = append(apiBranches, apiBranch) } - branchProtection, err := git_model.GetProtectedBranchBy(ctx, ctx.Repo.Repository.ID, branches[i].Name) - if err != nil { - ctx.Error(http.StatusInternalServerError, "GetBranchProtection", err) - return - } - apiBranch, err := convert.ToBranch(ctx.Repo.Repository, branches[i], c, branchProtection, ctx.Doer, ctx.Repo.IsAdmin()) - if err != nil { - ctx.Error(http.StatusInternalServerError, "convert.ToBranch", err) - return - } - apiBranches = append(apiBranches, apiBranch) + + totalNumOfBranches = total } ctx.SetLinkHeader(totalNumOfBranches, listOptions.PageSize) ctx.SetTotalCountHeader(int64(totalNumOfBranches)) - ctx.JSON(http.StatusOK, &apiBranches) + ctx.JSON(http.StatusOK, apiBranches) } // GetBranchProtection gets a branch protection @@ -427,7 +434,7 @@ func CreateBranchProtection(ctx *context.APIContext) { requiredApprovals = form.RequiredApprovals } - whitelistUsers, err := user_model.GetUserIDsByNames(form.PushWhitelistUsernames, false) + whitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.PushWhitelistUsernames, false) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err) @@ -436,7 +443,7 @@ func CreateBranchProtection(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "GetUserIDsByNames", err) return } - mergeWhitelistUsers, err := user_model.GetUserIDsByNames(form.MergeWhitelistUsernames, false) + mergeWhitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.MergeWhitelistUsernames, false) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err) @@ -445,7 +452,7 @@ func CreateBranchProtection(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "GetUserIDsByNames", err) return } - approvalsWhitelistUsers, err := user_model.GetUserIDsByNames(form.ApprovalsWhitelistUsernames, false) + approvalsWhitelistUsers, err := user_model.GetUserIDsByNames(ctx, form.ApprovalsWhitelistUsernames, false) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err) @@ -656,7 +663,7 @@ func EditBranchProtection(ctx *context.APIContext) { var whitelistUsers []int64 if form.PushWhitelistUsernames != nil { - whitelistUsers, err = user_model.GetUserIDsByNames(form.PushWhitelistUsernames, false) + whitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.PushWhitelistUsernames, false) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err) @@ -670,7 +677,7 @@ func EditBranchProtection(ctx *context.APIContext) { } var mergeWhitelistUsers []int64 if form.MergeWhitelistUsernames != nil { - mergeWhitelistUsers, err = user_model.GetUserIDsByNames(form.MergeWhitelistUsernames, false) + mergeWhitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.MergeWhitelistUsernames, false) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err) @@ -684,7 +691,7 @@ func EditBranchProtection(ctx *context.APIContext) { } var approvalsWhitelistUsers []int64 if form.ApprovalsWhitelistUsernames != nil { - approvalsWhitelistUsers, err = user_model.GetUserIDsByNames(form.ApprovalsWhitelistUsernames, false) + approvalsWhitelistUsers, err = user_model.GetUserIDsByNames(ctx, form.ApprovalsWhitelistUsernames, false) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.Error(http.StatusUnprocessableEntity, "User does not exist", err) diff --git a/routers/api/v1/repo/collaborators.go b/routers/api/v1/repo/collaborators.go index 0e6236216c..202418bd2b 100644 --- a/routers/api/v1/repo/collaborators.go +++ b/routers/api/v1/repo/collaborators.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo @@ -175,13 +174,13 @@ func AddCollaborator(ctx *context.APIContext) { return } - if err := repo_module.AddCollaborator(ctx.Repo.Repository, collaborator); err != nil { + if err := repo_module.AddCollaborator(ctx, ctx.Repo.Repository, collaborator); err != nil { ctx.Error(http.StatusInternalServerError, "AddCollaborator", err) return } if form.Permission != nil { - if err := repo_model.ChangeCollaborationAccessMode(ctx.Repo.Repository, collaborator.ID, perm.ParseAccessMode(*form.Permission)); err != nil { + if err := repo_model.ChangeCollaborationAccessMode(ctx, ctx.Repo.Repository, collaborator.ID, perm.ParseAccessMode(*form.Permission)); err != nil { ctx.Error(http.StatusInternalServerError, "ChangeCollaborationAccessMode", err) return } diff --git a/routers/api/v1/repo/commits.go b/routers/api/v1/repo/commits.go index 4e77c3f2f5..682044407d 100644 --- a/routers/api/v1/repo/commits.go +++ b/routers/api/v1/repo/commits.go @@ -1,7 +1,6 @@ // Copyright 2018 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/file.go b/routers/api/v1/repo/file.go index 6dead81e6d..623fe18e5d 100644 --- a/routers/api/v1/repo/file.go +++ b/routers/api/v1/repo/file.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo @@ -341,7 +340,11 @@ func download(ctx *context.APIContext, archiveName string, archiver *repo_model. return } defer fr.Close() - ctx.ServeContent(downloadName, fr, archiver.CreatedUnix.AsLocalTime()) + + ctx.ServeContent(fr, &context.ServeHeaderOptions{ + Filename: downloadName, + LastModified: archiver.CreatedUnix.AsLocalTime(), + }) } // GetEditorconfig get editor config of a repository diff --git a/routers/api/v1/repo/fork.go b/routers/api/v1/repo/fork.go index 112a9562f0..f2cd10e711 100644 --- a/routers/api/v1/repo/fork.go +++ b/routers/api/v1/repo/fork.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package repo @@ -59,12 +58,12 @@ func ListForks(ctx *context.APIContext) { } apiForks := make([]*api.Repository, len(forks)) for i, fork := range forks { - access, err := access_model.AccessLevel(ctx.Doer, fork) + access, err := access_model.AccessLevel(ctx, ctx.Doer, fork) if err != nil { ctx.Error(http.StatusInternalServerError, "AccessLevel", err) return } - apiForks[i] = convert.ToRepo(fork, access) + apiForks[i] = convert.ToRepo(ctx, fork, access) } ctx.SetTotalCountHeader(int64(ctx.Repo.Repository.NumForks)) @@ -151,5 +150,5 @@ func CreateFork(ctx *context.APIContext) { } // TODO change back to 201 - ctx.JSON(http.StatusAccepted, convert.ToRepo(fork, perm.AccessModeOwner)) + ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx, fork, perm.AccessModeOwner)) } diff --git a/routers/api/v1/repo/git_hook.go b/routers/api/v1/repo/git_hook.go index 0b4e09cadd..963cbc719f 100644 --- a/routers/api/v1/repo/git_hook.go +++ b/routers/api/v1/repo/git_hook.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/git_ref.go b/routers/api/v1/repo/git_ref.go index 47f46df339..34d2dcfcc8 100644 --- a/routers/api/v1/repo/git_ref.go +++ b/routers/api/v1/repo/git_ref.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/hook.go b/routers/api/v1/repo/hook.go index 57fff7d326..0c3d59a419 100644 --- a/routers/api/v1/repo/hook.go +++ b/routers/api/v1/repo/hook.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package repo @@ -185,7 +184,7 @@ func TestHook(ctx *context.APIContext) { Commits: []*api.PayloadCommit{commit}, TotalCommits: 1, HeadCommit: commit, - Repo: convert.ToRepo(ctx.Repo.Repository, perm.AccessModeNone), + Repo: convert.ToRepo(ctx, ctx.Repo.Repository, perm.AccessModeNone), Pusher: convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone), Sender: convert.ToUserWithAccessMode(ctx.Doer, perm.AccessModeNone), }); err != nil { diff --git a/routers/api/v1/repo/hook_test.go b/routers/api/v1/repo/hook_test.go index fd9a165bf3..34dc990c3d 100644 --- a/routers/api/v1/repo/hook_test.go +++ b/routers/api/v1/repo/hook_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/issue.go b/routers/api/v1/repo/issue.go index 08e3e03741..30dc7a6832 100644 --- a/routers/api/v1/repo/issue.go +++ b/routers/api/v1/repo/issue.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo @@ -179,7 +178,7 @@ func SearchIssues(ctx *context.APIContext) { repoCond := repo_model.SearchRepositoryCondition(opts) repoIDs, _, err := repo_model.SearchRepositoryIDs(opts) if err != nil { - ctx.Error(http.StatusInternalServerError, "SearchRepositoryByName", err) + ctx.Error(http.StatusInternalServerError, "SearchRepositoryIDs", err) return } @@ -268,7 +267,7 @@ func SearchIssues(ctx *context.APIContext) { issuesOpt.ReviewRequestedID = ctxUserID } - if issues, err = issues_model.Issues(issuesOpt); err != nil { + if issues, err = issues_model.Issues(ctx, issuesOpt); err != nil { ctx.Error(http.StatusInternalServerError, "Issues", err) return } @@ -276,7 +275,7 @@ func SearchIssues(ctx *context.APIContext) { issuesOpt.ListOptions = db.ListOptions{ Page: -1, } - if filteredCount, err = issues_model.CountIssues(issuesOpt); err != nil { + if filteredCount, err = issues_model.CountIssues(ctx, issuesOpt); err != nil { ctx.Error(http.StatusInternalServerError, "CountIssues", err) return } @@ -284,7 +283,7 @@ func SearchIssues(ctx *context.APIContext) { ctx.SetLinkHeader(int(filteredCount), limit) ctx.SetTotalCountHeader(filteredCount) - ctx.JSON(http.StatusOK, convert.ToAPIIssueList(issues)) + ctx.JSON(http.StatusOK, convert.ToAPIIssueList(ctx, issues)) } // ListIssues list the issues of a repository @@ -477,7 +476,7 @@ func ListIssues(ctx *context.APIContext) { MentionedID: mentionedByID, } - if issues, err = issues_model.Issues(issuesOpt); err != nil { + if issues, err = issues_model.Issues(ctx, issuesOpt); err != nil { ctx.Error(http.StatusInternalServerError, "Issues", err) return } @@ -485,7 +484,7 @@ func ListIssues(ctx *context.APIContext) { issuesOpt.ListOptions = db.ListOptions{ Page: -1, } - if filteredCount, err = issues_model.CountIssues(issuesOpt); err != nil { + if filteredCount, err = issues_model.CountIssues(ctx, issuesOpt); err != nil { ctx.Error(http.StatusInternalServerError, "CountIssues", err) return } @@ -493,7 +492,7 @@ func ListIssues(ctx *context.APIContext) { ctx.SetLinkHeader(int(filteredCount), listOptions.PageSize) ctx.SetTotalCountHeader(filteredCount) - ctx.JSON(http.StatusOK, convert.ToAPIIssueList(issues)) + ctx.JSON(http.StatusOK, convert.ToAPIIssueList(ctx, issues)) } func getUserIDForFilter(ctx *context.APIContext, queryName string) int64 { @@ -555,7 +554,7 @@ func GetIssue(ctx *context.APIContext) { } return } - ctx.JSON(http.StatusOK, convert.ToAPIIssue(issue)) + ctx.JSON(http.StatusOK, convert.ToAPIIssue(ctx, issue)) } // CreateIssue create an issue of a repository @@ -612,7 +611,7 @@ func CreateIssue(ctx *context.APIContext) { var err error if ctx.Repo.CanWrite(unit.TypeIssues) { issue.MilestoneID = form.Milestone - assigneeIDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(form.Assignee, form.Assignees) + assigneeIDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(ctx, form.Assignee, form.Assignees) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err)) @@ -624,7 +623,7 @@ func CreateIssue(ctx *context.APIContext) { // Check if the passed assignees is assignable for _, aID := range assigneeIDs { - assignee, err := user_model.GetUserByID(aID) + assignee, err := user_model.GetUserByID(ctx, aID) if err != nil { ctx.Error(http.StatusInternalServerError, "GetUserByID", err) return @@ -671,7 +670,7 @@ func CreateIssue(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "GetIssueByID", err) return } - ctx.JSON(http.StatusCreated, convert.ToAPIIssue(issue)) + ctx.JSON(http.StatusCreated, convert.ToAPIIssue(ctx, issue)) } // EditIssue modify an issue of a repository @@ -823,11 +822,11 @@ func EditIssue(ctx *context.APIContext) { } if titleChanged { - notification.NotifyIssueChangeTitle(ctx.Doer, issue, oldTitle) + notification.NotifyIssueChangeTitle(ctx, ctx.Doer, issue, oldTitle) } if statusChangeComment != nil { - notification.NotifyIssueChangeStatus(ctx.Doer, issue, statusChangeComment, issue.IsClosed) + notification.NotifyIssueChangeStatus(ctx, ctx.Doer, issue, statusChangeComment, issue.IsClosed) } // Refetch from database to assign some automatic values @@ -836,11 +835,11 @@ func EditIssue(ctx *context.APIContext) { ctx.InternalServerError(err) return } - if err = issue.LoadMilestone(); err != nil { + if err = issue.LoadMilestone(ctx); err != nil { ctx.InternalServerError(err) return } - ctx.JSON(http.StatusCreated, convert.ToAPIIssue(issue)) + ctx.JSON(http.StatusCreated, convert.ToAPIIssue(ctx, issue)) } func DeleteIssue(ctx *context.APIContext) { diff --git a/routers/api/v1/repo/issue_attachment.go b/routers/api/v1/repo/issue_attachment.go new file mode 100644 index 0000000000..4cf108b413 --- /dev/null +++ b/routers/api/v1/repo/issue_attachment.go @@ -0,0 +1,372 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package repo + +import ( + "net/http" + + issues_model "code.gitea.io/gitea/models/issues" + repo_model "code.gitea.io/gitea/models/repo" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/convert" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/setting" + api "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/services/attachment" + issue_service "code.gitea.io/gitea/services/issue" +) + +// GetIssueAttachment gets a single attachment of the issue +func GetIssueAttachment(ctx *context.APIContext) { + // swagger:operation GET /repos/{owner}/{repo}/issues/{index}/assets/{attachment_id} issue issueGetIssueAttachment + // --- + // summary: Get an issue attachment + // produces: + // - application/json + // parameters: + // - name: owner + // in: path + // description: owner of the repo + // type: string + // required: true + // - name: repo + // in: path + // description: name of the repo + // type: string + // required: true + // - name: index + // in: path + // description: index of the issue + // type: integer + // format: int64 + // required: true + // - name: attachment_id + // in: path + // description: id of the attachment to get + // type: integer + // format: int64 + // required: true + // responses: + // "200": + // "$ref": "#/responses/Attachment" + // "404": + // "$ref": "#/responses/error" + + issue := getIssueFromContext(ctx) + if issue == nil { + return + } + + attach := getIssueAttachmentSafeRead(ctx, issue) + if attach == nil { + return + } + + ctx.JSON(http.StatusOK, convert.ToAttachment(attach)) +} + +// ListIssueAttachments lists all attachments of the issue +func ListIssueAttachments(ctx *context.APIContext) { + // swagger:operation GET /repos/{owner}/{repo}/issues/{index}/assets issue issueListIssueAttachments + // --- + // summary: List issue's attachments + // produces: + // - application/json + // parameters: + // - name: owner + // in: path + // description: owner of the repo + // type: string + // required: true + // - name: repo + // in: path + // description: name of the repo + // type: string + // required: true + // - name: index + // in: path + // description: index of the issue + // type: integer + // format: int64 + // required: true + // responses: + // "200": + // "$ref": "#/responses/AttachmentList" + // "404": + // "$ref": "#/responses/error" + + issue := getIssueFromContext(ctx) + if issue == nil { + return + } + + if err := issue.LoadAttributes(ctx); err != nil { + ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) + return + } + + ctx.JSON(http.StatusOK, convert.ToAPIIssue(ctx, issue).Attachments) +} + +// CreateIssueAttachment creates an attachment and saves the given file +func CreateIssueAttachment(ctx *context.APIContext) { + // swagger:operation POST /repos/{owner}/{repo}/issues/{index}/assets issue issueCreateIssueAttachment + // --- + // summary: Create an issue attachment + // produces: + // - application/json + // consumes: + // - multipart/form-data + // parameters: + // - name: owner + // in: path + // description: owner of the repo + // type: string + // required: true + // - name: repo + // in: path + // description: name of the repo + // type: string + // required: true + // - name: index + // in: path + // description: index of the issue + // type: integer + // format: int64 + // required: true + // - name: name + // in: query + // description: name of the attachment + // type: string + // required: false + // - name: attachment + // in: formData + // description: attachment to upload + // type: file + // required: true + // responses: + // "201": + // "$ref": "#/responses/Attachment" + // "400": + // "$ref": "#/responses/error" + // "404": + // "$ref": "#/responses/error" + + issue := getIssueFromContext(ctx) + if issue == nil { + return + } + + if !canUserWriteIssueAttachment(ctx, issue) { + return + } + + // Get uploaded file from request + file, header, err := ctx.Req.FormFile("attachment") + if err != nil { + ctx.Error(http.StatusInternalServerError, "FormFile", err) + return + } + defer file.Close() + + filename := header.Filename + if query := ctx.FormString("name"); query != "" { + filename = query + } + + attachment, err := attachment.UploadAttachment(file, setting.Attachment.AllowedTypes, &repo_model.Attachment{ + Name: filename, + UploaderID: ctx.Doer.ID, + RepoID: ctx.Repo.Repository.ID, + IssueID: issue.ID, + }) + if err != nil { + ctx.Error(http.StatusInternalServerError, "UploadAttachment", err) + return + } + + issue.Attachments = append(issue.Attachments, attachment) + + if err := issue_service.ChangeContent(issue, ctx.Doer, issue.Content); err != nil { + ctx.Error(http.StatusInternalServerError, "ChangeContent", err) + return + } + + ctx.JSON(http.StatusCreated, convert.ToAttachment(attachment)) +} + +// EditIssueAttachment updates the given attachment +func EditIssueAttachment(ctx *context.APIContext) { + // swagger:operation PATCH /repos/{owner}/{repo}/issues/{index}/assets/{attachment_id} issue issueEditIssueAttachment + // --- + // summary: Edit an issue attachment + // produces: + // - application/json + // consumes: + // - application/json + // parameters: + // - name: owner + // in: path + // description: owner of the repo + // type: string + // required: true + // - name: repo + // in: path + // description: name of the repo + // type: string + // required: true + // - name: index + // in: path + // description: index of the issue + // type: integer + // format: int64 + // required: true + // - name: attachment_id + // in: path + // description: id of the attachment to edit + // type: integer + // format: int64 + // required: true + // - name: body + // in: body + // schema: + // "$ref": "#/definitions/EditAttachmentOptions" + // responses: + // "201": + // "$ref": "#/responses/Attachment" + // "404": + // "$ref": "#/responses/error" + + attachment := getIssueAttachmentSafeWrite(ctx) + if attachment == nil { + return + } + + // do changes to attachment. only meaningful change is name. + form := web.GetForm(ctx).(*api.EditAttachmentOptions) + if form.Name != "" { + attachment.Name = form.Name + } + + if err := repo_model.UpdateAttachment(ctx, attachment); err != nil { + ctx.Error(http.StatusInternalServerError, "UpdateAttachment", err) + } + + ctx.JSON(http.StatusCreated, convert.ToAttachment(attachment)) +} + +// DeleteIssueAttachment delete a given attachment +func DeleteIssueAttachment(ctx *context.APIContext) { + // swagger:operation DELETE /repos/{owner}/{repo}/issues/{index}/assets/{attachment_id} issue issueDeleteIssueAttachment + // --- + // summary: Delete an issue attachment + // produces: + // - application/json + // parameters: + // - name: owner + // in: path + // description: owner of the repo + // type: string + // required: true + // - name: repo + // in: path + // description: name of the repo + // type: string + // required: true + // - name: index + // in: path + // description: index of the issue + // type: integer + // format: int64 + // required: true + // - name: attachment_id + // in: path + // description: id of the attachment to delete + // type: integer + // format: int64 + // required: true + // responses: + // "204": + // "$ref": "#/responses/empty" + // "404": + // "$ref": "#/responses/error" + + attachment := getIssueAttachmentSafeWrite(ctx) + if attachment == nil { + return + } + + if err := repo_model.DeleteAttachment(attachment, true); err != nil { + ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err) + return + } + + ctx.Status(http.StatusNoContent) +} + +func getIssueFromContext(ctx *context.APIContext) *issues_model.Issue { + issue, err := issues_model.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64("index")) + if err != nil { + ctx.NotFoundOrServerError("GetIssueByIndex", issues_model.IsErrIssueNotExist, err) + return nil + } + + issue.Repo = ctx.Repo.Repository + + return issue +} + +func getIssueAttachmentSafeWrite(ctx *context.APIContext) *repo_model.Attachment { + issue := getIssueFromContext(ctx) + if issue == nil { + return nil + } + + if !canUserWriteIssueAttachment(ctx, issue) { + return nil + } + + return getIssueAttachmentSafeRead(ctx, issue) +} + +func getIssueAttachmentSafeRead(ctx *context.APIContext, issue *issues_model.Issue) *repo_model.Attachment { + attachment, err := repo_model.GetAttachmentByID(ctx, ctx.ParamsInt64("asset")) + if err != nil { + ctx.NotFoundOrServerError("GetAttachmentByID", repo_model.IsErrAttachmentNotExist, err) + return nil + } + if !attachmentBelongsToRepoOrIssue(ctx, attachment, issue) { + return nil + } + return attachment +} + +func canUserWriteIssueAttachment(ctx *context.APIContext, issue *issues_model.Issue) bool { + canEditIssue := ctx.IsSigned && (ctx.Doer.ID == issue.PosterID || ctx.IsUserRepoAdmin() || ctx.IsUserSiteAdmin()) && ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) + if !canEditIssue { + ctx.Error(http.StatusForbidden, "", "user should have permission to write issue") + return false + } + + return true +} + +func attachmentBelongsToRepoOrIssue(ctx *context.APIContext, attachment *repo_model.Attachment, issue *issues_model.Issue) bool { + if attachment.RepoID != ctx.Repo.Repository.ID { + log.Debug("Requested attachment[%d] does not belong to repo[%-v].", attachment.ID, ctx.Repo.Repository) + ctx.NotFound("no such attachment in repo") + return false + } + if attachment.IssueID == 0 { + log.Debug("Requested attachment[%d] is not in an issue.", attachment.ID) + ctx.NotFound("no such attachment in issue") + return false + } else if issue != nil && attachment.IssueID != issue.ID { + log.Debug("Requested attachment[%d] does not belong to issue[%d, #%d].", attachment.ID, issue.ID, issue.Index) + ctx.NotFound("no such attachment in issue") + return false + } + return true +} diff --git a/routers/api/v1/repo/issue_comment.go b/routers/api/v1/repo/issue_comment.go index 89038e4f16..9097004186 100644 --- a/routers/api/v1/repo/issue_comment.go +++ b/routers/api/v1/repo/issue_comment.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package repo @@ -19,7 +18,7 @@ import ( api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/routers/api/v1/utils" - comment_service "code.gitea.io/gitea/services/comments" + issue_service "code.gitea.io/gitea/services/issue" ) // ListIssueComments list all the comments of an issue @@ -91,11 +90,16 @@ func ListIssueComments(ctx *context.APIContext) { return } - if err := issues_model.CommentList(comments).LoadPosters(); err != nil { + if err := issues_model.CommentList(comments).LoadPosters(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadPosters", err) return } + if err := issues_model.CommentList(comments).LoadAttachments(ctx); err != nil { + ctx.Error(http.StatusInternalServerError, "LoadAttachments", err) + return + } + apiComments := make([]*api.Comment, len(comments)) for i, comment := range comments { comment.Issue = issue @@ -178,7 +182,7 @@ func ListIssueCommentsAndTimeline(ctx *context.APIContext) { return } - if err := issues_model.CommentList(comments).LoadPosters(); err != nil { + if err := issues_model.CommentList(comments).LoadPosters(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadPosters", err) return } @@ -187,7 +191,7 @@ func ListIssueCommentsAndTimeline(ctx *context.APIContext) { for _, comment := range comments { if comment.Type != issues_model.CommentTypeCode && isXRefCommentAccessible(ctx, ctx.Doer, comment, issue.RepoID) { comment.Issue = issue - apiComments = append(apiComments, convert.ToTimelineComment(comment, ctx.Doer)) + apiComments = append(apiComments, convert.ToTimelineComment(ctx, comment, ctx.Doer)) } } @@ -200,7 +204,7 @@ func isXRefCommentAccessible(ctx stdCtx.Context, user *user_model.User, c *issue if issues_model.CommentTypeIsRef(c.Type) && c.RefRepoID != issueRepoID && c.RefRepoID != 0 { var err error // Set RefRepo for description in template - c.RefRepo, err = repo_model.GetRepositoryByIDCtx(ctx, c.RefRepoID) + c.RefRepo, err = repo_model.GetRepositoryByID(ctx, c.RefRepoID) if err != nil { return false } @@ -281,21 +285,25 @@ func ListRepoIssueComments(ctx *context.APIContext) { return } - if err = issues_model.CommentList(comments).LoadPosters(); err != nil { + if err = issues_model.CommentList(comments).LoadPosters(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadPosters", err) return } apiComments := make([]*api.Comment, len(comments)) - if err := issues_model.CommentList(comments).LoadIssues(); err != nil { + if err := issues_model.CommentList(comments).LoadIssues(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadIssues", err) return } - if err := issues_model.CommentList(comments).LoadPosters(); err != nil { + if err := issues_model.CommentList(comments).LoadPosters(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadPosters", err) return } - if _, err := issues_model.CommentList(comments).Issues().LoadRepositories(); err != nil { + if err := issues_model.CommentList(comments).LoadAttachments(ctx); err != nil { + ctx.Error(http.StatusInternalServerError, "LoadAttachments", err) + return + } + if _, err := issues_model.CommentList(comments).Issues().LoadRepositories(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadRepositories", err) return } @@ -354,7 +362,7 @@ func CreateIssueComment(ctx *context.APIContext) { return } - comment, err := comment_service.CreateIssueComment(ctx.Doer, ctx.Repo.Repository, issue, form.Body, nil) + comment, err := issue_service.CreateIssueComment(ctx, ctx.Doer, ctx.Repo.Repository, issue, form.Body, nil) if err != nil { ctx.Error(http.StatusInternalServerError, "CreateIssueComment", err) return @@ -409,7 +417,7 @@ func GetIssueComment(ctx *context.APIContext) { return } - if err = comment.LoadIssue(); err != nil { + if err = comment.LoadIssue(ctx); err != nil { ctx.InternalServerError(err) return } @@ -423,7 +431,7 @@ func GetIssueComment(ctx *context.APIContext) { return } - if err := comment.LoadPoster(); err != nil { + if err := comment.LoadPoster(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "comment.LoadPoster", err) return } @@ -548,7 +556,7 @@ func editIssueComment(ctx *context.APIContext, form api.EditIssueCommentOption) oldContent := comment.Content comment.Content = form.Body - if err := comment_service.UpdateComment(comment, ctx.Doer, oldContent); err != nil { + if err := issue_service.UpdateComment(ctx, comment, ctx.Doer, oldContent); err != nil { ctx.Error(http.StatusInternalServerError, "UpdateComment", err) return } @@ -647,7 +655,7 @@ func deleteIssueComment(ctx *context.APIContext) { return } - if err = comment_service.DeleteComment(ctx.Doer, comment); err != nil { + if err = issue_service.DeleteComment(ctx, ctx.Doer, comment); err != nil { ctx.Error(http.StatusInternalServerError, "DeleteCommentByID", err) return } diff --git a/routers/api/v1/repo/issue_comment_attachment.go b/routers/api/v1/repo/issue_comment_attachment.go new file mode 100644 index 0000000000..2198a6a33d --- /dev/null +++ b/routers/api/v1/repo/issue_comment_attachment.go @@ -0,0 +1,383 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package repo + +import ( + "net/http" + + issues_model "code.gitea.io/gitea/models/issues" + repo_model "code.gitea.io/gitea/models/repo" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/convert" + "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/setting" + api "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/services/attachment" + issue_service "code.gitea.io/gitea/services/issue" +) + +// GetIssueCommentAttachment gets a single attachment of the comment +func GetIssueCommentAttachment(ctx *context.APIContext) { + // swagger:operation GET /repos/{owner}/{repo}/issues/comments/{id}/assets/{attachment_id} issue issueGetIssueCommentAttachment + // --- + // summary: Get a comment attachment + // produces: + // - application/json + // parameters: + // - name: owner + // in: path + // description: owner of the repo + // type: string + // required: true + // - name: repo + // in: path + // description: name of the repo + // type: string + // required: true + // - name: id + // in: path + // description: id of the comment + // type: integer + // format: int64 + // required: true + // - name: attachment_id + // in: path + // description: id of the attachment to get + // type: integer + // format: int64 + // required: true + // responses: + // "200": + // "$ref": "#/responses/Attachment" + // "404": + // "$ref": "#/responses/error" + + comment := getIssueCommentSafe(ctx) + if comment == nil { + return + } + attachment := getIssueCommentAttachmentSafeRead(ctx, comment) + if attachment == nil { + return + } + if attachment.CommentID != comment.ID { + log.Debug("User requested attachment[%d] is not in comment[%d].", attachment.ID, comment.ID) + ctx.NotFound("attachment not in comment") + return + } + + ctx.JSON(http.StatusOK, convert.ToAttachment(attachment)) +} + +// ListIssueCommentAttachments lists all attachments of the comment +func ListIssueCommentAttachments(ctx *context.APIContext) { + // swagger:operation GET /repos/{owner}/{repo}/issues/comments/{id}/assets issue issueListIssueCommentAttachments + // --- + // summary: List comment's attachments + // produces: + // - application/json + // parameters: + // - name: owner + // in: path + // description: owner of the repo + // type: string + // required: true + // - name: repo + // in: path + // description: name of the repo + // type: string + // required: true + // - name: id + // in: path + // description: id of the comment + // type: integer + // format: int64 + // required: true + // responses: + // "200": + // "$ref": "#/responses/AttachmentList" + // "404": + // "$ref": "#/responses/error" + comment := getIssueCommentSafe(ctx) + if comment == nil { + return + } + + if err := comment.LoadAttachments(ctx); err != nil { + ctx.Error(http.StatusInternalServerError, "LoadAttachments", err) + return + } + + ctx.JSON(http.StatusOK, convert.ToAttachments(comment.Attachments)) +} + +// CreateIssueCommentAttachment creates an attachment and saves the given file +func CreateIssueCommentAttachment(ctx *context.APIContext) { + // swagger:operation POST /repos/{owner}/{repo}/issues/comments/{id}/assets issue issueCreateIssueCommentAttachment + // --- + // summary: Create a comment attachment + // produces: + // - application/json + // consumes: + // - multipart/form-data + // parameters: + // - name: owner + // in: path + // description: owner of the repo + // type: string + // required: true + // - name: repo + // in: path + // description: name of the repo + // type: string + // required: true + // - name: id + // in: path + // description: id of the comment + // type: integer + // format: int64 + // required: true + // - name: name + // in: query + // description: name of the attachment + // type: string + // required: false + // - name: attachment + // in: formData + // description: attachment to upload + // type: file + // required: true + // responses: + // "201": + // "$ref": "#/responses/Attachment" + // "400": + // "$ref": "#/responses/error" + // "404": + // "$ref": "#/responses/error" + + // Check if comment exists and load comment + comment := getIssueCommentSafe(ctx) + if comment == nil { + return + } + + if !canUserWriteIssueCommentAttachment(ctx, comment) { + return + } + + // Get uploaded file from request + file, header, err := ctx.Req.FormFile("attachment") + if err != nil { + ctx.Error(http.StatusInternalServerError, "FormFile", err) + return + } + defer file.Close() + + filename := header.Filename + if query := ctx.FormString("name"); query != "" { + filename = query + } + + attachment, err := attachment.UploadAttachment(file, setting.Attachment.AllowedTypes, &repo_model.Attachment{ + Name: filename, + UploaderID: ctx.Doer.ID, + RepoID: ctx.Repo.Repository.ID, + IssueID: comment.IssueID, + CommentID: comment.ID, + }) + if err != nil { + ctx.Error(http.StatusInternalServerError, "UploadAttachment", err) + return + } + if err := comment.LoadAttachments(ctx); err != nil { + ctx.Error(http.StatusInternalServerError, "LoadAttachments", err) + return + } + + if err = issue_service.UpdateComment(ctx, comment, ctx.Doer, comment.Content); err != nil { + ctx.ServerError("UpdateComment", err) + return + } + + ctx.JSON(http.StatusCreated, convert.ToAttachment(attachment)) +} + +// EditIssueCommentAttachment updates the given attachment +func EditIssueCommentAttachment(ctx *context.APIContext) { + // swagger:operation PATCH /repos/{owner}/{repo}/issues/comments/{id}/assets/{attachment_id} issue issueEditIssueCommentAttachment + // --- + // summary: Edit a comment attachment + // produces: + // - application/json + // consumes: + // - application/json + // parameters: + // - name: owner + // in: path + // description: owner of the repo + // type: string + // required: true + // - name: repo + // in: path + // description: name of the repo + // type: string + // required: true + // - name: id + // in: path + // description: id of the comment + // type: integer + // format: int64 + // required: true + // - name: attachment_id + // in: path + // description: id of the attachment to edit + // type: integer + // format: int64 + // required: true + // - name: body + // in: body + // schema: + // "$ref": "#/definitions/EditAttachmentOptions" + // responses: + // "201": + // "$ref": "#/responses/Attachment" + // "404": + // "$ref": "#/responses/error" + + attach := getIssueCommentAttachmentSafeWrite(ctx) + if attach == nil { + return + } + + form := web.GetForm(ctx).(*api.EditAttachmentOptions) + if form.Name != "" { + attach.Name = form.Name + } + + if err := repo_model.UpdateAttachment(ctx, attach); err != nil { + ctx.Error(http.StatusInternalServerError, "UpdateAttachment", attach) + } + ctx.JSON(http.StatusCreated, convert.ToAttachment(attach)) +} + +// DeleteIssueCommentAttachment delete a given attachment +func DeleteIssueCommentAttachment(ctx *context.APIContext) { + // swagger:operation DELETE /repos/{owner}/{repo}/issues/comments/{id}/assets/{attachment_id} issue issueDeleteIssueCommentAttachment + // --- + // summary: Delete a comment attachment + // produces: + // - application/json + // parameters: + // - name: owner + // in: path + // description: owner of the repo + // type: string + // required: true + // - name: repo + // in: path + // description: name of the repo + // type: string + // required: true + // - name: id + // in: path + // description: id of the comment + // type: integer + // format: int64 + // required: true + // - name: attachment_id + // in: path + // description: id of the attachment to delete + // type: integer + // format: int64 + // required: true + // responses: + // "204": + // "$ref": "#/responses/empty" + // "404": + // "$ref": "#/responses/error" + + attach := getIssueCommentAttachmentSafeWrite(ctx) + if attach == nil { + return + } + + if err := repo_model.DeleteAttachment(attach, true); err != nil { + ctx.Error(http.StatusInternalServerError, "DeleteAttachment", err) + return + } + ctx.Status(http.StatusNoContent) +} + +func getIssueCommentSafe(ctx *context.APIContext) *issues_model.Comment { + comment, err := issues_model.GetCommentByID(ctx, ctx.ParamsInt64("id")) + if err != nil { + ctx.NotFoundOrServerError("GetCommentByID", issues_model.IsErrCommentNotExist, err) + return nil + } + if err := comment.LoadIssue(ctx); err != nil { + ctx.Error(http.StatusInternalServerError, "comment.LoadIssue", err) + return nil + } + if comment.Issue == nil || comment.Issue.RepoID != ctx.Repo.Repository.ID { + ctx.Error(http.StatusNotFound, "", "no matching issue comment found") + return nil + } + + comment.Issue.Repo = ctx.Repo.Repository + + return comment +} + +func getIssueCommentAttachmentSafeWrite(ctx *context.APIContext) *repo_model.Attachment { + comment := getIssueCommentSafe(ctx) + if comment == nil { + return nil + } + if !canUserWriteIssueCommentAttachment(ctx, comment) { + return nil + } + return getIssueCommentAttachmentSafeRead(ctx, comment) +} + +func canUserWriteIssueCommentAttachment(ctx *context.APIContext, comment *issues_model.Comment) bool { + canEditComment := ctx.IsSigned && (ctx.Doer.ID == comment.PosterID || ctx.IsUserRepoAdmin() || ctx.IsUserSiteAdmin()) && ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull) + if !canEditComment { + ctx.Error(http.StatusForbidden, "", "user should have permission to edit comment") + return false + } + + return true +} + +func getIssueCommentAttachmentSafeRead(ctx *context.APIContext, comment *issues_model.Comment) *repo_model.Attachment { + attachment, err := repo_model.GetAttachmentByID(ctx, ctx.ParamsInt64("asset")) + if err != nil { + ctx.NotFoundOrServerError("GetAttachmentByID", repo_model.IsErrAttachmentNotExist, err) + return nil + } + if !attachmentBelongsToRepoOrComment(ctx, attachment, comment) { + return nil + } + return attachment +} + +func attachmentBelongsToRepoOrComment(ctx *context.APIContext, attachment *repo_model.Attachment, comment *issues_model.Comment) bool { + if attachment.RepoID != ctx.Repo.Repository.ID { + log.Debug("Requested attachment[%d] does not belong to repo[%-v].", attachment.ID, ctx.Repo.Repository) + ctx.NotFound("no such attachment in repo") + return false + } + if attachment.IssueID == 0 || attachment.CommentID == 0 { + log.Debug("Requested attachment[%d] is not in a comment.", attachment.ID) + ctx.NotFound("no such attachment in comment") + return false + } + if comment != nil && attachment.CommentID != comment.ID { + log.Debug("Requested attachment[%d] does not belong to comment[%d].", attachment.ID, comment.ID) + ctx.NotFound("no such attachment in comment") + return false + } + return true +} diff --git a/routers/api/v1/repo/issue_label.go b/routers/api/v1/repo/issue_label.go index 091f1ce27c..04d70913c7 100644 --- a/routers/api/v1/repo/issue_label.go +++ b/routers/api/v1/repo/issue_label.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/issue_reaction.go b/routers/api/v1/repo/issue_reaction.go index f4c40d2bcd..dcfe7967b5 100644 --- a/routers/api/v1/repo/issue_reaction.go +++ b/routers/api/v1/repo/issue_reaction.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo @@ -58,7 +57,7 @@ func GetIssueCommentReactions(ctx *context.APIContext) { return } - if err := comment.LoadIssue(); err != nil { + if err := comment.LoadIssue(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "comment.LoadIssue", err) } @@ -185,7 +184,7 @@ func changeIssueCommentReaction(ctx *context.APIContext, form api.EditReactionOp return } - err = comment.LoadIssue() + err = comment.LoadIssue(ctx) if err != nil { ctx.Error(http.StatusInternalServerError, "comment.LoadIssue() failed", err) } diff --git a/routers/api/v1/repo/issue_stopwatch.go b/routers/api/v1/repo/issue_stopwatch.go index 941b22e454..110139cc36 100644 --- a/routers/api/v1/repo/issue_stopwatch.go +++ b/routers/api/v1/repo/issue_stopwatch.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/issue_subscription.go b/routers/api/v1/repo/issue_subscription.go index 5e03e42b4c..32832d83f7 100644 --- a/routers/api/v1/repo/issue_subscription.go +++ b/routers/api/v1/repo/issue_subscription.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/issue_tracked_time.go b/routers/api/v1/repo/issue_tracked_time.go index 1e26403ec8..ede60a2ed8 100644 --- a/routers/api/v1/repo/issue_tracked_time.go +++ b/routers/api/v1/repo/issue_tracked_time.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo @@ -72,7 +71,7 @@ func ListTrackedTimes(ctx *context.APIContext) { // "404": // "$ref": "#/responses/notFound" - if !ctx.Repo.Repository.IsTimetrackerEnabled() { + if !ctx.Repo.Repository.IsTimetrackerEnabled(ctx) { ctx.NotFound("Timetracker is disabled") return } @@ -139,7 +138,7 @@ func ListTrackedTimes(ctx *context.APIContext) { } ctx.SetTotalCountHeader(count) - ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(trackedTimes)) + ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(ctx, trackedTimes)) } // AddTime add time manual to the given issue @@ -191,7 +190,7 @@ func AddTime(ctx *context.APIContext) { } if !ctx.Repo.CanUseTimetracker(issue, ctx.Doer) { - if !ctx.Repo.Repository.IsTimetrackerEnabled() { + if !ctx.Repo.Repository.IsTimetrackerEnabled(ctx) { ctx.Error(http.StatusBadRequest, "", "time tracking disabled") return } @@ -224,7 +223,7 @@ func AddTime(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } - ctx.JSON(http.StatusOK, convert.ToTrackedTime(trackedTime)) + ctx.JSON(http.StatusOK, convert.ToTrackedTime(ctx, trackedTime)) } // ResetIssueTime reset time manual to the given issue @@ -272,7 +271,7 @@ func ResetIssueTime(ctx *context.APIContext) { } if !ctx.Repo.CanUseTimetracker(issue, ctx.Doer) { - if !ctx.Repo.Repository.IsTimetrackerEnabled() { + if !ctx.Repo.Repository.IsTimetrackerEnabled(ctx) { ctx.JSON(http.StatusBadRequest, struct{ Message string }{Message: "time tracking disabled"}) return } @@ -343,7 +342,7 @@ func DeleteTime(ctx *context.APIContext) { } if !ctx.Repo.CanUseTimetracker(issue, ctx.Doer) { - if !ctx.Repo.Repository.IsTimetrackerEnabled() { + if !ctx.Repo.Repository.IsTimetrackerEnabled(ctx) { ctx.JSON(http.StatusBadRequest, struct{ Message string }{Message: "time tracking disabled"}) return } @@ -411,7 +410,7 @@ func ListTrackedTimesByUser(ctx *context.APIContext) { // "403": // "$ref": "#/responses/forbidden" - if !ctx.Repo.Repository.IsTimetrackerEnabled() { + if !ctx.Repo.Repository.IsTimetrackerEnabled(ctx) { ctx.Error(http.StatusBadRequest, "", "time tracking disabled") return } @@ -448,7 +447,7 @@ func ListTrackedTimesByUser(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } - ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(trackedTimes)) + ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(ctx, trackedTimes)) } // ListTrackedTimesByRepository lists all tracked times of the repository @@ -499,7 +498,7 @@ func ListTrackedTimesByRepository(ctx *context.APIContext) { // "403": // "$ref": "#/responses/forbidden" - if !ctx.Repo.Repository.IsTimetrackerEnabled() { + if !ctx.Repo.Repository.IsTimetrackerEnabled(ctx) { ctx.Error(http.StatusBadRequest, "", "time tracking disabled") return } @@ -558,7 +557,7 @@ func ListTrackedTimesByRepository(ctx *context.APIContext) { } ctx.SetTotalCountHeader(count) - ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(trackedTimes)) + ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(ctx, trackedTimes)) } // ListMyTrackedTimes lists all tracked times of the current user @@ -620,5 +619,5 @@ func ListMyTrackedTimes(ctx *context.APIContext) { } ctx.SetTotalCountHeader(count) - ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(trackedTimes)) + ctx.JSON(http.StatusOK, convert.ToTrackedTimeList(ctx, trackedTimes)) } diff --git a/routers/api/v1/repo/key.go b/routers/api/v1/repo/key.go index 14f6aa6148..54313e8e76 100644 --- a/routers/api/v1/repo/key.go +++ b/routers/api/v1/repo/key.go @@ -1,11 +1,11 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package repo import ( + stdCtx "context" "fmt" "net/http" "net/url" @@ -24,16 +24,16 @@ import ( ) // appendPrivateInformation appends the owner and key type information to api.PublicKey -func appendPrivateInformation(apiKey *api.DeployKey, key *asymkey_model.DeployKey, repository *repo_model.Repository) (*api.DeployKey, error) { +func appendPrivateInformation(ctx stdCtx.Context, apiKey *api.DeployKey, key *asymkey_model.DeployKey, repository *repo_model.Repository) (*api.DeployKey, error) { apiKey.ReadOnly = key.Mode == perm.AccessModeRead if repository.ID == key.RepoID { - apiKey.Repository = convert.ToRepo(repository, key.Mode) + apiKey.Repository = convert.ToRepo(ctx, repository, key.Mode) } else { - repo, err := repo_model.GetRepositoryByID(key.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, key.RepoID) if err != nil { return apiKey, err } - apiKey.Repository = convert.ToRepo(repo, key.Mode) + apiKey.Repository = convert.ToRepo(ctx, repo, key.Mode) } return apiKey, nil } @@ -108,7 +108,7 @@ func ListDeployKeys(ctx *context.APIContext) { } apiKeys[i] = convert.ToDeployKey(apiLink, keys[i]) if ctx.Doer.IsAdmin || ((ctx.Repo.Repository.ID == keys[i].RepoID) && (ctx.Doer.ID == ctx.Repo.Owner.ID)) { - apiKeys[i], _ = appendPrivateInformation(apiKeys[i], keys[i], ctx.Repo.Repository) + apiKeys[i], _ = appendPrivateInformation(ctx, apiKeys[i], keys[i], ctx.Repo.Repository) } } @@ -162,7 +162,7 @@ func GetDeployKey(ctx *context.APIContext) { apiLink := composeDeployKeysAPILink(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name) apiKey := convert.ToDeployKey(apiLink, key) if ctx.Doer.IsAdmin || ((ctx.Repo.Repository.ID == key.RepoID) && (ctx.Doer.ID == ctx.Repo.Owner.ID)) { - apiKey, _ = appendPrivateInformation(apiKey, key, ctx.Repo.Repository) + apiKey, _ = appendPrivateInformation(ctx, apiKey, key, ctx.Repo.Repository) } ctx.JSON(http.StatusOK, apiKey) } diff --git a/routers/api/v1/repo/label.go b/routers/api/v1/repo/label.go index 8b1e298668..8b49becd37 100644 --- a/routers/api/v1/repo/label.go +++ b/routers/api/v1/repo/label.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/language.go b/routers/api/v1/repo/language.go index ca803cb68b..12f1761ad0 100644 --- a/routers/api/v1/repo/language.go +++ b/routers/api/v1/repo/language.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/main_test.go b/routers/api/v1/repo/main_test.go index 1f91a24937..543fb922d6 100644 --- a/routers/api/v1/repo/main_test.go +++ b/routers/api/v1/repo/main_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/migrate.go b/routers/api/v1/repo/migrate.go index ed371d787c..35516ff58f 100644 --- a/routers/api/v1/repo/migrate.go +++ b/routers/api/v1/repo/migrate.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo @@ -67,7 +66,7 @@ func Migrate(ctx *context.APIContext) { if len(form.RepoOwner) != 0 { repoOwner, err = user_model.GetUserByName(ctx, form.RepoOwner) } else if form.RepoOwnerID != 0 { - repoOwner, err = user_model.GetUserByID(form.RepoOwnerID) + repoOwner, err = user_model.GetUserByID(ctx, form.RepoOwnerID) } else { repoOwner = ctx.Doer } @@ -195,7 +194,7 @@ func Migrate(ctx *context.APIContext) { } if err == nil { - notification.NotifyMigrateRepository(ctx.Doer, repoOwner, repo) + notification.NotifyMigrateRepository(ctx, ctx.Doer, repoOwner, repo) return } @@ -212,7 +211,7 @@ func Migrate(ctx *context.APIContext) { } log.Trace("Repository migrated: %s/%s", repoOwner.Name, form.RepoName) - ctx.JSON(http.StatusCreated, convert.ToRepo(repo, perm.AccessModeAdmin)) + ctx.JSON(http.StatusCreated, convert.ToRepo(ctx, repo, perm.AccessModeAdmin)) } func handleMigrateError(ctx *context.APIContext, repoOwner *user_model.User, remoteAddr string, err error) { diff --git a/routers/api/v1/repo/milestone.go b/routers/api/v1/repo/milestone.go index 0e8800510b..2b80b4df73 100644 --- a/routers/api/v1/repo/milestone.go +++ b/routers/api/v1/repo/milestone.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/mirror.go b/routers/api/v1/repo/mirror.go index 91e5e0c031..b693c0e7db 100644 --- a/routers/api/v1/repo/mirror.go +++ b/routers/api/v1/repo/mirror.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/notes.go b/routers/api/v1/repo/notes.go index ee3133adec..91eebb4c72 100644 --- a/routers/api/v1/repo/notes.go +++ b/routers/api/v1/repo/notes.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/patch.go b/routers/api/v1/repo/patch.go index 40afe2d92b..6fbb9e7b3a 100644 --- a/routers/api/v1/repo/patch.go +++ b/routers/api/v1/repo/patch.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/pull.go b/routers/api/v1/repo/pull.go index f7e82dab37..1246ede9e6 100644 --- a/routers/api/v1/repo/pull.go +++ b/routers/api/v1/repo/pull.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package repo @@ -109,19 +108,19 @@ func ListPullRequests(ctx *context.APIContext) { apiPrs := make([]*api.PullRequest, len(prs)) for i := range prs { - if err = prs[i].LoadIssue(); err != nil { + if err = prs[i].LoadIssue(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadIssue", err) return } - if err = prs[i].LoadAttributes(); err != nil { + if err = prs[i].LoadAttributes(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } - if err = prs[i].LoadBaseRepoCtx(ctx); err != nil { + if err = prs[i].LoadBaseRepo(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err) return } - if err = prs[i].LoadHeadRepoCtx(ctx); err != nil { + if err = prs[i].LoadHeadRepo(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err) return } @@ -173,11 +172,11 @@ func GetPullRequest(ctx *context.APIContext) { return } - if err = pr.LoadBaseRepoCtx(ctx); err != nil { + if err = pr.LoadBaseRepo(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err) return } - if err = pr.LoadHeadRepoCtx(ctx); err != nil { + if err = pr.LoadHeadRepo(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err) return } @@ -300,7 +299,7 @@ func CreatePullRequest(ctx *context.APIContext) { defer headGitRepo.Close() // Check if another PR exists with the same targets - existingPr, err := issues_model.GetUnmergedPullRequest(headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch, issues_model.PullRequestFlowGithub) + existingPr, err := issues_model.GetUnmergedPullRequest(ctx, headRepo.ID, ctx.Repo.Repository.ID, headBranch, baseBranch, issues_model.PullRequestFlowGithub) if err != nil { if !issues_model.IsErrPullRequestNotExist(err) { ctx.Error(http.StatusInternalServerError, "GetUnmergedPullRequest", err) @@ -320,7 +319,7 @@ func CreatePullRequest(ctx *context.APIContext) { } if len(form.Labels) > 0 { - labels, err := issues_model.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels) + labels, err := issues_model.GetLabelsInRepoByIDs(ctx, ctx.Repo.Repository.ID, form.Labels) if err != nil { ctx.Error(http.StatusInternalServerError, "GetLabelsInRepoByIDs", err) return @@ -334,7 +333,7 @@ func CreatePullRequest(ctx *context.APIContext) { } if ctx.Repo.Owner.IsOrganization() { - orgLabels, err := issues_model.GetLabelsInOrgByIDs(ctx.Repo.Owner.ID, form.Labels) + orgLabels, err := issues_model.GetLabelsInOrgByIDs(ctx, ctx.Repo.Owner.ID, form.Labels) if err != nil { ctx.Error(http.StatusInternalServerError, "GetLabelsInOrgByIDs", err) return @@ -389,7 +388,7 @@ func CreatePullRequest(ctx *context.APIContext) { } // Get all assignee IDs - assigneeIDs, err := issues_model.MakeIDsFromAPIAssigneesToAdd(form.Assignee, form.Assignees) + assigneeIDs, err := issues_model.MakeIDsFromAPIAssigneesToAdd(ctx, form.Assignee, form.Assignees) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.Error(http.StatusUnprocessableEntity, "", fmt.Sprintf("Assignee does not exist: [name: %s]", err)) @@ -400,7 +399,7 @@ func CreatePullRequest(ctx *context.APIContext) { } // Check if the passed assignees is assignable for _, aID := range assigneeIDs { - assignee, err := user_model.GetUserByID(aID) + assignee, err := user_model.GetUserByID(ctx, aID) if err != nil { ctx.Error(http.StatusInternalServerError, "GetUserByID", err) return @@ -483,7 +482,7 @@ func EditPullRequest(ctx *context.APIContext) { return } - err = pr.LoadIssue() + err = pr.LoadIssue(ctx) if err != nil { ctx.Error(http.StatusInternalServerError, "LoadIssue", err) return @@ -551,14 +550,14 @@ func EditPullRequest(ctx *context.APIContext) { } if ctx.Repo.CanWrite(unit.TypePullRequests) && form.Labels != nil { - labels, err := issues_model.GetLabelsInRepoByIDs(ctx.Repo.Repository.ID, form.Labels) + labels, err := issues_model.GetLabelsInRepoByIDs(ctx, ctx.Repo.Repository.ID, form.Labels) if err != nil { ctx.Error(http.StatusInternalServerError, "GetLabelsInRepoByIDsError", err) return } if ctx.Repo.Owner.IsOrganization() { - orgLabels, err := issues_model.GetLabelsInOrgByIDs(ctx.Repo.Owner.ID, form.Labels) + orgLabels, err := issues_model.GetLabelsInOrgByIDs(ctx, ctx.Repo.Owner.ID, form.Labels) if err != nil { ctx.Error(http.StatusInternalServerError, "GetLabelsInOrgByIDs", err) return @@ -591,11 +590,11 @@ func EditPullRequest(ctx *context.APIContext) { } if titleChanged { - notification.NotifyIssueChangeTitle(ctx.Doer, issue, oldTitle) + notification.NotifyIssueChangeTitle(ctx, ctx.Doer, issue, oldTitle) } if statusChangeComment != nil { - notification.NotifyIssueChangeStatus(ctx.Doer, issue, statusChangeComment, issue.IsClosed) + notification.NotifyIssueChangeStatus(ctx, ctx.Doer, issue, statusChangeComment, issue.IsClosed) } // change pull target branch @@ -619,7 +618,7 @@ func EditPullRequest(ctx *context.APIContext) { } return } - notification.NotifyPullRequestChangeTargetBranch(ctx.Doer, pr, form.Base) + notification.NotifyPullRequestChangeTargetBranch(ctx, ctx.Doer, pr, form.Base) } // update allow edits @@ -743,12 +742,12 @@ func MergePullRequest(ctx *context.APIContext) { return } - if err := pr.LoadHeadRepoCtx(ctx); err != nil { + if err := pr.LoadHeadRepo(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err) return } - if err := pr.LoadIssueCtx(ctx); err != nil { + if err := pr.LoadIssue(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadIssue", err) return } @@ -811,7 +810,7 @@ func MergePullRequest(ctx *context.APIContext) { message := strings.TrimSpace(form.MergeTitleField) if len(message) == 0 { - message, err = pull_service.GetDefaultMergeMessage(ctx.Repo.GitRepo, pr, repo_model.MergeStyle(form.Do)) + message, err = pull_service.GetDefaultMergeMessage(ctx, ctx.Repo.GitRepo, pr, repo_model.MergeStyle(form.Do)) if err != nil { ctx.Error(http.StatusInternalServerError, "GetDefaultMergeMessage", err) return @@ -1097,7 +1096,7 @@ func UpdatePullRequest(ctx *context.APIContext) { return } - if err = pr.LoadIssue(); err != nil { + if err = pr.LoadIssue(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadIssue", err) return } @@ -1107,11 +1106,11 @@ func UpdatePullRequest(ctx *context.APIContext) { return } - if err = pr.LoadBaseRepoCtx(ctx); err != nil { + if err = pr.LoadBaseRepo(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadBaseRepo", err) return } - if err = pr.LoadHeadRepoCtx(ctx); err != nil { + if err = pr.LoadHeadRepo(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadHeadRepo", err) return } @@ -1267,7 +1266,7 @@ func GetPullRequestCommits(ctx *context.APIContext) { return } - if err := pr.LoadBaseRepoCtx(ctx); err != nil { + if err := pr.LoadBaseRepo(ctx); err != nil { ctx.InternalServerError(err) return } @@ -1383,12 +1382,12 @@ func GetPullRequestFiles(ctx *context.APIContext) { return } - if err := pr.LoadBaseRepo(); err != nil { + if err := pr.LoadBaseRepo(ctx); err != nil { ctx.InternalServerError(err) return } - if err := pr.LoadHeadRepo(); err != nil { + if err := pr.LoadHeadRepo(ctx); err != nil { ctx.InternalServerError(err) return } diff --git a/routers/api/v1/repo/pull_review.go b/routers/api/v1/repo/pull_review.go index f36d0586ab..2f357afb79 100644 --- a/routers/api/v1/repo/pull_review.go +++ b/routers/api/v1/repo/pull_review.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo @@ -71,7 +70,7 @@ func ListPullReviews(ctx *context.APIContext) { return } - if err = pr.LoadIssue(); err != nil { + if err = pr.LoadIssue(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadIssue", err) return } @@ -476,7 +475,7 @@ func SubmitPullReview(ctx *context.APIContext) { // preparePullReviewType return ReviewType and false or nil and true if an error happen func preparePullReviewType(ctx *context.APIContext, pr *issues_model.PullRequest, event api.ReviewStateType, body string, hasComments bool) (issues_model.ReviewType, bool) { - if err := pr.LoadIssue(); err != nil { + if err := pr.LoadIssue(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadIssue", err) return -1, true } diff --git a/routers/api/v1/repo/release.go b/routers/api/v1/repo/release.go index acc9696e1b..4e1927ea3d 100644 --- a/routers/api/v1/repo/release.go +++ b/routers/api/v1/repo/release.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package repo @@ -61,7 +60,7 @@ func GetRelease(ctx *context.APIContext) { return } - if err := release.LoadAttributes(); err != nil { + if err := release.LoadAttributes(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } @@ -123,14 +122,14 @@ func ListReleases(ctx *context.APIContext) { IsPreRelease: ctx.FormOptionalBool("pre-release"), } - releases, err := repo_model.GetReleasesByRepoID(ctx.Repo.Repository.ID, opts) + releases, err := repo_model.GetReleasesByRepoID(ctx, ctx.Repo.Repository.ID, opts) if err != nil { ctx.Error(http.StatusInternalServerError, "GetReleasesByRepoID", err) return } rels := make([]*api.Release, len(releases)) for i, release := range releases { - if err := release.LoadAttributes(); err != nil { + if err := release.LoadAttributes(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } @@ -313,7 +312,7 @@ func EditRelease(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "GetReleaseByID", err) return } - if err := rel.LoadAttributes(); err != nil { + if err := rel.LoadAttributes(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } diff --git a/routers/api/v1/repo/release_attachment.go b/routers/api/v1/repo/release_attachment.go index a469877c13..e7dbb42c74 100644 --- a/routers/api/v1/repo/release_attachment.go +++ b/routers/api/v1/repo/release_attachment.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo @@ -69,7 +68,7 @@ func GetReleaseAttachment(ctx *context.APIContext) { return } // FIXME Should prove the existence of the given repo, but results in unnecessary database requests - ctx.JSON(http.StatusOK, convert.ToReleaseAttachment(attach)) + ctx.JSON(http.StatusOK, convert.ToAttachment(attach)) } // ListReleaseAttachments lists all attachments of the release @@ -114,7 +113,7 @@ func ListReleaseAttachments(ctx *context.APIContext) { ctx.NotFound() return } - if err := release.LoadAttributes(); err != nil { + if err := release.LoadAttributes(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } @@ -195,7 +194,12 @@ func CreateReleaseAttachment(ctx *context.APIContext) { } // Create a new attachment and save the file - attach, err := attachment.UploadAttachment(file, ctx.Doer.ID, release.RepoID, releaseID, filename, setting.Repository.Release.AllowedTypes) + attach, err := attachment.UploadAttachment(file, setting.Repository.Release.AllowedTypes, &repo_model.Attachment{ + Name: filename, + UploaderID: ctx.Doer.ID, + RepoID: release.RepoID, + ReleaseID: releaseID, + }) if err != nil { if upload.IsErrFileTypeForbidden(err) { ctx.Error(http.StatusBadRequest, "DetectContentType", err) @@ -205,7 +209,7 @@ func CreateReleaseAttachment(ctx *context.APIContext) { return } - ctx.JSON(http.StatusCreated, convert.ToReleaseAttachment(attach)) + ctx.JSON(http.StatusCreated, convert.ToAttachment(attach)) } // EditReleaseAttachment updates the given attachment @@ -275,7 +279,7 @@ func EditReleaseAttachment(ctx *context.APIContext) { if err := repo_model.UpdateAttachment(ctx, attach); err != nil { ctx.Error(http.StatusInternalServerError, "UpdateAttachment", attach) } - ctx.JSON(http.StatusCreated, convert.ToReleaseAttachment(attach)) + ctx.JSON(http.StatusCreated, convert.ToAttachment(attach)) } // DeleteReleaseAttachment delete a given attachment diff --git a/routers/api/v1/repo/release_tags.go b/routers/api/v1/repo/release_tags.go index 2cb97c58a0..5e1f1860ae 100644 --- a/routers/api/v1/repo/release_tags.go +++ b/routers/api/v1/repo/release_tags.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo @@ -60,7 +59,7 @@ func GetReleaseByTag(ctx *context.APIContext) { return } - if err = release.LoadAttributes(); err != nil { + if err = release.LoadAttributes(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "LoadAttributes", err) return } diff --git a/routers/api/v1/repo/repo.go b/routers/api/v1/repo/repo.go index de8a4d1864..3490405078 100644 --- a/routers/api/v1/repo/repo.go +++ b/routers/api/v1/repo/repo.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo @@ -191,7 +190,7 @@ func Search(ctx *context.APIContext) { } var err error - repos, count, err := repo_model.SearchRepository(opts) + repos, count, err := repo_model.SearchRepository(ctx, opts) if err != nil { ctx.JSON(http.StatusInternalServerError, api.SearchError{ OK: false, @@ -209,14 +208,14 @@ func Search(ctx *context.APIContext) { }) return } - accessMode, err := access_model.AccessLevel(ctx.Doer, repo) + accessMode, err := access_model.AccessLevel(ctx, ctx.Doer, repo) if err != nil { ctx.JSON(http.StatusInternalServerError, api.SearchError{ OK: false, Error: err.Error(), }) } - results[i] = convert.ToRepo(repo, accessMode) + results[i] = convert.ToRepo(ctx, repo, accessMode) } ctx.SetLinkHeader(int(count), opts.PageSize) ctx.SetTotalCountHeader(count) @@ -258,12 +257,12 @@ func CreateUserRepo(ctx *context.APIContext, owner *user_model.User, opt api.Cre } // reload repo from db to get a real state after creation - repo, err = repo_model.GetRepositoryByID(repo.ID) + repo, err = repo_model.GetRepositoryByID(ctx, repo.ID) if err != nil { ctx.Error(http.StatusInternalServerError, "GetRepositoryByID", err) } - ctx.JSON(http.StatusCreated, convert.ToRepo(repo, perm.AccessModeOwner)) + ctx.JSON(http.StatusCreated, convert.ToRepo(ctx, repo, perm.AccessModeOwner)) } // Create one repository of mine @@ -408,7 +407,7 @@ func Generate(ctx *context.APIContext) { } log.Trace("Repository generated [%d]: %s/%s", repo.ID, ctxUser.Name, repo.Name) - ctx.JSON(http.StatusCreated, convert.ToRepo(repo, perm.AccessModeOwner)) + ctx.JSON(http.StatusCreated, convert.ToRepo(ctx, repo, perm.AccessModeOwner)) } // CreateOrgRepoDeprecated create one repository of the organization @@ -524,7 +523,7 @@ func Get(ctx *context.APIContext) { return } - ctx.JSON(http.StatusOK, convert.ToRepo(ctx.Repo.Repository, ctx.Repo.AccessMode)) + ctx.JSON(http.StatusOK, convert.ToRepo(ctx, ctx.Repo.Repository, ctx.Repo.AccessMode)) } // GetByID returns a single Repository @@ -545,7 +544,7 @@ func GetByID(ctx *context.APIContext) { // "200": // "$ref": "#/responses/Repository" - repo, err := repo_model.GetRepositoryByID(ctx.ParamsInt64(":id")) + repo, err := repo_model.GetRepositoryByID(ctx, ctx.ParamsInt64(":id")) if err != nil { if repo_model.IsErrRepoNotExist(err) { ctx.NotFound() @@ -563,7 +562,7 @@ func GetByID(ctx *context.APIContext) { ctx.NotFound() return } - ctx.JSON(http.StatusOK, convert.ToRepo(repo, perm.AccessMode)) + ctx.JSON(http.StatusOK, convert.ToRepo(ctx, repo, perm.AccessMode)) } // Edit edit repository properties @@ -619,13 +618,13 @@ func Edit(ctx *context.APIContext) { } } - repo, err := repo_model.GetRepositoryByID(ctx.Repo.Repository.ID) + repo, err := repo_model.GetRepositoryByID(ctx, ctx.Repo.Repository.ID) if err != nil { ctx.InternalServerError(err) return } - ctx.JSON(http.StatusOK, convert.ToRepo(repo, ctx.Repo.AccessMode)) + ctx.JSON(http.StatusOK, convert.ToRepo(ctx, repo, ctx.Repo.AccessMode)) } // updateBasicProperties updates the basic properties of a repo: Name, Description, Website and Visibility @@ -670,7 +669,7 @@ func updateBasicProperties(ctx *context.APIContext, opts api.EditRepoOption) err if opts.Private != nil { // Visibility of forked repository is forced sync with base repository. if repo.IsFork { - if err := repo.GetBaseRepo(); err != nil { + if err := repo.GetBaseRepo(ctx); err != nil { ctx.Error(http.StatusInternalServerError, "Unable to load base repository", err) return err } @@ -732,7 +731,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { var units []repo_model.RepoUnit var deleteUnitTypes []unit_model.Type - currHasIssues := repo.UnitEnabledCtx(ctx, unit_model.TypeIssues) + currHasIssues := repo.UnitEnabled(ctx, unit_model.TypeIssues) newHasIssues := currHasIssues if opts.HasIssues != nil { newHasIssues = *opts.HasIssues @@ -772,7 +771,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { AllowOnlyContributorsToTrackTime: opts.InternalTracker.AllowOnlyContributorsToTrackTime, EnableDependencies: opts.InternalTracker.EnableIssueDependencies, } - } else if unit, err := repo.GetUnit(unit_model.TypeIssues); err != nil { + } else if unit, err := repo.GetUnit(ctx, unit_model.TypeIssues); err != nil { // Unit type doesn't exist so we make a new config file with default values config = &repo_model.IssuesConfig{ EnableTimetracker: true, @@ -799,7 +798,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { } } - currHasWiki := repo.UnitEnabledCtx(ctx, unit_model.TypeWiki) + currHasWiki := repo.UnitEnabled(ctx, unit_model.TypeWiki) newHasWiki := currHasWiki if opts.HasWiki != nil { newHasWiki = *opts.HasWiki @@ -839,7 +838,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { } } - currHasPullRequests := repo.UnitEnabledCtx(ctx, unit_model.TypePullRequests) + currHasPullRequests := repo.UnitEnabled(ctx, unit_model.TypePullRequests) newHasPullRequests := currHasPullRequests if opts.HasPullRequests != nil { newHasPullRequests = *opts.HasPullRequests @@ -849,7 +848,7 @@ func updateRepoUnits(ctx *context.APIContext, opts api.EditRepoOption) error { // We do allow setting individual PR settings through the API, so // we get the config settings and then set them // if those settings were provided in the opts. - unit, err := repo.GetUnit(unit_model.TypePullRequests) + unit, err := repo.GetUnit(ctx, unit_model.TypePullRequests) var config *repo_model.PullRequestsConfig if err != nil { // Unit type doesn't exist so we make a new config file with default values diff --git a/routers/api/v1/repo/repo_test.go b/routers/api/v1/repo/repo_test.go index 9acc0ee7d2..59c3bde819 100644 --- a/routers/api/v1/repo/repo_test.go +++ b/routers/api/v1/repo/repo_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/star.go b/routers/api/v1/repo/star.go index c78c3cc512..a3d1105873 100644 --- a/routers/api/v1/repo/star.go +++ b/routers/api/v1/repo/star.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/status.go b/routers/api/v1/repo/status.go index 97ef69a6ea..0b196d162c 100644 --- a/routers/api/v1/repo/status.go +++ b/routers/api/v1/repo/status.go @@ -1,6 +1,5 @@ // Copyright 2017 Gitea. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package repo @@ -67,7 +66,7 @@ func NewCommitStatus(ctx *context.APIContext) { return } - ctx.JSON(http.StatusCreated, convert.ToCommitStatus(status)) + ctx.JSON(http.StatusCreated, convert.ToCommitStatus(ctx, status)) } // GetCommitStatuses returns all statuses for any given commit hash @@ -200,7 +199,7 @@ func getCommitStatuses(ctx *context.APIContext, sha string) { apiStatuses := make([]*api.CommitStatus, 0, len(statuses)) for _, status := range statuses { - apiStatuses = append(apiStatuses, convert.ToCommitStatus(status)) + apiStatuses = append(apiStatuses, convert.ToCommitStatus(ctx, status)) } ctx.SetLinkHeader(int(maxResults), listOptions.PageSize) @@ -264,7 +263,7 @@ func GetCombinedCommitStatusByRef(ctx *context.APIContext) { return } - combiStatus := convert.ToCombinedStatus(statuses, convert.ToRepo(repo, ctx.Repo.AccessMode)) + combiStatus := convert.ToCombinedStatus(ctx, statuses, convert.ToRepo(ctx, repo, ctx.Repo.AccessMode)) ctx.SetTotalCountHeader(count) ctx.JSON(http.StatusOK, combiStatus) diff --git a/routers/api/v1/repo/subscriber.go b/routers/api/v1/repo/subscriber.go index c1aaa24193..5cc94abd48 100644 --- a/routers/api/v1/repo/subscriber.go +++ b/routers/api/v1/repo/subscriber.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/tag.go b/routers/api/v1/repo/tag.go index ab31866162..6b38a08c2f 100644 --- a/routers/api/v1/repo/tag.go +++ b/routers/api/v1/repo/tag.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/teams.go b/routers/api/v1/repo/teams.go index f485f2086e..1ea3ae0008 100644 --- a/routers/api/v1/repo/teams.go +++ b/routers/api/v1/repo/teams.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/topic.go b/routers/api/v1/repo/topic.go index 64dc763dc3..316b190259 100644 --- a/routers/api/v1/repo/topic.go +++ b/routers/api/v1/repo/topic.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/transfer.go b/routers/api/v1/repo/transfer.go index 067a4ebe19..5154c5afa3 100644 --- a/routers/api/v1/repo/transfer.go +++ b/routers/api/v1/repo/transfer.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo @@ -106,7 +105,7 @@ func Transfer(ctx *context.APIContext) { oldFullname := ctx.Repo.Repository.FullName() - if err := repo_service.StartRepositoryTransfer(ctx.Doer, newOwner, ctx.Repo.Repository, teams); err != nil { + if err := repo_service.StartRepositoryTransfer(ctx, ctx.Doer, newOwner, ctx.Repo.Repository, teams); err != nil { if models.IsErrRepoTransferInProgress(err) { ctx.Error(http.StatusConflict, "StartRepositoryTransfer", err) return @@ -123,12 +122,12 @@ func Transfer(ctx *context.APIContext) { if ctx.Repo.Repository.Status == repo_model.RepositoryPendingTransfer { log.Trace("Repository transfer initiated: %s -> %s", oldFullname, ctx.Repo.Repository.FullName()) - ctx.JSON(http.StatusCreated, convert.ToRepo(ctx.Repo.Repository, perm.AccessModeAdmin)) + ctx.JSON(http.StatusCreated, convert.ToRepo(ctx, ctx.Repo.Repository, perm.AccessModeAdmin)) return } log.Trace("Repository transferred: %s -> %s", oldFullname, ctx.Repo.Repository.FullName()) - ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx.Repo.Repository, perm.AccessModeAdmin)) + ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx, ctx.Repo.Repository, perm.AccessModeAdmin)) } // AcceptTransfer accept a repo transfer @@ -166,7 +165,7 @@ func AcceptTransfer(ctx *context.APIContext) { return } - ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx.Repo.Repository, ctx.Repo.AccessMode)) + ctx.JSON(http.StatusAccepted, convert.ToRepo(ctx, ctx.Repo.Repository, ctx.Repo.AccessMode)) } // RejectTransfer reject a repo transfer @@ -204,11 +203,11 @@ func RejectTransfer(ctx *context.APIContext) { return } - ctx.JSON(http.StatusOK, convert.ToRepo(ctx.Repo.Repository, ctx.Repo.AccessMode)) + ctx.JSON(http.StatusOK, convert.ToRepo(ctx, ctx.Repo.Repository, ctx.Repo.AccessMode)) } func acceptOrRejectRepoTransfer(ctx *context.APIContext, accept bool) error { - repoTransfer, err := models.GetPendingRepositoryTransfer(ctx.Repo.Repository) + repoTransfer, err := models.GetPendingRepositoryTransfer(ctx, ctx.Repo.Repository) if err != nil { if models.IsErrNoPendingTransfer(err) { ctx.NotFound() @@ -217,7 +216,7 @@ func acceptOrRejectRepoTransfer(ctx *context.APIContext, accept bool) error { return err } - if err := repoTransfer.LoadAttributes(); err != nil { + if err := repoTransfer.LoadAttributes(ctx); err != nil { return err } @@ -227,7 +226,7 @@ func acceptOrRejectRepoTransfer(ctx *context.APIContext, accept bool) error { } if accept { - return repo_service.TransferOwnership(repoTransfer.Doer, repoTransfer.Recipient, ctx.Repo.Repository, repoTransfer.Teams) + return repo_service.TransferOwnership(ctx, repoTransfer.Doer, repoTransfer.Recipient, ctx.Repo.Repository, repoTransfer.Teams) } return models.CancelRepositoryTransfer(ctx.Repo.Repository) diff --git a/routers/api/v1/repo/tree.go b/routers/api/v1/repo/tree.go index b8294ebe31..9df96204cb 100644 --- a/routers/api/v1/repo/tree.go +++ b/routers/api/v1/repo/tree.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/api/v1/repo/wiki.go b/routers/api/v1/repo/wiki.go index 6d95648542..0b55a9b281 100644 --- a/routers/api/v1/repo/wiki.go +++ b/routers/api/v1/repo/wiki.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo @@ -86,7 +85,7 @@ func NewWikiPage(ctx *context.APIContext) { wikiPage := getWikiPage(ctx, wikiName) if !ctx.Written() { - notification.NotifyNewWikiPage(ctx.Doer, ctx.Repo.Repository, wikiName, form.Message) + notification.NotifyNewWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, wikiName, form.Message) ctx.JSON(http.StatusCreated, wikiPage) } } @@ -154,7 +153,7 @@ func EditWikiPage(ctx *context.APIContext) { wikiPage := getWikiPage(ctx, newWikiName) if !ctx.Written() { - notification.NotifyEditWikiPage(ctx.Doer, ctx.Repo.Repository, newWikiName, form.Message) + notification.NotifyEditWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, newWikiName, form.Message) ctx.JSON(http.StatusOK, wikiPage) } } @@ -245,7 +244,7 @@ func DeleteWikiPage(ctx *context.APIContext) { return } - notification.NotifyDeleteWikiPage(ctx.Doer, ctx.Repo.Repository, wikiName) + notification.NotifyDeleteWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, wikiName) ctx.Status(http.StatusNoContent) } diff --git a/routers/api/v1/settings/settings.go b/routers/api/v1/settings/settings.go index 36f93893a8..02bda1309d 100644 --- a/routers/api/v1/settings/settings.go +++ b/routers/api/v1/settings/settings.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package settings diff --git a/routers/api/v1/swagger/activitypub.go b/routers/api/v1/swagger/activitypub.go index afc0c05057..91341669da 100644 --- a/routers/api/v1/swagger/activitypub.go +++ b/routers/api/v1/swagger/activitypub.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package swagger diff --git a/routers/api/v1/swagger/app.go b/routers/api/v1/swagger/app.go index 9783abe1a0..6a08b11874 100644 --- a/routers/api/v1/swagger/app.go +++ b/routers/api/v1/swagger/app.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package swagger diff --git a/routers/api/v1/swagger/cron.go b/routers/api/v1/swagger/cron.go index 85f2ed0e35..00cfbe0adb 100644 --- a/routers/api/v1/swagger/cron.go +++ b/routers/api/v1/swagger/cron.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package swagger diff --git a/routers/api/v1/swagger/issue.go b/routers/api/v1/swagger/issue.go index 09e7077b20..62458a3424 100644 --- a/routers/api/v1/swagger/issue.go +++ b/routers/api/v1/swagger/issue.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package swagger diff --git a/routers/api/v1/swagger/key.go b/routers/api/v1/swagger/key.go index c3da37af63..8390833589 100644 --- a/routers/api/v1/swagger/key.go +++ b/routers/api/v1/swagger/key.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package swagger diff --git a/routers/api/v1/swagger/misc.go b/routers/api/v1/swagger/misc.go index 1d3c257efa..a4052a6a76 100644 --- a/routers/api/v1/swagger/misc.go +++ b/routers/api/v1/swagger/misc.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package swagger diff --git a/routers/api/v1/swagger/nodeinfo.go b/routers/api/v1/swagger/nodeinfo.go index c1ecf3a3f3..8650dfa092 100644 --- a/routers/api/v1/swagger/nodeinfo.go +++ b/routers/api/v1/swagger/nodeinfo.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package swagger diff --git a/routers/api/v1/swagger/notify.go b/routers/api/v1/swagger/notify.go index cd30d496e0..743d807a0a 100644 --- a/routers/api/v1/swagger/notify.go +++ b/routers/api/v1/swagger/notify.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package swagger diff --git a/routers/api/v1/swagger/options.go b/routers/api/v1/swagger/options.go index e8cfc0706f..979b184075 100644 --- a/routers/api/v1/swagger/options.go +++ b/routers/api/v1/swagger/options.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package swagger diff --git a/routers/api/v1/swagger/org.go b/routers/api/v1/swagger/org.go index d98e821ba7..0105446b00 100644 --- a/routers/api/v1/swagger/org.go +++ b/routers/api/v1/swagger/org.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package swagger diff --git a/routers/api/v1/swagger/package.go b/routers/api/v1/swagger/package.go index 2a1f057314..eada12d1ea 100644 --- a/routers/api/v1/swagger/package.go +++ b/routers/api/v1/swagger/package.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package swagger diff --git a/routers/api/v1/swagger/repo.go b/routers/api/v1/swagger/repo.go index 642b1b7b91..bd867213a6 100644 --- a/routers/api/v1/swagger/repo.go +++ b/routers/api/v1/swagger/repo.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package swagger diff --git a/routers/api/v1/swagger/settings.go b/routers/api/v1/swagger/settings.go index 4bf153cb9c..a9466699df 100644 --- a/routers/api/v1/swagger/settings.go +++ b/routers/api/v1/swagger/settings.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package swagger diff --git a/routers/api/v1/swagger/user.go b/routers/api/v1/swagger/user.go index 857bdc2a14..fb6d185ee7 100644 --- a/routers/api/v1/swagger/user.go +++ b/routers/api/v1/swagger/user.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package swagger diff --git a/routers/api/v1/user/app.go b/routers/api/v1/user/app.go index 14f1592591..6cb7b812b2 100644 --- a/routers/api/v1/user/app.go +++ b/routers/api/v1/user/app.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package user diff --git a/routers/api/v1/user/email.go b/routers/api/v1/user/email.go index 31c13172fc..84823aaed2 100644 --- a/routers/api/v1/user/email.go +++ b/routers/api/v1/user/email.go @@ -1,6 +1,5 @@ // Copyright 2015 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package user diff --git a/routers/api/v1/user/follower.go b/routers/api/v1/user/follower.go index f0109d7d6e..dd78dd528f 100644 --- a/routers/api/v1/user/follower.go +++ b/routers/api/v1/user/follower.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package user @@ -220,7 +219,7 @@ func Follow(ctx *context.APIContext) { // "204": // "$ref": "#/responses/empty" - if err := user_service.FollowUser(ctx.Doer.ID, ctx.ContextUser.ID); err != nil { + if err := user_service.FollowUser(ctx, ctx.Doer.ID, ctx.ContextUser.ID); err != nil { ctx.Error(http.StatusInternalServerError, "FollowUser", err) return } @@ -242,7 +241,7 @@ func Unfollow(ctx *context.APIContext) { // "204": // "$ref": "#/responses/empty" - if err := user_service.UnfollowUser(ctx.Doer.ID, ctx.ContextUser.ID); err != nil { + if err := user_service.UnfollowUser(ctx, ctx.Doer.ID, ctx.ContextUser.ID); err != nil { ctx.Error(http.StatusInternalServerError, "UnfollowUser", err) return } diff --git a/routers/api/v1/user/gpg_key.go b/routers/api/v1/user/gpg_key.go index b87cf0041e..7c91d2ac65 100644 --- a/routers/api/v1/user/gpg_key.go +++ b/routers/api/v1/user/gpg_key.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package user diff --git a/routers/api/v1/user/helper.go b/routers/api/v1/user/helper.go index ae7fa5248e..28f600ad92 100644 --- a/routers/api/v1/user/helper.go +++ b/routers/api/v1/user/helper.go @@ -1,6 +1,5 @@ // Copyright 2021 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package user diff --git a/routers/api/v1/user/key.go b/routers/api/v1/user/key.go index 71a2c910a6..25bda0444a 100644 --- a/routers/api/v1/user/key.go +++ b/routers/api/v1/user/key.go @@ -1,6 +1,5 @@ // Copyright 2015 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package user @@ -8,6 +7,7 @@ import ( "net/http" asymkey_model "code.gitea.io/gitea/models/asymkey" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/perm" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/context" @@ -30,7 +30,7 @@ func appendPrivateInformation(apiKey *api.PublicKey, key *asymkey_model.PublicKe if defaultUser.ID == key.OwnerID { apiKey.Owner = convert.ToUser(defaultUser, defaultUser) } else { - user, err := user_model.GetUserByID(key.OwnerID) + user, err := user_model.GetUserByID(db.DefaultContext, key.OwnerID) if err != nil { return apiKey, err } diff --git a/routers/api/v1/user/repo.go b/routers/api/v1/user/repo.go index 709e3a6c54..e79a9d8f8b 100644 --- a/routers/api/v1/user/repo.go +++ b/routers/api/v1/user/repo.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package user @@ -39,13 +38,13 @@ func listUserRepos(ctx *context.APIContext, u *user_model.User, private bool) { apiRepos := make([]*api.Repository, 0, len(repos)) for i := range repos { - access, err := access_model.AccessLevel(ctx.Doer, repos[i]) + access, err := access_model.AccessLevel(ctx, ctx.Doer, repos[i]) if err != nil { ctx.Error(http.StatusInternalServerError, "AccessLevel", err) return } if ctx.IsSigned && ctx.Doer.IsAdmin || access >= perm.AccessModeRead { - apiRepos = append(apiRepos, convert.ToRepo(repos[i], access)) + apiRepos = append(apiRepos, convert.ToRepo(ctx, repos[i], access)) } } @@ -112,7 +111,7 @@ func ListMyRepos(ctx *context.APIContext) { } var err error - repos, count, err := repo_model.SearchRepository(opts) + repos, count, err := repo_model.SearchRepository(ctx, opts) if err != nil { ctx.Error(http.StatusInternalServerError, "SearchRepository", err) return @@ -124,11 +123,11 @@ func ListMyRepos(ctx *context.APIContext) { ctx.Error(http.StatusInternalServerError, "GetOwner", err) return } - accessMode, err := access_model.AccessLevel(ctx.Doer, repo) + accessMode, err := access_model.AccessLevel(ctx, ctx.Doer, repo) if err != nil { ctx.Error(http.StatusInternalServerError, "AccessLevel", err) } - results[i] = convert.ToRepo(repo, accessMode) + results[i] = convert.ToRepo(ctx, repo, accessMode) } ctx.SetLinkHeader(int(count), opts.ListOptions.PageSize) diff --git a/routers/api/v1/user/settings.go b/routers/api/v1/user/settings.go index f00bf8c268..89bfd83efc 100644 --- a/routers/api/v1/user/settings.go +++ b/routers/api/v1/user/settings.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package user diff --git a/routers/api/v1/user/star.go b/routers/api/v1/user/star.go index 9cb9ec79b8..0475489640 100644 --- a/routers/api/v1/user/star.go +++ b/routers/api/v1/user/star.go @@ -1,11 +1,11 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package user import ( + std_context "context" "net/http" "code.gitea.io/gitea/models/db" @@ -20,19 +20,19 @@ import ( // getStarredRepos returns the repos that the user with the specified userID has // starred -func getStarredRepos(user *user_model.User, private bool, listOptions db.ListOptions) ([]*api.Repository, error) { - starredRepos, err := repo_model.GetStarredRepos(user.ID, private, listOptions) +func getStarredRepos(ctx std_context.Context, user *user_model.User, private bool, listOptions db.ListOptions) ([]*api.Repository, error) { + starredRepos, err := repo_model.GetStarredRepos(ctx, user.ID, private, listOptions) if err != nil { return nil, err } repos := make([]*api.Repository, len(starredRepos)) for i, starred := range starredRepos { - access, err := access_model.AccessLevel(user, starred) + access, err := access_model.AccessLevel(ctx, user, starred) if err != nil { return nil, err } - repos[i] = convert.ToRepo(starred, access) + repos[i] = convert.ToRepo(ctx, starred, access) } return repos, nil } @@ -63,7 +63,7 @@ func GetStarredRepos(ctx *context.APIContext) { // "$ref": "#/responses/RepositoryList" private := ctx.ContextUser.ID == ctx.Doer.ID - repos, err := getStarredRepos(ctx.ContextUser, private, utils.GetListOptions(ctx)) + repos, err := getStarredRepos(ctx, ctx.ContextUser, private, utils.GetListOptions(ctx)) if err != nil { ctx.Error(http.StatusInternalServerError, "getStarredRepos", err) return @@ -93,7 +93,7 @@ func GetMyStarredRepos(ctx *context.APIContext) { // "200": // "$ref": "#/responses/RepositoryList" - repos, err := getStarredRepos(ctx.Doer, true, utils.GetListOptions(ctx)) + repos, err := getStarredRepos(ctx, ctx.Doer, true, utils.GetListOptions(ctx)) if err != nil { ctx.Error(http.StatusInternalServerError, "getStarredRepos", err) } diff --git a/routers/api/v1/user/user.go b/routers/api/v1/user/user.go index 69197aef23..8a21c2c7ca 100644 --- a/routers/api/v1/user/user.go +++ b/routers/api/v1/user/user.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package user diff --git a/routers/api/v1/user/watch.go b/routers/api/v1/user/watch.go index 83f23db15c..707e5da090 100644 --- a/routers/api/v1/user/watch.go +++ b/routers/api/v1/user/watch.go @@ -1,10 +1,10 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package user import ( + std_context "context" "net/http" "code.gitea.io/gitea/models/db" @@ -18,19 +18,19 @@ import ( ) // getWatchedRepos returns the repos that the user with the specified userID is watching -func getWatchedRepos(user *user_model.User, private bool, listOptions db.ListOptions) ([]*api.Repository, int64, error) { - watchedRepos, total, err := repo_model.GetWatchedRepos(user.ID, private, listOptions) +func getWatchedRepos(ctx std_context.Context, user *user_model.User, private bool, listOptions db.ListOptions) ([]*api.Repository, int64, error) { + watchedRepos, total, err := repo_model.GetWatchedRepos(ctx, user.ID, private, listOptions) if err != nil { return nil, 0, err } repos := make([]*api.Repository, len(watchedRepos)) for i, watched := range watchedRepos { - access, err := access_model.AccessLevel(user, watched) + access, err := access_model.AccessLevel(ctx, user, watched) if err != nil { return nil, 0, err } - repos[i] = convert.ToRepo(watched, access) + repos[i] = convert.ToRepo(ctx, watched, access) } return repos, total, nil } @@ -61,7 +61,7 @@ func GetWatchedRepos(ctx *context.APIContext) { // "$ref": "#/responses/RepositoryList" private := ctx.ContextUser.ID == ctx.Doer.ID - repos, total, err := getWatchedRepos(ctx.ContextUser, private, utils.GetListOptions(ctx)) + repos, total, err := getWatchedRepos(ctx, ctx.ContextUser, private, utils.GetListOptions(ctx)) if err != nil { ctx.Error(http.StatusInternalServerError, "getWatchedRepos", err) } @@ -90,7 +90,7 @@ func GetMyWatchedRepos(ctx *context.APIContext) { // "200": // "$ref": "#/responses/RepositoryList" - repos, total, err := getWatchedRepos(ctx.Doer, true, utils.GetListOptions(ctx)) + repos, total, err := getWatchedRepos(ctx, ctx.Doer, true, utils.GetListOptions(ctx)) if err != nil { ctx.Error(http.StatusInternalServerError, "getWatchedRepos", err) } diff --git a/routers/api/v1/utils/git.go b/routers/api/v1/utils/git.go index 816f8b3595..2801dee8ba 100644 --- a/routers/api/v1/utils/git.go +++ b/routers/api/v1/utils/git.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package utils diff --git a/routers/api/v1/utils/hook.go b/routers/api/v1/utils/hook.go index aa922f4f5b..7faf609ae8 100644 --- a/routers/api/v1/utils/hook.go +++ b/routers/api/v1/utils/hook.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package utils diff --git a/routers/api/v1/utils/page.go b/routers/api/v1/utils/page.go index 608bec7395..ef5806fa92 100644 --- a/routers/api/v1/utils/page.go +++ b/routers/api/v1/utils/page.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package utils diff --git a/routers/common/db.go b/routers/common/db.go index 99d66f93e8..2e86fbd0fd 100644 --- a/routers/common/db.go +++ b/routers/common/db.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package common @@ -13,6 +12,8 @@ import ( "code.gitea.io/gitea/models/migrations" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" + + "xorm.io/xorm" ) // InitDBEngine In case of problems connecting to DB, retry connection. Eg, PGSQL in Docker Container on Synology @@ -25,7 +26,7 @@ func InitDBEngine(ctx context.Context) (err error) { default: } log.Info("ORM engine initialization attempt #%d/%d...", i+1, setting.Database.DBConnectRetries) - if err = db.InitEngineWithMigration(ctx, migrations.Migrate); err == nil { + if err = db.InitEngineWithMigration(ctx, migrateWithSetting); err == nil { break } else if i == setting.Database.DBConnectRetries-1 { return err @@ -37,3 +38,20 @@ func InitDBEngine(ctx context.Context) (err error) { db.HasEngine = true return nil } + +func migrateWithSetting(x *xorm.Engine) error { + if setting.Database.AutoMigration { + return migrations.Migrate(x) + } + + if current, err := migrations.GetCurrentDBVersion(x); err != nil { + return err + } else if current < 0 { + // execute migrations when the database isn't initialized even if AutoMigration is false + return migrations.Migrate(x) + } else if expected := migrations.ExpectedVersion(); current != expected { + log.Fatal(`"database.AUTO_MIGRATION" is disabled, but current database version %d is not equal to the expected version %d.`+ + `You can set "database.AUTO_MIGRATION" to true or migrate manually by running "gitea [--config /path/to/app.ini] migrate"`, current, expected) + } + return nil +} diff --git a/routers/common/middleware.go b/routers/common/middleware.go index 6ea1e1dfbe..0c7838b0ef 100644 --- a/routers/common/middleware.go +++ b/routers/common/middleware.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package common diff --git a/routers/common/repo.go b/routers/common/repo.go index a9e80fad48..4b04ddae34 100644 --- a/routers/common/repo.go +++ b/routers/common/repo.go @@ -1,13 +1,10 @@ // 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. +// SPDX-License-Identifier: MIT package common import ( - "fmt" "io" - "net/url" "path" "path/filepath" "strings" @@ -53,50 +50,44 @@ func ServeData(ctx *context.Context, filePath string, size int64, reader io.Read buf = buf[:n] } - httpcache.AddCacheControlToHeader(ctx.Resp.Header(), 5*time.Minute) + opts := &context.ServeHeaderOptions{ + Filename: path.Base(filePath), + } if size >= 0 { - ctx.Resp.Header().Set("Content-Length", fmt.Sprintf("%d", size)) + opts.ContentLength = &size } else { log.Error("ServeData called to serve data: %s with size < 0: %d", filePath, size) } - fileName := path.Base(filePath) sniffedType := typesniffer.DetectContentType(buf) isPlain := sniffedType.IsText() || ctx.FormBool("render") - mimeType := "" - charset := "" if setting.MimeTypeMap.Enabled { - fileExtension := strings.ToLower(filepath.Ext(fileName)) - mimeType = setting.MimeTypeMap.Map[fileExtension] + fileExtension := strings.ToLower(filepath.Ext(filePath)) + opts.ContentType = setting.MimeTypeMap.Map[fileExtension] } - if mimeType == "" { + if opts.ContentType == "" { if sniffedType.IsBrowsableBinaryType() { - mimeType = sniffedType.GetMimeType() + opts.ContentType = sniffedType.GetMimeType() } else if isPlain { - mimeType = "text/plain" + opts.ContentType = "text/plain" } else { - mimeType = typesniffer.ApplicationOctetStream + opts.ContentType = typesniffer.ApplicationOctetStream } } if isPlain { + var charset string charset, err = charsetModule.DetectEncoding(buf) if err != nil { log.Error("Detect raw file %s charset failed: %v, using by default utf-8", filePath, err) charset = "utf-8" } + opts.ContentTypeCharset = strings.ToLower(charset) } - if charset != "" { - ctx.Resp.Header().Set("Content-Type", mimeType+"; charset="+strings.ToLower(charset)) - } else { - ctx.Resp.Header().Set("Content-Type", mimeType) - } - ctx.Resp.Header().Set("X-Content-Type-Options", "nosniff") - isSVG := sniffedType.IsSvgImage() // serve types that can present a security risk with CSP @@ -109,16 +100,12 @@ func ServeData(ctx *context.Context, filePath string, size int64, reader io.Read ctx.Resp.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'") } - disposition := "inline" + opts.Disposition = "inline" if isSVG && !setting.UI.SVG.Enabled { - disposition = "attachment" + opts.Disposition = "attachment" } - // encode filename per https://datatracker.ietf.org/doc/html/rfc5987 - encodedFileName := `filename*=UTF-8''` + url.PathEscape(fileName) - - ctx.Resp.Header().Set("Content-Disposition", disposition+"; "+encodedFileName) - ctx.Resp.Header().Set("Access-Control-Expose-Headers", "Content-Disposition") + ctx.SetServeHeaders(opts) _, err = ctx.Resp.Write(buf) if err != nil { diff --git a/routers/init.go b/routers/init.go index 53b33f468f..670191debc 100644 --- a/routers/init.go +++ b/routers/init.go @@ -1,6 +1,5 @@ // Copyright 2016 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. +// SPDX-License-Identifier: MIT package routers @@ -185,8 +184,14 @@ func NormalRoutes(ctx context.Context) *web.Route { r.Mount("/", web_routers.Routes(ctx)) r.Mount("/api/v1", apiv1.Routes(ctx)) r.Mount("/api/internal", private.Routes()) + if setting.Packages.Enabled { - r.Mount("/api/packages", packages_router.Routes(ctx)) + // Add endpoints to match common package manager APIs + + // This implements package support for most package managers + r.Mount("/api/packages", packages_router.CommonRoutes(ctx)) + + // This implements the OCI API (Note this is not preceded by /api but is instead /v2) r.Mount("/v2", packages_router.ContainerRoutes(ctx)) } return r diff --git a/routers/install/install.go b/routers/install/install.go index 184dc5bae1..ab37f9ba35 100644 --- a/routers/install/install.go +++ b/routers/install/install.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // 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. +// SPDX-License-Identifier: MIT package install diff --git a/routers/install/routes.go b/routers/install/routes.go index 7617477827..9aa5a88d24 100644 --- a/routers/install/routes.go +++ b/routers/install/routes.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package install diff --git a/routers/install/routes_test.go b/routers/install/routes_test.go index e69d2d15df..35b5e5e916 100644 --- a/routers/install/routes_test.go +++ b/routers/install/routes_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package install diff --git a/routers/install/setting.go b/routers/install/setting.go index c4912f1124..b76219f45d 100644 --- a/routers/install/setting.go +++ b/routers/install/setting.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package install diff --git a/routers/private/default_branch.go b/routers/private/default_branch.go index 55ffef43f3..268ebbe443 100644 --- a/routers/private/default_branch.go +++ b/routers/private/default_branch.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT // Package private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead. package private diff --git a/routers/private/hook_post_receive.go b/routers/private/hook_post_receive.go index 93aa450f9c..c62038899d 100644 --- a/routers/private/hook_post_receive.go +++ b/routers/private/hook_post_receive.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT // Package private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead. package private @@ -184,7 +183,7 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) { baseRepo = repo if repo.IsFork { - if err := repo.GetBaseRepo(); err != nil { + if err := repo.GetBaseRepo(ctx); err != nil { log.Error("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err) ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{ Err: fmt.Sprintf("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err), @@ -202,7 +201,7 @@ func HookPostReceive(ctx *gitea_context.PrivateContext) { continue } - pr, err := issues_model.GetUnmergedPullRequest(repo.ID, baseRepo.ID, branch, baseRepo.DefaultBranch, issues_model.PullRequestFlowGithub) + pr, err := issues_model.GetUnmergedPullRequest(ctx, repo.ID, baseRepo.ID, branch, baseRepo.DefaultBranch, issues_model.PullRequestFlowGithub) if err != nil && !issues_model.IsErrPullRequestNotExist(err) { log.Error("Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err) ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{ diff --git a/routers/private/hook_pre_receive.go b/routers/private/hook_pre_receive.go index fdd0a0bc3a..e49ae68a64 100644 --- a/routers/private/hook_pre_receive.go +++ b/routers/private/hook_pre_receive.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT // Package private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead. package private @@ -372,7 +371,7 @@ func preReceiveTag(ctx *preReceiveContext, oldCommitID, newCommitID, refFullName if !ctx.gotProtectedTags { var err error - ctx.protectedTags, err = git_model.GetProtectedTags(ctx.Repo.Repository.ID) + ctx.protectedTags, err = git_model.GetProtectedTags(ctx, ctx.Repo.Repository.ID) if err != nil { log.Error("Unable to get protected tags for %-v Error: %v", ctx.Repo.Repository, err) ctx.JSON(http.StatusInternalServerError, private.Response{ @@ -383,7 +382,7 @@ func preReceiveTag(ctx *preReceiveContext, oldCommitID, newCommitID, refFullName ctx.gotProtectedTags = true } - isAllowed, err := git_model.IsUserAllowedToControlTag(ctx.protectedTags, tagName, ctx.opts.UserID) + isAllowed, err := git_model.IsUserAllowedToControlTag(ctx, ctx.protectedTags, tagName, ctx.opts.UserID) if err != nil { ctx.JSON(http.StatusInternalServerError, private.Response{ Err: err.Error(), @@ -465,7 +464,7 @@ func (ctx *preReceiveContext) loadPusherAndPermission() bool { return true } - user, err := user_model.GetUserByID(ctx.opts.UserID) + user, err := user_model.GetUserByID(ctx, ctx.opts.UserID) if err != nil { log.Error("Unable to get User id %d Error: %v", ctx.opts.UserID, err) ctx.JSON(http.StatusInternalServerError, private.Response{ diff --git a/routers/private/hook_proc_receive.go b/routers/private/hook_proc_receive.go index 0653f8b0d2..05921e6f58 100644 --- a/routers/private/hook_proc_receive.go +++ b/routers/private/hook_proc_receive.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT // Package private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead. package private diff --git a/routers/private/hook_verification.go b/routers/private/hook_verification.go index 8a2d1cf33d..7b9550dfdd 100644 --- a/routers/private/hook_verification.go +++ b/routers/private/hook_verification.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT // Package private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead. package private diff --git a/routers/private/internal.go b/routers/private/internal.go index f8e451e80f..306e4ffb00 100644 --- a/routers/private/internal.go +++ b/routers/private/internal.go @@ -1,13 +1,11 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT // Package private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead. package private import ( "net/http" - "reflect" "strings" "code.gitea.io/gitea/modules/context" @@ -40,13 +38,9 @@ func CheckInternalToken(next http.Handler) http.Handler { } // bind binding an obj to a handler -func bind(obj interface{}) http.HandlerFunc { - tp := reflect.TypeOf(obj) - for tp.Kind() == reflect.Ptr { - tp = tp.Elem() - } +func bind[T any](obj T) http.HandlerFunc { return web.Wrap(func(ctx *context.PrivateContext) { - theObj := reflect.New(tp).Interface() // create a new form obj for every request but not use obj directly + theObj := new(T) // create a new form obj for every request but not use obj directly binding.Bind(ctx.Req, theObj) web.SetForm(ctx, theObj) }) diff --git a/routers/private/internal_repo.go b/routers/private/internal_repo.go index c50d2a01a7..bd8db0a185 100644 --- a/routers/private/internal_repo.go +++ b/routers/private/internal_repo.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT // Package private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead. package private @@ -69,7 +68,7 @@ func RepoAssignment(ctx *gitea_context.PrivateContext) context.CancelFunc { } func loadRepository(ctx *gitea_context.PrivateContext, ownerName, repoName string) *repo_model.Repository { - repo, err := repo_model.GetRepositoryByOwnerAndName(ownerName, repoName) + repo, err := repo_model.GetRepositoryByOwnerAndName(ctx, ownerName, repoName) if err != nil { log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err) ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ diff --git a/routers/private/key.go b/routers/private/key.go index 9977492c63..b536019dd7 100644 --- a/routers/private/key.go +++ b/routers/private/key.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT // Package private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead. package private diff --git a/routers/private/mail.go b/routers/private/mail.go index 255e1d901d..622a01dd8f 100644 --- a/routers/private/mail.go +++ b/routers/private/mail.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package private diff --git a/routers/private/manager.go b/routers/private/manager.go index e7f08ac455..f15da298d6 100644 --- a/routers/private/manager.go +++ b/routers/private/manager.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package private diff --git a/routers/private/manager_process.go b/routers/private/manager_process.go index e12bbee18b..a5993bf371 100644 --- a/routers/private/manager_process.go +++ b/routers/private/manager_process.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package private diff --git a/routers/private/manager_unix.go b/routers/private/manager_unix.go index 43cbdec01c..09ced33b8d 100644 --- a/routers/private/manager_unix.go +++ b/routers/private/manager_unix.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build !windows diff --git a/routers/private/manager_windows.go b/routers/private/manager_windows.go index 2b72ee952d..b5382c7d91 100644 --- a/routers/private/manager_windows.go +++ b/routers/private/manager_windows.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT //go:build windows diff --git a/routers/private/restore_repo.go b/routers/private/restore_repo.go index 34e06e51c2..97ac9a3c5a 100644 --- a/routers/private/restore_repo.go +++ b/routers/private/restore_repo.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package private diff --git a/routers/private/serv.go b/routers/private/serv.go index ddb2e6aa8b..17f966e3e4 100644 --- a/routers/private/serv.go +++ b/routers/private/serv.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT // Package private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead. package private @@ -52,7 +51,7 @@ func ServNoCommand(ctx *context.PrivateContext) { results.Key = key if key.Type == asymkey_model.KeyTypeUser || key.Type == asymkey_model.KeyTypePrincipal { - user, err := user_model.GetUserByID(key.OwnerID) + user, err := user_model.GetUserByID(ctx, key.OwnerID) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.JSON(http.StatusUnauthorized, private.Response{ @@ -260,7 +259,7 @@ func ServCommand(ctx *context.PrivateContext) { } else { // Get the user represented by the Key var err error - user, err = user_model.GetUserByID(key.OwnerID) + user, err = user_model.GetUserByID(ctx, key.OwnerID) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.JSON(http.StatusUnauthorized, private.ErrServCommand{ @@ -383,7 +382,7 @@ func ServCommand(ctx *context.PrivateContext) { if results.IsWiki { // Ensure the wiki is enabled before we allow access to it - if _, err := repo.GetUnit(unit.TypeWiki); err != nil { + if _, err := repo.GetUnit(ctx, unit.TypeWiki); err != nil { if repo_model.IsErrUnitTypeNotExist(err) { ctx.JSON(http.StatusForbidden, private.ErrServCommand{ Results: results, diff --git a/routers/private/ssh_log.go b/routers/private/ssh_log.go index 2f1793a0e0..54604ad554 100644 --- a/routers/private/ssh_log.go +++ b/routers/private/ssh_log.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package private diff --git a/routers/utils/utils.go b/routers/utils/utils.go index 66eaa1d9ce..d6856fceac 100644 --- a/routers/utils/utils.go +++ b/routers/utils/utils.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package utils diff --git a/routers/utils/utils_test.go b/routers/utils/utils_test.go index 42cf948e30..6d19214c88 100644 --- a/routers/utils/utils_test.go +++ b/routers/utils/utils_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package utils diff --git a/routers/web/admin/admin.go b/routers/web/admin/admin.go index d0664eb780..0a51000c70 100644 --- a/routers/web/admin/admin.go +++ b/routers/web/admin/admin.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/web/admin/admin_test.go b/routers/web/admin/admin_test.go index 1bc43998b2..2b65ab3ea3 100644 --- a/routers/web/admin/admin_test.go +++ b/routers/web/admin/admin_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/web/admin/applications.go b/routers/web/admin/applications.go index c7a9c3100f..745d17ff2a 100644 --- a/routers/web/admin/applications.go +++ b/routers/web/admin/applications.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/web/admin/auths.go b/routers/web/admin/auths.go index b79b317555..1bc166902c 100644 --- a/routers/web/admin/auths.go +++ b/routers/web/admin/auths.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package admin @@ -159,7 +158,7 @@ func parseLDAPConfig(form forms.AuthenticationForm) *ldap.Source { func parseSMTPConfig(form forms.AuthenticationForm) *smtp.Source { return &smtp.Source{ Auth: form.SMTPAuth, - Addr: form.SMTPAddr, + Host: form.SMTPHost, Port: form.SMTPPort, AllowedDomains: form.AllowedDomains, ForceSMTPS: form.ForceSMTPS, diff --git a/routers/web/admin/config.go b/routers/web/admin/config.go index 614d3d4f66..eaa02588ca 100644 --- a/routers/web/admin/config.go +++ b/routers/web/admin/config.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package admin @@ -18,7 +17,6 @@ import ( "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" - system_module "code.gitea.io/gitea/modules/system" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/services/mailer" @@ -203,7 +201,11 @@ func ChangeConfig(ctx *context.Context) { value := ctx.FormString("value") version := ctx.FormInt("version") - if err := system_module.SetSetting(key, value, version); err != nil { + if err := system_model.SetSetting(&system_model.Setting{ + SettingKey: key, + SettingValue: value, + Version: version, + }); err != nil { log.Error("set setting failed: %v", err) ctx.JSON(http.StatusOK, map[string]string{ "err": ctx.Tr("admin.config.set_setting_failed", key), diff --git a/routers/web/admin/emails.go b/routers/web/admin/emails.go index 9482ae0123..c16158c6ae 100644 --- a/routers/web/admin/emails.go +++ b/routers/web/admin/emails.go @@ -1,6 +1,5 @@ // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/web/admin/hooks.go b/routers/web/admin/hooks.go index bf71cb5595..e8db9a3ded 100644 --- a/routers/web/admin/hooks.go +++ b/routers/web/admin/hooks.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/web/admin/main_test.go b/routers/web/admin/main_test.go index 4e6ad4d743..ea79830fa1 100644 --- a/routers/web/admin/main_test.go +++ b/routers/web/admin/main_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/web/admin/notice.go b/routers/web/admin/notice.go index f5ec294cc3..f60cf90b3c 100644 --- a/routers/web/admin/notice.go +++ b/routers/web/admin/notice.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/web/admin/orgs.go b/routers/web/admin/orgs.go index 6081ab9b1c..a4eb0af58d 100644 --- a/routers/web/admin/orgs.go +++ b/routers/web/admin/orgs.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/web/admin/packages.go b/routers/web/admin/packages.go index 5de8922e6f..80cec51275 100644 --- a/routers/web/admin/packages.go +++ b/routers/web/admin/packages.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/web/admin/repos.go b/routers/web/admin/repos.go index 17b00975ec..dc5432c549 100644 --- a/routers/web/admin/repos.go +++ b/routers/web/admin/repos.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package admin @@ -42,7 +41,7 @@ func Repos(ctx *context.Context) { // DeleteRepo delete one repository func DeleteRepo(ctx *context.Context) { - repo, err := repo_model.GetRepositoryByID(ctx.FormInt64("id")) + repo, err := repo_model.GetRepositoryByID(ctx, ctx.FormInt64("id")) if err != nil { ctx.ServerError("GetRepositoryByID", err) return diff --git a/routers/web/admin/users.go b/routers/web/admin/users.go index 5cdfb8142e..38969dadaa 100644 --- a/routers/web/admin/users.go +++ b/routers/web/admin/users.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package admin @@ -207,7 +206,7 @@ func NewUserPost(ctx *context.Context) { } func prepareUserInfo(ctx *context.Context) *user_model.User { - u, err := user_model.GetUserByID(ctx.ParamsInt64(":userid")) + u, err := user_model.GetUserByID(ctx, ctx.ParamsInt64(":userid")) if err != nil { if user_model.IsErrUserNotExist(err) { ctx.Redirect(setting.AppSubURL + "/admin/users") @@ -414,7 +413,7 @@ func EditUserPost(ctx *context.Context) { // DeleteUser response for deleting a user func DeleteUser(ctx *context.Context) { - u, err := user_model.GetUserByID(ctx.ParamsInt64(":userid")) + u, err := user_model.GetUserByID(ctx, ctx.ParamsInt64(":userid")) if err != nil { ctx.ServerError("GetUserByID", err) return diff --git a/routers/web/admin/users_test.go b/routers/web/admin/users_test.go index da67cd5cb4..ed58a54eef 100644 --- a/routers/web/admin/users_test.go +++ b/routers/web/admin/users_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package admin diff --git a/routers/web/auth.go b/routers/web/auth.go index a771643b66..1ca860ecc8 100644 --- a/routers/web/auth.go +++ b/routers/web/auth.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT //go:build !windows diff --git a/routers/web/auth/2fa.go b/routers/web/auth/2fa.go index c61922cd9d..4791b04313 100644 --- a/routers/web/auth/2fa.go +++ b/routers/web/auth/2fa.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package auth @@ -69,7 +68,7 @@ func TwoFactorPost(ctx *context.Context) { if ok && twofa.LastUsedPasscode != form.Passcode { remember := ctx.Session.Get("twofaRemember").(bool) - u, err := user_model.GetUserByID(id) + u, err := user_model.GetUserByID(ctx, id) if err != nil { ctx.ServerError("UserSignIn", err) return @@ -147,7 +146,7 @@ func TwoFactorScratchPost(ctx *context.Context) { } remember := ctx.Session.Get("twofaRemember").(bool) - u, err := user_model.GetUserByID(id) + u, err := user_model.GetUserByID(ctx, id) if err != nil { ctx.ServerError("UserSignIn", err) return diff --git a/routers/web/auth/auth.go b/routers/web/auth/auth.go index 25d70d7c47..71a62bce65 100644 --- a/routers/web/auth/auth.go +++ b/routers/web/auth/auth.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package auth @@ -17,11 +16,8 @@ import ( "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/eventsource" - "code.gitea.io/gitea/modules/hcaptcha" "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/mcaptcha" "code.gitea.io/gitea/modules/password" - "code.gitea.io/gitea/modules/recaptcha" "code.gitea.io/gitea/modules/session" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/timeutil" @@ -82,19 +78,12 @@ func AutoSignIn(ctx *context.Context) (bool, error) { isSucceed = true - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { - return false, fmt.Errorf("unable to RegenerateSession: Error: %w", err) - } - - // Set session IDs - if err := ctx.Session.Set("uid", u.ID); err != nil { - return false, err - } - if err := ctx.Session.Set("uname", u.Name); err != nil { - return false, err - } - if err := ctx.Session.Release(); err != nil { - return false, err + if err := updateSession(ctx, nil, map[string]interface{}{ + // Set session IDs + "uid": u.ID, + "uname": u.Name, + }); err != nil { + return false, fmt.Errorf("unable to updateSession: %w", err) } if err := resetLocale(ctx, u); err != nil { @@ -170,6 +159,10 @@ func SignIn(ctx *context.Context) { ctx.Data["PageIsLogin"] = true ctx.Data["EnableSSPI"] = auth.IsSSPIEnabled() + if setting.Service.EnableCaptcha && setting.Service.RequireCaptchaForLogin { + context.SetCaptchaData(ctx) + } + ctx.HTML(http.StatusOK, tplSignIn) } @@ -196,6 +189,16 @@ func SignInPost(ctx *context.Context) { } form := web.GetForm(ctx).(*forms.SignInForm) + + if setting.Service.EnableCaptcha && setting.Service.RequireCaptchaForLogin { + context.SetCaptchaData(ctx) + + context.VerifyCaptcha(ctx, tplSignIn, form) + if ctx.Written() { + return + } + } + u, source, err := auth_service.UserSignIn(form.UserName, form.Password) if err != nil { if user_model.IsErrUserNotExist(err) || user_model.IsErrEmailAddressNotExist(err) { @@ -252,32 +255,17 @@ func SignInPost(ctx *context.Context) { return } - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { - ctx.ServerError("UserSignIn: Unable to set regenerate session", err) - return + updates := map[string]interface{}{ + // User will need to use 2FA TOTP or WebAuthn, save data + "twofaUid": u.ID, + "twofaRemember": form.Remember, } - - // User will need to use 2FA TOTP or WebAuthn, save data - if err := ctx.Session.Set("twofaUid", u.ID); err != nil { - ctx.ServerError("UserSignIn: Unable to set twofaUid in session", err) - return - } - - if err := ctx.Session.Set("twofaRemember", form.Remember); err != nil { - ctx.ServerError("UserSignIn: Unable to set twofaRemember in session", err) - return - } - if hasTOTPtwofa { // User will need to use WebAuthn, save data - if err := ctx.Session.Set("totpEnrolled", u.ID); err != nil { - ctx.ServerError("UserSignIn: Unable to set WebAuthn Enrolled in session", err) - return - } + updates["totpEnrolled"] = u.ID } - - if err := ctx.Session.Release(); err != nil { - ctx.ServerError("UserSignIn: Unable to save session", err) + if err := updateSession(ctx, nil, updates); err != nil { + ctx.ServerError("UserSignIn: Unable to update session", err) return } @@ -308,29 +296,23 @@ func handleSignInFull(ctx *context.Context, u *user_model.User, remember, obeyRe setting.CookieRememberName, u.Name, days) } - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { + if err := updateSession(ctx, []string{ + // Delete the openid, 2fa and linkaccount data + "openid_verified_uri", + "openid_signin_remember", + "openid_determined_email", + "openid_determined_username", + "twofaUid", + "twofaRemember", + "linkAccount", + }, map[string]interface{}{ + "uid": u.ID, + "uname": u.Name, + }); err != nil { ctx.ServerError("RegenerateSession", err) return setting.AppSubURL + "/" } - // Delete the openid, 2fa and linkaccount data - _ = ctx.Session.Delete("openid_verified_uri") - _ = ctx.Session.Delete("openid_signin_remember") - _ = ctx.Session.Delete("openid_determined_email") - _ = ctx.Session.Delete("openid_determined_username") - _ = ctx.Session.Delete("twofaUid") - _ = ctx.Session.Delete("twofaRemember") - _ = ctx.Session.Delete("linkAccount") - if err := ctx.Session.Set("uid", u.ID); err != nil { - log.Error("Error setting uid %d in session: %v", u.ID, err) - } - if err := ctx.Session.Set("uname", u.Name); err != nil { - log.Error("Error setting uname %s session: %v", u.Name, err) - } - if err := ctx.Session.Release(); err != nil { - log.Error("Unable to store session: %v", err) - } - // Language setting of the user overwrites the one previously set // If the user does not have a locale set, we save the current one. if len(u.Language) == 0 { @@ -411,14 +393,7 @@ func SignUp(ctx *context.Context) { ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up" - ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha - ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL - ctx.Data["Captcha"] = context.GetImageCaptcha() - ctx.Data["CaptchaType"] = setting.Service.CaptchaType - ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey - ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey - ctx.Data["McaptchaSitekey"] = setting.Service.McaptchaSitekey - ctx.Data["McaptchaURL"] = setting.Service.McaptchaURL + context.SetCaptchaData(ctx) ctx.Data["PageIsSignUp"] = true // Show Disabled Registration message if DisableRegistration or AllowOnlyExternalRegistration options are true @@ -434,14 +409,7 @@ func SignUpPost(ctx *context.Context) { ctx.Data["SignUpLink"] = setting.AppSubURL + "/user/sign_up" - ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha - ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL - ctx.Data["Captcha"] = context.GetImageCaptcha() - ctx.Data["CaptchaType"] = setting.Service.CaptchaType - ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey - ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey - ctx.Data["McaptchaSitekey"] = setting.Service.McaptchaSitekey - ctx.Data["McaptchaURL"] = setting.Service.McaptchaURL + context.SetCaptchaData(ctx) ctx.Data["PageIsSignUp"] = true // Permission denied if DisableRegistration or AllowOnlyExternalRegistration options are true @@ -455,31 +423,9 @@ func SignUpPost(ctx *context.Context) { return } - if setting.Service.EnableCaptcha { - var valid bool - var err error - switch setting.Service.CaptchaType { - case setting.ImageCaptcha: - valid = context.GetImageCaptcha().VerifyReq(ctx.Req) - case setting.ReCaptcha: - valid, err = recaptcha.Verify(ctx, form.GRecaptchaResponse) - case setting.HCaptcha: - valid, err = hcaptcha.Verify(ctx, form.HcaptchaResponse) - case setting.MCaptcha: - valid, err = mcaptcha.Verify(ctx, form.McaptchaResponse) - default: - ctx.ServerError("Unknown Captcha Type", fmt.Errorf("Unknown Captcha Type: %s", setting.Service.CaptchaType)) - return - } - if err != nil { - log.Debug("%s", err.Error()) - } - - if !valid { - ctx.Data["Err_Captcha"] = true - ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUp, &form) - return - } + context.VerifyCaptcha(ctx, tplSignUp, form) + if ctx.Written() { + return } if !form.IsEmailDomainAllowed() { @@ -762,27 +708,27 @@ func handleAccountActivation(ctx *context.Context, user *user_model.User) { log.Trace("User activated: %s", user.Name) - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { + if err := updateSession(ctx, nil, map[string]interface{}{ + "uid": user.ID, + "uname": user.Name, + }); err != nil { log.Error("Unable to regenerate session for user: %-v with email: %s: %v", user, user.Email, err) ctx.ServerError("ActivateUserEmail", err) return } - if err := ctx.Session.Set("uid", user.ID); err != nil { - log.Error("Error setting uid in session[%s]: %v", ctx.Session.ID(), err) - } - if err := ctx.Session.Set("uname", user.Name); err != nil { - log.Error("Error setting uname in session[%s]: %v", ctx.Session.ID(), err) - } - if err := ctx.Session.Release(); err != nil { - log.Error("Error storing session[%s]: %v", ctx.Session.ID(), err) - } - if err := resetLocale(ctx, user); err != nil { ctx.ServerError("resetLocale", err) return } + // Register last login + user.SetLastLogin() + if err := user_model.UpdateUserCols(ctx, user, "last_login_unix"); err != nil { + ctx.ServerError("UpdateUserCols", err) + return + } + ctx.Flash.Success(ctx.Tr("auth.account_activated")) ctx.Redirect(setting.AppSubURL + "/") } @@ -801,7 +747,7 @@ func ActivateEmail(ctx *context.Context) { log.Trace("Email activated: %s", email.Email) ctx.Flash.Success(ctx.Tr("settings.add_email_success")) - if u, err := user_model.GetUserByID(email.UID); err != nil { + if u, err := user_model.GetUserByID(ctx, email.UID); err != nil { log.Warn("GetUserByID: %d", email.UID) } else if setting.CacheService.Enabled { // Allow user to validate more emails @@ -814,3 +760,25 @@ func ActivateEmail(ctx *context.Context) { // Should users be logged in automatically here? (consider 2FA requirements, etc.) ctx.Redirect(setting.AppSubURL + "/user/settings/account") } + +func updateSession(ctx *context.Context, deletes []string, updates map[string]interface{}) error { + if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { + return fmt.Errorf("regenerate session: %w", err) + } + sess := ctx.Session + sessID := sess.ID() + for _, k := range deletes { + if err := sess.Delete(k); err != nil { + return fmt.Errorf("delete %v in session[%s]: %w", k, sessID, err) + } + } + for k, v := range updates { + if err := sess.Set(k, v); err != nil { + return fmt.Errorf("set %v in session[%s]: %w", k, sessID, err) + } + } + if err := sess.Release(); err != nil { + return fmt.Errorf("store session[%s]: %w", sessID, err) + } + return nil +} diff --git a/routers/web/auth/linkaccount.go b/routers/web/auth/linkaccount.go index 4f3f2062b6..6c409c6b9d 100644 --- a/routers/web/auth/linkaccount.go +++ b/routers/web/auth/linkaccount.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package auth @@ -14,11 +13,6 @@ import ( user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" - "code.gitea.io/gitea/modules/hcaptcha" - "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/mcaptcha" - "code.gitea.io/gitea/modules/recaptcha" - "code.gitea.io/gitea/modules/session" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/web" auth_service "code.gitea.io/gitea/services/auth" @@ -156,25 +150,16 @@ func linkAccount(ctx *context.Context, u *user_model.User, gothUser goth.User, r return } - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { + if err := updateSession(ctx, nil, map[string]interface{}{ + // User needs to use 2FA, save data and redirect to 2FA page. + "twofaUid": u.ID, + "twofaRemember": remember, + "linkAccount": true, + }); err != nil { ctx.ServerError("RegenerateSession", err) return } - // User needs to use 2FA, save data and redirect to 2FA page. - if err := ctx.Session.Set("twofaUid", u.ID); err != nil { - log.Error("Error setting twofaUid in session: %v", err) - } - if err := ctx.Session.Set("twofaRemember", remember); err != nil { - log.Error("Error setting twofaRemember in session: %v", err) - } - if err := ctx.Session.Set("linkAccount", true); err != nil { - log.Error("Error setting linkAccount in session: %v", err) - } - if err := ctx.Session.Release(); err != nil { - log.Error("Error storing session: %v", err) - } - // If WebAuthn is enrolled -> Redirect to WebAuthn instead regs, err := auth.GetWebAuthnCredentialsByUID(u.ID) if err == nil && len(regs) > 0 { @@ -231,28 +216,8 @@ func LinkAccountPostRegister(ctx *context.Context) { } if setting.Service.EnableCaptcha && setting.Service.RequireExternalRegistrationCaptcha { - var valid bool - var err error - switch setting.Service.CaptchaType { - case setting.ImageCaptcha: - valid = context.GetImageCaptcha().VerifyReq(ctx.Req) - case setting.ReCaptcha: - valid, err = recaptcha.Verify(ctx, form.GRecaptchaResponse) - case setting.HCaptcha: - valid, err = hcaptcha.Verify(ctx, form.HcaptchaResponse) - case setting.MCaptcha: - valid, err = mcaptcha.Verify(ctx, form.McaptchaResponse) - default: - ctx.ServerError("Unknown Captcha Type", fmt.Errorf("Unknown Captcha Type: %s", setting.Service.CaptchaType)) - return - } - if err != nil { - log.Debug("%s", err.Error()) - } - - if !valid { - ctx.Data["Err_Captcha"] = true - ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplLinkAccount, &form) + context.VerifyCaptcha(ctx, tplLinkAccount, form) + if ctx.Written() { return } } diff --git a/routers/web/auth/main_test.go b/routers/web/auth/main_test.go index 71f522fb07..8295515ba9 100644 --- a/routers/web/auth/main_test.go +++ b/routers/web/auth/main_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package auth diff --git a/routers/web/auth/oauth.go b/routers/web/auth/oauth.go index 4fba8d8e8c..3d70ca9a50 100644 --- a/routers/web/auth/oauth.go +++ b/routers/web/auth/oauth.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth @@ -22,7 +21,6 @@ import ( "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/session" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/util" @@ -196,7 +194,7 @@ func newAccessTokenResponse(ctx stdContext.Context, grant *auth.OAuth2Grant, ser ErrorDescription: "cannot find application", } } - user, err := user_model.GetUserByID(grant.UserID) + user, err := user_model.GetUserByID(ctx, grant.UserID) if err != nil { if user_model.IsErrUserNotExist(err) { return nil, &AccessTokenError{ @@ -387,7 +385,7 @@ func AuthorizeOAuth(ctx *context.Context) { var user *user_model.User if app.UID != 0 { - user, err = user_model.GetUserByID(app.UID) + user, err = user_model.GetUserByID(ctx, app.UID) if err != nil { ctx.ServerError("GetUserByID", err) return @@ -1027,17 +1025,12 @@ func setUserGroupClaims(loginSource *auth.Source, u *user_model.User, gothUser * } func showLinkingLogin(ctx *context.Context, gothUser goth.User) { - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { - ctx.ServerError("RegenerateSession", err) + if err := updateSession(ctx, nil, map[string]interface{}{ + "linkAccountGothUser": gothUser, + }); err != nil { + ctx.ServerError("updateSession", err) return } - - if err := ctx.Session.Set("linkAccountGothUser", gothUser); err != nil { - log.Error("Error setting linkAccountGothUser in session: %v", err) - } - if err := ctx.Session.Release(); err != nil { - log.Error("Error storing session: %v", err) - } ctx.Redirect(setting.AppSubURL + "/user/link_account") } @@ -1075,21 +1068,14 @@ func handleOAuth2SignIn(ctx *context.Context, source *auth.Source, u *user_model // If this user is enrolled in 2FA and this source doesn't override it, // we can't sign the user in just yet. Instead, redirect them to the 2FA authentication page. if !needs2FA { - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { - ctx.ServerError("RegenerateSession", err) + if err := updateSession(ctx, nil, map[string]interface{}{ + "uid": u.ID, + "uname": u.Name, + }); err != nil { + ctx.ServerError("updateSession", err) return } - if err := ctx.Session.Set("uid", u.ID); err != nil { - log.Error("Error setting uid in session: %v", err) - } - if err := ctx.Session.Set("uname", u.Name); err != nil { - log.Error("Error setting uname in session: %v", err) - } - if err := ctx.Session.Release(); err != nil { - log.Error("Error storing session: %v", err) - } - // Clear whatever CSRF cookie has right now, force to generate a new one middleware.DeleteCSRFCookie(ctx.Resp) @@ -1138,22 +1124,15 @@ func handleOAuth2SignIn(ctx *context.Context, source *auth.Source, u *user_model } } - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { - ctx.ServerError("RegenerateSession", err) + if err := updateSession(ctx, nil, map[string]interface{}{ + // User needs to use 2FA, save data and redirect to 2FA page. + "twofaUid": u.ID, + "twofaRemember": false, + }); err != nil { + ctx.ServerError("updateSession", err) return } - // User needs to use 2FA, save data and redirect to 2FA page. - if err := ctx.Session.Set("twofaUid", u.ID); err != nil { - log.Error("Error setting twofaUid in session: %v", err) - } - if err := ctx.Session.Set("twofaRemember", false); err != nil { - log.Error("Error setting twofaRemember in session: %v", err) - } - if err := ctx.Session.Release(); err != nil { - log.Error("Error storing session: %v", err) - } - // If WebAuthn is enrolled -> Redirect to WebAuthn instead regs, err := auth.GetWebAuthnCredentialsByUID(u.ID) if err == nil && len(regs) > 0 { @@ -1243,7 +1222,7 @@ func oAuth2UserLoginCallback(authSource *auth.Source, request *http.Request, res return nil, goth.User{}, err } if hasUser { - user, err = user_model.GetUserByID(externalLoginUser.UserID) + user, err = user_model.GetUserByID(request.Context(), externalLoginUser.UserID) return user, gothUser, err } diff --git a/routers/web/auth/oauth_test.go b/routers/web/auth/oauth_test.go index 48400846d2..5116b4fc71 100644 --- a/routers/web/auth/oauth_test.go +++ b/routers/web/auth/oauth_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package auth diff --git a/routers/web/auth/openid.go b/routers/web/auth/openid.go index 3b1065189d..f544b65356 100644 --- a/routers/web/auth/openid.go +++ b/routers/web/auth/openid.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package auth @@ -13,11 +12,7 @@ import ( "code.gitea.io/gitea/modules/auth/openid" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/context" - "code.gitea.io/gitea/modules/hcaptcha" "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/mcaptcha" - "code.gitea.io/gitea/modules/recaptcha" - "code.gitea.io/gitea/modules/session" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/web" @@ -232,27 +227,16 @@ func signInOpenIDVerify(ctx *context.Context) { } } - if _, err := session.RegenerateSession(ctx.Resp, ctx.Req); err != nil { - ctx.ServerError("RegenerateSession", err) - return - } - - if err := ctx.Session.Set("openid_verified_uri", id); err != nil { - log.Error("signInOpenIDVerify: Could not set openid_verified_uri in session: %v", err) - } - if err := ctx.Session.Set("openid_determined_email", email); err != nil { - log.Error("signInOpenIDVerify: Could not set openid_determined_email in session: %v", err) - } - if u != nil { nickname = u.LowerName } - - if err := ctx.Session.Set("openid_determined_username", nickname); err != nil { - log.Error("signInOpenIDVerify: Could not set openid_determined_username in session: %v", err) - } - if err := ctx.Session.Release(); err != nil { - log.Error("signInOpenIDVerify: Unable to save changes to the session: %v", err) + if err := updateSession(ctx, nil, map[string]interface{}{ + "openid_verified_uri": id, + "openid_determined_email": email, + "openid_determined_username": nickname, + }); err != nil { + ctx.ServerError("updateSession", err) + return } if u != nil || !setting.Service.EnableOpenIDSignUp || setting.Service.AllowOnlyInternalRegistration { @@ -369,14 +353,7 @@ func RegisterOpenIDPost(ctx *context.Context) { ctx.Data["PageIsSignIn"] = true ctx.Data["PageIsOpenIDRegister"] = true ctx.Data["EnableOpenIDSignUp"] = setting.Service.EnableOpenIDSignUp - ctx.Data["EnableCaptcha"] = setting.Service.EnableCaptcha - ctx.Data["RecaptchaURL"] = setting.Service.RecaptchaURL - ctx.Data["Captcha"] = context.GetImageCaptcha() - ctx.Data["CaptchaType"] = setting.Service.CaptchaType - ctx.Data["RecaptchaSitekey"] = setting.Service.RecaptchaSitekey - ctx.Data["HcaptchaSitekey"] = setting.Service.HcaptchaSitekey - ctx.Data["McaptchaSitekey"] = setting.Service.McaptchaSitekey - ctx.Data["McaptchaURL"] = setting.Service.McaptchaURL + context.SetCaptchaData(ctx) ctx.Data["OpenID"] = oid if setting.Service.AllowOnlyInternalRegistration { @@ -385,42 +362,11 @@ func RegisterOpenIDPost(ctx *context.Context) { } if setting.Service.EnableCaptcha { - var valid bool - var err error - switch setting.Service.CaptchaType { - case setting.ImageCaptcha: - valid = context.GetImageCaptcha().VerifyReq(ctx.Req) - case setting.ReCaptcha: - if err := ctx.Req.ParseForm(); err != nil { - ctx.ServerError("", err) - return - } - valid, err = recaptcha.Verify(ctx, form.GRecaptchaResponse) - case setting.HCaptcha: - if err := ctx.Req.ParseForm(); err != nil { - ctx.ServerError("", err) - return - } - valid, err = hcaptcha.Verify(ctx, form.HcaptchaResponse) - case setting.MCaptcha: - if err := ctx.Req.ParseForm(); err != nil { - ctx.ServerError("", err) - return - } - valid, err = mcaptcha.Verify(ctx, form.McaptchaResponse) - default: - ctx.ServerError("Unknown Captcha Type", fmt.Errorf("Unknown Captcha Type: %s", setting.Service.CaptchaType)) - return - } - if err != nil { - log.Debug("%s", err.Error()) - } - - if !valid { - ctx.Data["Err_Captcha"] = true - ctx.RenderWithErr(ctx.Tr("form.captcha_incorrect"), tplSignUpOID, &form) + if err := ctx.Req.ParseForm(); err != nil { + ctx.ServerError("", err) return } + context.VerifyCaptcha(ctx, tplSignUpOID, form) } length := setting.MinPasswordLength diff --git a/routers/web/auth/password.go b/routers/web/auth/password.go index c21ca9cf69..e546c77bc9 100644 --- a/routers/web/auth/password.go +++ b/routers/web/auth/password.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth diff --git a/routers/web/auth/webauthn.go b/routers/web/auth/webauthn.go index 917cbdd57b..965fc10fe7 100644 --- a/routers/web/auth/webauthn.go +++ b/routers/web/auth/webauthn.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package auth @@ -50,7 +49,7 @@ func WebAuthnLoginAssertion(ctx *context.Context) { return } - user, err := user_model.GetUserByID(idSess) + user, err := user_model.GetUserByID(ctx, idSess) if err != nil { ctx.ServerError("UserSignIn", err) return @@ -92,7 +91,7 @@ func WebAuthnLoginAssertionPost(ctx *context.Context) { }() // Load the user from the db - user, err := user_model.GetUserByID(idSess) + user, err := user_model.GetUserByID(ctx, idSess) if err != nil { ctx.ServerError("UserSignIn", err) return diff --git a/routers/web/auth_windows.go b/routers/web/auth_windows.go index f404fd3771..3125d7ce9a 100644 --- a/routers/web/auth_windows.go +++ b/routers/web/auth_windows.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package web diff --git a/routers/web/base.go b/routers/web/base.go index 2441d6d517..b0d8a7c3f1 100644 --- a/routers/web/base.go +++ b/routers/web/base.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package web diff --git a/routers/web/events/events.go b/routers/web/events/events.go index d8c6f38d02..1a5a162c1a 100644 --- a/routers/web/events/events.go +++ b/routers/web/events/events.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package events diff --git a/routers/web/explore/code.go b/routers/web/explore/code.go index 38474255d1..942b1f8378 100644 --- a/routers/web/explore/code.go +++ b/routers/web/explore/code.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package explore diff --git a/routers/web/explore/org.go b/routers/web/explore/org.go index eb6972fad3..c9fb05ff3a 100644 --- a/routers/web/explore/org.go +++ b/routers/web/explore/org.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package explore diff --git a/routers/web/explore/repo.go b/routers/web/explore/repo.go index 8cb615b7bc..5271e39bbc 100644 --- a/routers/web/explore/repo.go +++ b/routers/web/explore/repo.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package explore @@ -98,7 +97,7 @@ func RenderRepoSearch(ctx *context.Context, opts *RepoSearchOptions) { language := ctx.FormTrim("language") ctx.Data["Language"] = language - repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{ + repos, count, err = repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{ Page: page, PageSize: opts.PageSize, diff --git a/routers/web/explore/topic.go b/routers/web/explore/topic.go index 39b87f2498..50df9d1113 100644 --- a/routers/web/explore/topic.go +++ b/routers/web/explore/topic.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package explore diff --git a/routers/web/explore/user.go b/routers/web/explore/user.go index ea3d83e8d6..e00493c87b 100644 --- a/routers/web/explore/user.go +++ b/routers/web/explore/user.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package explore @@ -69,6 +68,10 @@ func RenderUserSearch(ctx *context.Context, opts *user_model.SearchUserOptions, orderBy = "`user`.updated_unix ASC" case "reversealphabetically": orderBy = "`user`.name DESC" + case "lastlogin": + orderBy = "`user`.last_login_unix ASC" + case "reverselastlogin": + orderBy = "`user`.last_login_unix DESC" case UserSearchDefaultSortType: // "alphabetically" default: orderBy = "`user`.name ASC" diff --git a/routers/web/feed/convert.go b/routers/web/feed/convert.go index c6fc352b64..7d472a7f87 100644 --- a/routers/web/feed/convert.go +++ b/routers/web/feed/convert.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package feed @@ -69,7 +68,7 @@ func renderMarkdown(ctx *context.Context, act *activities_model.Action, content // feedActionsToFeedItems convert gitea's Action feed to feeds Item func feedActionsToFeedItems(ctx *context.Context, actions activities_model.ActionList) (items []*feeds.Item, err error) { for _, act := range actions { - act.LoadActUser() + act.LoadActUser(ctx) var content, desc, title string diff --git a/routers/web/feed/profile.go b/routers/web/feed/profile.go index 0e11f210ce..7641769192 100644 --- a/routers/web/feed/profile.go +++ b/routers/web/feed/profile.go @@ -1,11 +1,9 @@ // 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. +// SPDX-License-Identifier: MIT package feed import ( - "net/http" "time" activities_model "code.gitea.io/gitea/models/activities" @@ -59,7 +57,6 @@ func showUserFeed(ctx *context.Context, formatType string) { // writeFeed write a feeds.Feed as atom or rss to ctx.Resp func writeFeed(ctx *context.Context, feed *feeds.Feed, formatType string) { - ctx.Resp.WriteHeader(http.StatusOK) if formatType == "atom" { ctx.Resp.Header().Set("Content-Type", "application/atom+xml;charset=utf-8") if err := feed.WriteAtom(ctx.Resp); err != nil { diff --git a/routers/web/feed/repo.go b/routers/web/feed/repo.go index 027f90872f..1d24b58800 100644 --- a/routers/web/feed/repo.go +++ b/routers/web/feed/repo.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package feed diff --git a/routers/web/goget.go b/routers/web/goget.go index a58739fe42..fb8afae999 100644 --- a/routers/web/goget.go +++ b/routers/web/goget.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package web @@ -53,7 +52,7 @@ func goGet(ctx *context.Context) { } branchName := setting.Repository.DefaultBranch - repo, err := repo_model.GetRepositoryByOwnerAndName(ownerName, repoName) + repo, err := repo_model.GetRepositoryByOwnerAndName(ctx, ownerName, repoName) if err == nil && len(repo.DefaultBranch) > 0 { branchName = repo.DefaultBranch } diff --git a/routers/web/healthcheck/check.go b/routers/web/healthcheck/check.go index 57707b6121..1142a0aec5 100644 --- a/routers/web/healthcheck/check.go +++ b/routers/web/healthcheck/check.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package healthcheck diff --git a/routers/web/home.go b/routers/web/home.go index 0c74987ba7..ecfecf6e67 100644 --- a/routers/web/home.go +++ b/routers/web/home.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package web @@ -88,7 +87,7 @@ func HomeSitemap(ctx *context.Context) { } } - _, cnt, err := repo_model.SearchRepository(&repo_model.SearchRepoOptions{ + _, cnt, err := repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{ PageSize: 1, }, diff --git a/routers/web/metrics.go b/routers/web/metrics.go index c7e01b8faa..46c13f0a24 100644 --- a/routers/web/metrics.go +++ b/routers/web/metrics.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package web diff --git a/routers/web/misc/markdown.go b/routers/web/misc/markdown.go index 0567cbb30c..aaa3ed0781 100644 --- a/routers/web/misc/markdown.go +++ b/routers/web/misc/markdown.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2022 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. +// SPDX-License-Identifier: MIT package misc diff --git a/routers/web/misc/swagger.go b/routers/web/misc/swagger.go index e46d4194b4..72c09a3780 100644 --- a/routers/web/misc/swagger.go +++ b/routers/web/misc/swagger.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package misc diff --git a/routers/web/nodeinfo.go b/routers/web/nodeinfo.go index 2ee94e35e8..01b71e7086 100644 --- a/routers/web/nodeinfo.go +++ b/routers/web/nodeinfo.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package web diff --git a/routers/web/org/home.go b/routers/web/org/home.go index 63243a391f..4cc364acd3 100644 --- a/routers/web/org/home.go +++ b/routers/web/org/home.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package org @@ -99,7 +98,7 @@ func Home(ctx *context.Context) { count int64 err error ) - repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{ + repos, count, err = repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{ PageSize: setting.UI.User.RepoPagingNum, Page: page, diff --git a/routers/web/org/members.go b/routers/web/org/members.go index ec5a98fc6a..8361da6632 100644 --- a/routers/web/org/members.go +++ b/routers/web/org/members.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2020 The Gitea Authors. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package org @@ -108,13 +107,20 @@ func MembersAction(ctx *context.Context) { } case "leave": err = models.RemoveOrgUser(org.ID, ctx.Doer.ID) - if organization.IsErrLastOrgOwner(err) { + if err == nil { + ctx.Flash.Success(ctx.Tr("form.organization_leave_success", org.DisplayName())) + ctx.JSON(http.StatusOK, map[string]interface{}{ + "redirect": "", // keep the user stay on current page, in case they want to do other operations. + }) + } else if organization.IsErrLastOrgOwner(err) { ctx.Flash.Error(ctx.Tr("form.last_org_owner")) ctx.JSON(http.StatusOK, map[string]interface{}{ "redirect": ctx.Org.OrgLink + "/members", }) - return + } else { + log.Error("RemoveOrgUser(%d,%d): %v", org.ID, ctx.Doer.ID, err) } + return } if err != nil { diff --git a/routers/web/org/org.go b/routers/web/org/org.go index 32d8787995..f67e7edb4c 100644 --- a/routers/web/org/org.go +++ b/routers/web/org/org.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package org diff --git a/routers/web/org/org_labels.go b/routers/web/org/org_labels.go index 185e1eee31..1c910a93a5 100644 --- a/routers/web/org/org_labels.go +++ b/routers/web/org/org_labels.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package org diff --git a/routers/web/org/setting.go b/routers/web/org/setting.go index 3f7bc59856..899e554ba0 100644 --- a/routers/web/org/setting.go +++ b/routers/web/org/setting.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package org diff --git a/routers/web/org/setting_oauth2.go b/routers/web/org/setting_oauth2.go index 47d1141f34..9bf4280b07 100644 --- a/routers/web/org/setting_oauth2.go +++ b/routers/web/org/setting_oauth2.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package org diff --git a/routers/web/org/setting_packages.go b/routers/web/org/setting_packages.go new file mode 100644 index 0000000000..80135ca2d0 --- /dev/null +++ b/routers/web/org/setting_packages.go @@ -0,0 +1,86 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package org + +import ( + "fmt" + "net/http" + + "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/setting" + shared "code.gitea.io/gitea/routers/web/shared/packages" +) + +const ( + tplSettingsPackages base.TplName = "org/settings/packages" + tplSettingsPackagesRuleEdit base.TplName = "org/settings/packages_cleanup_rules_edit" + tplSettingsPackagesRulePreview base.TplName = "org/settings/packages_cleanup_rules_preview" +) + +func Packages(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("packages.title") + ctx.Data["PageIsOrgSettings"] = true + ctx.Data["PageIsSettingsPackages"] = true + + shared.SetPackagesContext(ctx, ctx.ContextUser) + + ctx.HTML(http.StatusOK, tplSettingsPackages) +} + +func PackagesRuleAdd(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("packages.title") + ctx.Data["PageIsOrgSettings"] = true + ctx.Data["PageIsSettingsPackages"] = true + + shared.SetRuleAddContext(ctx) + + ctx.HTML(http.StatusOK, tplSettingsPackagesRuleEdit) +} + +func PackagesRuleEdit(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("packages.title") + ctx.Data["PageIsOrgSettings"] = true + ctx.Data["PageIsSettingsPackages"] = true + + shared.SetRuleEditContext(ctx, ctx.ContextUser) + + ctx.HTML(http.StatusOK, tplSettingsPackagesRuleEdit) +} + +func PackagesRuleAddPost(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("packages.title") + ctx.Data["PageIsOrgSettings"] = true + ctx.Data["PageIsSettingsPackages"] = true + + shared.PerformRuleAddPost( + ctx, + ctx.ContextUser, + fmt.Sprintf("%s/org/%s/settings/packages", setting.AppSubURL, ctx.ContextUser.Name), + tplSettingsPackagesRuleEdit, + ) +} + +func PackagesRuleEditPost(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("packages.title") + ctx.Data["PageIsOrgSettings"] = true + ctx.Data["PageIsSettingsPackages"] = true + + shared.PerformRuleEditPost( + ctx, + ctx.ContextUser, + fmt.Sprintf("%s/org/%s/settings/packages", setting.AppSubURL, ctx.ContextUser.Name), + tplSettingsPackagesRuleEdit, + ) +} + +func PackagesRulePreview(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("packages.title") + ctx.Data["PageIsOrgSettings"] = true + ctx.Data["PageIsSettingsPackages"] = true + + shared.SetRulePreviewContext(ctx, ctx.ContextUser) + + ctx.HTML(http.StatusOK, tplSettingsPackagesRulePreview) +} diff --git a/routers/web/org/teams.go b/routers/web/org/teams.go index 399d07fe47..5dd86fdf11 100644 --- a/routers/web/org/teams.go +++ b/routers/web/org/teams.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package org @@ -50,7 +49,7 @@ func Teams(ctx *context.Context) { ctx.Data["PageIsOrgTeams"] = true for _, t := range ctx.Org.Teams { - if err := t.GetMembersCtx(ctx); err != nil { + if err := t.LoadMembers(ctx); err != nil { ctx.ServerError("GetMembers", err) return } @@ -347,7 +346,7 @@ func TeamMembers(ctx *context.Context) { ctx.Data["Title"] = ctx.Org.Team.Name ctx.Data["PageIsOrgTeams"] = true ctx.Data["PageIsOrgTeamMembers"] = true - if err := ctx.Org.Team.GetMembersCtx(ctx); err != nil { + if err := ctx.Org.Team.LoadMembers(ctx); err != nil { ctx.ServerError("GetMembers", err) return } @@ -369,7 +368,7 @@ func TeamRepositories(ctx *context.Context) { ctx.Data["Title"] = ctx.Org.Team.Name ctx.Data["PageIsOrgTeams"] = true ctx.Data["PageIsOrgTeamRepos"] = true - if err := ctx.Org.Team.GetRepositoriesCtx(ctx); err != nil { + if err := ctx.Org.Team.LoadRepositories(ctx); err != nil { ctx.ServerError("GetRepositories", err) return } @@ -571,7 +570,7 @@ func getTeamInviteFromContext(ctx *context.Context) (*org_model.TeamInvite, *org return nil, nil, nil, nil, err } - inviter, err := user_model.GetUserByIDCtx(ctx, invite.InviterID) + inviter, err := user_model.GetUserByID(ctx, invite.InviterID) if err != nil { return nil, nil, nil, nil, err } @@ -581,7 +580,7 @@ func getTeamInviteFromContext(ctx *context.Context) (*org_model.TeamInvite, *org return nil, nil, nil, nil, err } - org, err := user_model.GetUserByIDCtx(ctx, team.OrgID) + org, err := user_model.GetUserByID(ctx, team.OrgID) if err != nil { return nil, nil, nil, nil, err } diff --git a/routers/web/repo/activity.go b/routers/web/repo/activity.go index 316cbcd95f..3d030edaca 100644 --- a/routers/web/repo/activity.go +++ b/routers/web/repo/activity.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/attachment.go b/routers/web/repo/attachment.go index 190dc6c2c7..589632ad6e 100644 --- a/routers/web/repo/attachment.go +++ b/routers/web/repo/attachment.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo @@ -45,7 +44,11 @@ func uploadAttachment(ctx *context.Context, repoID int64, allowedTypes string) { } defer file.Close() - attach, err := attachment.UploadAttachment(file, ctx.Doer.ID, repoID, 0, header.Filename, allowedTypes) + attach, err := attachment.UploadAttachment(file, allowedTypes, &repo_model.Attachment{ + Name: header.Filename, + UploaderID: ctx.Doer.ID, + RepoID: repoID, + }) if err != nil { if upload.IsErrFileTypeForbidden(err) { ctx.Error(http.StatusBadRequest, err.Error()) @@ -83,7 +86,7 @@ func DeleteAttachment(ctx *context.Context) { }) } -// GetAttachment serve attachements +// GetAttachment serve attachments func GetAttachment(ctx *context.Context) { attach, err := repo_model.GetAttachmentByUUID(ctx, ctx.Params(":uuid")) if err != nil { @@ -95,7 +98,7 @@ func GetAttachment(ctx *context.Context) { return } - repository, unitType, err := repo_service.LinkedRepository(attach) + repository, unitType, err := repo_service.LinkedRepository(ctx, attach) if err != nil { ctx.ServerError("LinkedRepository", err) return diff --git a/routers/web/repo/blame.go b/routers/web/repo/blame.go index 64a6f0ec53..50bfa9d3bd 100644 --- a/routers/web/repo/blame.go +++ b/routers/web/repo/blame.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo @@ -100,6 +99,8 @@ func RefBlame(ctx *context.Context) { ctx.Data["FileName"] = blob.Name() ctx.Data["NumLines"], err = blob.GetBlobLineCount() + ctx.Data["NumLinesSet"] = true + if err != nil { ctx.NotFound("GetBlobLineCount", err) return @@ -237,6 +238,8 @@ func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames m rows := make([]*blameRow, 0) escapeStatus := &charset.EscapeStatus{} + var lexerName string + i := 0 commitCnt := 0 for _, part := range blameParts { @@ -278,7 +281,13 @@ func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames m line += "\n" } fileName := fmt.Sprintf("%v", ctx.Data["FileName"]) - line = highlight.Code(fileName, language, line) + line, lexerNameForLine := highlight.Code(fileName, language, line) + + // set lexer name to the first detected lexer. this is certainly suboptimal and + // we should instead highlight the whole file at once + if lexerName == "" { + lexerName = lexerNameForLine + } br.EscapeStatus, line = charset.EscapeControlHTML(line, ctx.Locale) br.Code = gotemplate.HTML(line) @@ -290,4 +299,5 @@ func renderBlame(ctx *context.Context, blameParts []git.BlamePart, commitNames m ctx.Data["EscapeStatus"] = escapeStatus ctx.Data["BlameRows"] = rows ctx.Data["CommitCnt"] = commitCnt + ctx.Data["LexerName"] = lexerName } diff --git a/routers/web/repo/branch.go b/routers/web/repo/branch.go index d1f1255db4..18bb06ed1a 100644 --- a/routers/web/repo/branch.go +++ b/routers/web/repo/branch.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo @@ -126,6 +125,10 @@ func RestoreBranchPost(ctx *context.Context) { log.Error("GetDeletedBranchByID: %v", err) ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", branchName)) return + } else if deletedBranch == nil { + log.Debug("RestoreBranch: Can't restore branch[%d] '%s', as it does not exist", branchID, branchName) + ctx.Flash.Error(ctx.Tr("repo.branch.restore_failed", branchName)) + return } if err := git.Push(ctx, ctx.Repo.Repository.RepoPath(), git.PushOptions{ @@ -275,14 +278,14 @@ func loadOneBranch(ctx *context.Context, rawBranch, defaultBranch *git.Branch, p mergeMovedOn := false if pr != nil { pr.HeadRepo = ctx.Repo.Repository - if err := pr.LoadIssue(); err != nil { - ctx.ServerError("pr.LoadIssue", err) + if err := pr.LoadIssue(ctx); err != nil { + ctx.ServerError("LoadIssue", err) return nil } if repo, ok := repoIDToRepo[pr.BaseRepoID]; ok { pr.BaseRepo = repo - } else if err := pr.LoadBaseRepoCtx(ctx); err != nil { - ctx.ServerError("pr.LoadBaseRepo", err) + } else if err := pr.LoadBaseRepo(ctx); err != nil { + ctx.ServerError("LoadBaseRepo", err) return nil } else { repoIDToRepo[pr.BaseRepoID] = pr.BaseRepo @@ -334,7 +337,7 @@ func getDeletedBranches(ctx *context.Context) ([]*Branch, error) { } for i := range deletedBranches { - deletedBranches[i].LoadUser() + deletedBranches[i].LoadUser(ctx) branches = append(branches, &Branch{ Name: deletedBranches[i].Name, IsDeleted: true, diff --git a/routers/web/repo/cherry_pick.go b/routers/web/repo/cherry_pick.go index d2a4e19d0e..48bc6959e0 100644 --- a/routers/web/repo/cherry_pick.go +++ b/routers/web/repo/cherry_pick.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo @@ -178,7 +177,7 @@ func CherryPickPost(ctx *context.Context) { } } - if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(unit.TypePullRequests) { + if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(ctx, unit.TypePullRequests) { ctx.Redirect(ctx.Repo.RepoLink + "/compare/" + util.PathEscapeSegments(ctx.Repo.BranchName) + "..." + util.PathEscapeSegments(form.NewBranchName)) } else { ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(branchName)) diff --git a/routers/web/repo/commit.go b/routers/web/repo/commit.go index a6553256b0..efc216661c 100644 --- a/routers/web/repo/commit.go +++ b/routers/web/repo/commit.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/compare.go b/routers/web/repo/compare.go index db6b59471f..d95eeaecc9 100644 --- a/routers/web/repo/compare.go +++ b/routers/web/repo/compare.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo @@ -270,7 +269,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo { ci.HeadRepo = baseRepo } } else { - ci.HeadRepo, err = repo_model.GetRepositoryByOwnerAndName(headInfosSplit[0], headInfosSplit[1]) + ci.HeadRepo, err = repo_model.GetRepositoryByOwnerAndName(ctx, headInfosSplit[0], headInfosSplit[1]) if err != nil { if repo_model.IsErrRepoNotExist(err) { ctx.NotFound("GetRepositoryByOwnerAndName", nil) @@ -340,7 +339,7 @@ func ParseCompareInfo(ctx *context.Context) *CompareInfo { // forked from var rootRepo *repo_model.Repository if baseRepo.IsFork { - err = baseRepo.GetBaseRepo() + err = baseRepo.GetBaseRepo(ctx) if err != nil { if !repo_model.IsErrRepoNotExist(err) { ctx.ServerError("Unable to find root repo", err) @@ -578,7 +577,7 @@ func PrepareCompareDiff( if (headCommitID == ci.CompareInfo.MergeBase && !ci.DirectComparison) || headCommitID == ci.CompareInfo.BaseCommitID { ctx.Data["IsNothingToCompare"] = true - if unit, err := repo.GetUnit(unit.TypePullRequests); err == nil { + if unit, err := repo.GetUnit(ctx, unit.TypePullRequests); err == nil { config := unit.PullRequestsConfig() if !config.AutodetectManualMerge { @@ -747,7 +746,7 @@ func CompareDiff(ctx *context.Context) { ctx.Data["HeadTags"] = headTags if ctx.Data["PageIsComparePull"] == true { - pr, err := issues_model.GetUnmergedPullRequest(ci.HeadRepo.ID, ctx.Repo.Repository.ID, ci.HeadBranch, ci.BaseBranch, issues_model.PullRequestFlowGithub) + pr, err := issues_model.GetUnmergedPullRequest(ctx, ci.HeadRepo.ID, ctx.Repo.Repository.ID, ci.HeadBranch, ci.BaseBranch, issues_model.PullRequestFlowGithub) if err != nil { if !issues_model.IsErrPullRequestNotExist(err) { ctx.ServerError("GetUnmergedPullRequest", err) @@ -755,7 +754,7 @@ func CompareDiff(ctx *context.Context) { } } else { ctx.Data["HasPullRequest"] = true - if err := pr.LoadIssue(); err != nil { + if err := pr.LoadIssue(ctx); err != nil { ctx.ServerError("LoadIssue", err) return } diff --git a/routers/web/repo/download.go b/routers/web/repo/download.go index cd2d305de6..c1e9ba58b9 100644 --- a/routers/web/repo/download.go +++ b/routers/web/repo/download.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/editor.go b/routers/web/repo/editor.go index e8fc020450..e5ba4ad2c1 100644 --- a/routers/web/repo/editor.go +++ b/routers/web/repo/editor.go @@ -1,6 +1,5 @@ // Copyright 2016 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package repo @@ -329,7 +328,7 @@ func editFilePost(ctx *context.Context, form forms.EditRepoFileForm, isNewFile b } } - if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(unit.TypePullRequests) { + if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(ctx, unit.TypePullRequests) { ctx.Redirect(ctx.Repo.RepoLink + "/compare/" + util.PathEscapeSegments(ctx.Repo.BranchName) + "..." + util.PathEscapeSegments(form.NewBranchName)) } else { ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(branchName) + "/" + util.PathEscapeSegments(form.TreePath)) @@ -515,7 +514,7 @@ func DeleteFilePost(ctx *context.Context) { } ctx.Flash.Success(ctx.Tr("repo.editor.file_delete_success", ctx.Repo.TreePath)) - if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(unit.TypePullRequests) { + if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(ctx, unit.TypePullRequests) { ctx.Redirect(ctx.Repo.RepoLink + "/compare/" + util.PathEscapeSegments(ctx.Repo.BranchName) + "..." + util.PathEscapeSegments(form.NewBranchName)) } else { treePath := path.Dir(ctx.Repo.TreePath) @@ -718,7 +717,7 @@ func UploadFilePost(ctx *context.Context) { return } - if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(unit.TypePullRequests) { + if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(ctx, unit.TypePullRequests) { ctx.Redirect(ctx.Repo.RepoLink + "/compare/" + util.PathEscapeSegments(ctx.Repo.BranchName) + "..." + util.PathEscapeSegments(form.NewBranchName)) } else { ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(branchName) + "/" + util.PathEscapeSegments(form.TreePath)) diff --git a/routers/web/repo/editor_test.go b/routers/web/repo/editor_test.go index ac0c385897..1e53aac9b0 100644 --- a/routers/web/repo/editor_test.go +++ b/routers/web/repo/editor_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/find.go b/routers/web/repo/find.go index 7117c00076..daefe59c8f 100644 --- a/routers/web/repo/find.go +++ b/routers/web/repo/find.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/http.go b/routers/web/repo/http.go index 1ec781bb13..b2a49e3e3a 100644 --- a/routers/web/repo/http.go +++ b/routers/web/repo/http.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo @@ -259,7 +258,7 @@ func httpBase(ctx *context.Context) (h *serviceHandler) { if isWiki { // Ensure the wiki is enabled before we allow access to it - if _, err := repo.GetUnit(unit.TypeWiki); err != nil { + if _, err := repo.GetUnit(ctx, unit.TypeWiki); err != nil { if repo_model.IsErrUnitTypeNotExist(err) { ctx.PlainText(http.StatusForbidden, "repository wiki is disabled") return diff --git a/routers/web/repo/http_test.go b/routers/web/repo/http_test.go index 58ac1c07a1..5ba8de3d63 100644 --- a/routers/web/repo/http_test.go +++ b/routers/web/repo/http_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/issue.go b/routers/web/repo/issue.go index 38ad593c17..d315525dac 100644 --- a/routers/web/repo/issue.go +++ b/routers/web/repo/issue.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo @@ -48,7 +47,6 @@ import ( "code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/routers/utils" asymkey_service "code.gitea.io/gitea/services/asymkey" - comment_service "code.gitea.io/gitea/services/comments" "code.gitea.io/gitea/services/forms" issue_service "code.gitea.io/gitea/services/issue" pull_service "code.gitea.io/gitea/services/pull" @@ -115,7 +113,7 @@ func MustEnableIssues(ctx *context.Context) { return } - unit, err := ctx.Repo.Repository.GetUnit(unit.TypeExternalTracker) + unit, err := ctx.Repo.Repository.GetUnit(ctx, unit.TypeExternalTracker) if err == nil { ctx.Redirect(unit.ExternalTrackerConfig().ExternalTrackerURL) return @@ -246,7 +244,7 @@ func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption uti if forceEmpty { issues = []*issues_model.Issue{} } else { - issues, err = issues_model.Issues(&issues_model.IssuesOptions{ + issues, err = issues_model.Issues(ctx, &issues_model.IssuesOptions{ ListOptions: db.ListOptions{ Page: pager.Paginater.Current(), PageSize: setting.UI.IssuePagingNum, @@ -608,7 +606,7 @@ func RetrieveRepoReviewers(ctx *context.Context, repo *repo_model.Repository, is currentPullReviewers := make([]*repoReviewerSelection, 0, len(pullReviews)) for _, item := range pullReviews { if item.Review.ReviewerID > 0 { - if err = item.Review.LoadReviewer(); err != nil { + if err = item.Review.LoadReviewer(ctx); err != nil { if user_model.IsErrUserNotExist(err) { continue } @@ -617,7 +615,7 @@ func RetrieveRepoReviewers(ctx *context.Context, repo *repo_model.Repository, is } item.User = item.Review.Reviewer } else if item.Review.ReviewerTeamID > 0 { - if err = item.Review.LoadReviewerTeam(); err != nil { + if err = item.Review.LoadReviewerTeam(ctx); err != nil { if organization.IsErrTeamNotExist(err) { continue } @@ -784,6 +782,10 @@ func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleFiles } } } + + } + if !strings.HasPrefix(template.Ref, "refs/") { // Assume that the ref intended is always a branch - for tags users should use refs/tags/ + template.Ref = git.BranchPrefix + template.Ref } ctx.Data["HasSelectedLabel"] = len(labelIDs) > 0 ctx.Data["label_ids"] = strings.Join(labelIDs, ",") @@ -1004,7 +1006,7 @@ func ValidateRepoMetas(ctx *context.Context, form forms.CreateIssueForm, isPull // Check if the passed assignees actually exists and is assignable for _, aID := range assigneeIDs { - assignee, err := user_model.GetUserByID(aID) + assignee, err := user_model.GetUserByID(ctx, aID) if err != nil { ctx.ServerError("GetUserByID", err) return nil, nil, 0, 0 @@ -1163,7 +1165,7 @@ func getBranchData(ctx *context.Context, issue *issues_model.Issue) { pull := issue.PullRequest ctx.Data["BaseBranch"] = pull.BaseBranch ctx.Data["HeadBranch"] = pull.HeadBranch - ctx.Data["HeadUserName"] = pull.MustHeadUserName() + ctx.Data["HeadUserName"] = pull.MustHeadUserName(ctx) } } @@ -1171,7 +1173,7 @@ func getBranchData(ctx *context.Context, issue *issues_model.Issue) { func ViewIssue(ctx *context.Context) { if ctx.Params(":type") == "issues" { // If issue was requested we check if repo has external tracker and redirect - extIssueUnit, err := ctx.Repo.Repository.GetUnit(unit.TypeExternalTracker) + extIssueUnit, err := ctx.Repo.Repository.GetUnit(ctx, unit.TypeExternalTracker) if err == nil && extIssueUnit != nil { if extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == markup.IssueNameStyleNumeric || extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == "" { metas := ctx.Repo.Repository.ComposeMetas() @@ -1372,7 +1374,7 @@ func ViewIssue(ctx *context.Context) { comment *issues_model.Comment participants = make([]*user_model.User, 1, 10) ) - if ctx.Repo.Repository.IsTimetrackerEnabled() { + if ctx.Repo.Repository.IsTimetrackerEnabled(ctx) { if ctx.IsSigned { // Deal with the stopwatch ctx.Data["IsStopwatchRunning"] = issues_model.StopwatchExists(ctx.Doer.ID, issue.ID) @@ -1426,13 +1428,13 @@ func ViewIssue(ctx *context.Context) { for _, comment = range issue.Comments { comment.Issue = issue - if err := comment.LoadPoster(); err != nil { + if err := comment.LoadPoster(ctx); err != nil { ctx.ServerError("LoadPoster", err) return } if comment.Type == issues_model.CommentTypeComment || comment.Type == issues_model.CommentTypeReview { - if err := comment.LoadAttachments(); err != nil { + if err := comment.LoadAttachments(ctx); err != nil { ctx.ServerError("LoadAttachments", err) return } @@ -1467,7 +1469,7 @@ func ViewIssue(ctx *context.Context) { return } } else if comment.Type == issues_model.CommentTypeMilestone { - if err = comment.LoadMilestone(); err != nil { + if err = comment.LoadMilestone(ctx); err != nil { ctx.ServerError("LoadMilestone", err) return } @@ -1591,7 +1593,7 @@ func ViewIssue(ctx *context.Context) { ctx.Data["AllowMerge"] = false if ctx.IsSigned { - if err := pull.LoadHeadRepoCtx(ctx); err != nil { + if err := pull.LoadHeadRepo(ctx); err != nil { log.Error("LoadHeadRepo: %v", err) } else if pull.HeadRepo != nil { perm, err := access_model.GetUserRepoPermission(ctx, pull.HeadRepo, ctx.Doer) @@ -1613,7 +1615,7 @@ func ViewIssue(ctx *context.Context) { } } - if err := pull.LoadBaseRepoCtx(ctx); err != nil { + if err := pull.LoadBaseRepo(ctx); err != nil { log.Error("LoadBaseRepo: %v", err) } perm, err := access_model.GetUserRepoPermission(ctx, pull.BaseRepo, ctx.Doer) @@ -1633,7 +1635,7 @@ func ViewIssue(ctx *context.Context) { } } - prUnit, err := repo.GetUnit(unit.TypePullRequests) + prUnit, err := repo.GetUnit(ctx, unit.TypePullRequests) if err != nil { ctx.ServerError("GetUnit", err) return @@ -1662,21 +1664,21 @@ func ViewIssue(ctx *context.Context) { ctx.Data["MergeStyle"] = mergeStyle - defaultMergeMessage, err := pull_service.GetDefaultMergeMessage(ctx.Repo.GitRepo, pull, mergeStyle) + defaultMergeMessage, err := pull_service.GetDefaultMergeMessage(ctx, ctx.Repo.GitRepo, pull, mergeStyle) if err != nil { ctx.ServerError("GetDefaultMergeMessage", err) return } ctx.Data["DefaultMergeMessage"] = defaultMergeMessage - defaultSquashMergeMessage, err := pull_service.GetDefaultMergeMessage(ctx.Repo.GitRepo, pull, repo_model.MergeStyleSquash) + defaultSquashMergeMessage, err := pull_service.GetDefaultMergeMessage(ctx, ctx.Repo.GitRepo, pull, repo_model.MergeStyleSquash) if err != nil { ctx.ServerError("GetDefaultSquashMergeMessage", err) return } ctx.Data["DefaultSquashMergeMessage"] = defaultSquashMergeMessage - if err = pull.LoadProtectedBranch(); err != nil { + if err = pull.LoadProtectedBranch(ctx); err != nil { ctx.ServerError("LoadProtectedBranch", err) return } @@ -1885,7 +1887,7 @@ func GetIssueInfo(ctx *context.Context) { } } - ctx.JSON(http.StatusOK, convert.ToAPIIssue(issue)) + ctx.JSON(http.StatusOK, convert.ToAPIIssue(ctx, issue)) } // UpdateIssueTitle change issue's title @@ -2059,7 +2061,7 @@ func UpdateIssueAssignee(ctx *context.Context) { return } default: - assignee, err := user_model.GetUserByID(assigneeID) + assignee, err := user_model.GetUserByID(ctx, assigneeID) if err != nil { ctx.ServerError("GetUserByID", err) return @@ -2170,7 +2172,7 @@ func UpdatePullReviewRequest(ctx *context.Context) { continue } - reviewer, err := user_model.GetUserByID(reviewID) + reviewer, err := user_model.GetUserByID(ctx, reviewID) if err != nil { if user_model.IsErrUserNotExist(err) { log.Warn( @@ -2280,7 +2282,7 @@ func SearchIssues(ctx *context.Context) { repoCond := repo_model.SearchRepositoryCondition(opts) repoIDs, _, err := repo_model.SearchRepositoryIDs(opts) if err != nil { - ctx.Error(http.StatusInternalServerError, "SearchRepositoryByName", err.Error()) + ctx.Error(http.StatusInternalServerError, "SearchRepositoryIDs", err.Error()) return } @@ -2369,7 +2371,7 @@ func SearchIssues(ctx *context.Context) { issuesOpt.ReviewRequestedID = ctxUserID } - if issues, err = issues_model.Issues(issuesOpt); err != nil { + if issues, err = issues_model.Issues(ctx, issuesOpt); err != nil { ctx.Error(http.StatusInternalServerError, "Issues", err.Error()) return } @@ -2377,14 +2379,14 @@ func SearchIssues(ctx *context.Context) { issuesOpt.ListOptions = db.ListOptions{ Page: -1, } - if filteredCount, err = issues_model.CountIssues(issuesOpt); err != nil { + if filteredCount, err = issues_model.CountIssues(ctx, issuesOpt); err != nil { ctx.Error(http.StatusInternalServerError, "CountIssues", err.Error()) return } } ctx.SetTotalCountHeader(filteredCount) - ctx.JSON(http.StatusOK, convert.ToAPIIssueList(issues)) + ctx.JSON(http.StatusOK, convert.ToAPIIssueList(ctx, issues)) } func getUserIDForFilter(ctx *context.Context, queryName string) int64 { @@ -2527,7 +2529,7 @@ func ListIssues(ctx *context.Context) { MentionedID: mentionedByID, } - if issues, err = issues_model.Issues(issuesOpt); err != nil { + if issues, err = issues_model.Issues(ctx, issuesOpt); err != nil { ctx.Error(http.StatusInternalServerError, err.Error()) return } @@ -2535,14 +2537,14 @@ func ListIssues(ctx *context.Context) { issuesOpt.ListOptions = db.ListOptions{ Page: -1, } - if filteredCount, err = issues_model.CountIssues(issuesOpt); err != nil { + if filteredCount, err = issues_model.CountIssues(ctx, issuesOpt); err != nil { ctx.Error(http.StatusInternalServerError, err.Error()) return } } ctx.SetTotalCountHeader(filteredCount) - ctx.JSON(http.StatusOK, convert.ToAPIIssueList(issues)) + ctx.JSON(http.StatusOK, convert.ToAPIIssueList(ctx, issues)) } // UpdateIssueStatus change issue's status @@ -2562,7 +2564,7 @@ func UpdateIssueStatus(ctx *context.Context) { log.Warn("Unrecognized action: %s", action) } - if _, err := issues_model.IssueList(issues).LoadRepositories(); err != nil { + if _, err := issues_model.IssueList(issues).LoadRepositories(ctx); err != nil { ctx.ServerError("LoadRepositories", err) return } @@ -2646,7 +2648,7 @@ func NewComment(ctx *context.Context) { if form.Status == "reopen" && issue.IsPull { pull := issue.PullRequest var err error - pr, err = issues_model.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch, pull.Flow) + pr, err = issues_model.GetUnmergedPullRequest(ctx, pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch, pull.Flow) if err != nil { if !issues_model.IsErrPullRequestNotExist(err) { ctx.ServerError("GetUnmergedPullRequest", err) @@ -2706,7 +2708,7 @@ func NewComment(ctx *context.Context) { return } - comment, err := comment_service.CreateIssueComment(ctx.Doer, ctx.Repo.Repository, issue, form.Content, attachments) + comment, err := issue_service.CreateIssueComment(ctx, ctx.Doer, ctx.Repo.Repository, issue, form.Content, attachments) if err != nil { ctx.ServerError("CreateIssueComment", err) return @@ -2723,7 +2725,7 @@ func UpdateCommentContent(ctx *context.Context) { return } - if err := comment.LoadIssue(); err != nil { + if err := comment.LoadIssue(ctx); err != nil { ctx.NotFoundOrServerError("LoadIssue", issues_model.IsErrIssueNotExist, err) return } @@ -2746,12 +2748,12 @@ func UpdateCommentContent(ctx *context.Context) { }) return } - if err = comment_service.UpdateComment(comment, ctx.Doer, oldContent); err != nil { + if err = issue_service.UpdateComment(ctx, comment, ctx.Doer, oldContent); err != nil { ctx.ServerError("UpdateComment", err) return } - if err := comment.LoadAttachments(); err != nil { + if err := comment.LoadAttachments(ctx); err != nil { ctx.ServerError("LoadAttachments", err) return } @@ -2789,7 +2791,7 @@ func DeleteComment(ctx *context.Context) { return } - if err := comment.LoadIssue(); err != nil { + if err := comment.LoadIssue(ctx); err != nil { ctx.NotFoundOrServerError("LoadIssue", issues_model.IsErrIssueNotExist, err) return } @@ -2802,8 +2804,8 @@ func DeleteComment(ctx *context.Context) { return } - if err = comment_service.DeleteComment(ctx.Doer, comment); err != nil { - ctx.ServerError("DeleteCommentByID", err) + if err = issue_service.DeleteComment(ctx, ctx.Doer, comment); err != nil { + ctx.ServerError("DeleteComment", err) return } @@ -2915,7 +2917,7 @@ func ChangeCommentReaction(ctx *context.Context) { return } - if err := comment.LoadIssue(); err != nil { + if err := comment.LoadIssue(ctx); err != nil { ctx.NotFoundOrServerError("LoadIssue", issues_model.IsErrIssueNotExist, err) return } @@ -3024,7 +3026,7 @@ func filterXRefComments(ctx *context.Context, issue *issues_model.Issue) error { if issues_model.CommentTypeIsRef(c.Type) && c.RefRepoID != issue.RepoID && c.RefRepoID != 0 { var err error // Set RefRepo for description in template - c.RefRepo, err = repo_model.GetRepositoryByID(c.RefRepoID) + c.RefRepo, err = repo_model.GetRepositoryByID(ctx, c.RefRepoID) if err != nil { return err } @@ -3047,7 +3049,7 @@ func GetIssueAttachments(ctx *context.Context) { issue := GetActionIssue(ctx) attachments := make([]*api.Attachment, len(issue.Attachments)) for i := 0; i < len(issue.Attachments); i++ { - attachments[i] = convert.ToReleaseAttachment(issue.Attachments[i]) + attachments[i] = convert.ToAttachment(issue.Attachments[i]) } ctx.JSON(http.StatusOK, attachments) } @@ -3061,12 +3063,12 @@ func GetCommentAttachments(ctx *context.Context) { } attachments := make([]*api.Attachment, 0) if comment.Type == issues_model.CommentTypeComment { - if err := comment.LoadAttachments(); err != nil { + if err := comment.LoadAttachments(ctx); err != nil { ctx.ServerError("LoadAttachments", err) return } for i := 0; i < len(comment.Attachments); i++ { - attachments = append(attachments, convert.ToReleaseAttachment(comment.Attachments[i])) + attachments = append(attachments, convert.ToAttachment(comment.Attachments[i])) } } ctx.JSON(http.StatusOK, attachments) diff --git a/routers/web/repo/issue_content_history.go b/routers/web/repo/issue_content_history.go index a9386d274a..3e6b31f8f7 100644 --- a/routers/web/repo/issue_content_history.go +++ b/routers/web/repo/issue_content_history.go @@ -1,21 +1,21 @@ // 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. +// SPDX-License-Identifier: MIT package repo import ( "bytes" - "fmt" "html" "net/http" "strings" + "code.gitea.io/gitea/models/avatars" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/templates" "code.gitea.io/gitea/modules/timeutil" "github.com/sergi/go-diff/diffmatchpatch" @@ -64,16 +64,20 @@ func GetContentHistoryList(ctx *context.Context) { } else { actionText = ctx.Locale.Tr("repo.issues.content_history.edited") } - timeSinceText := timeutil.TimeSinceUnix(item.EditedUnix, ctx.Locale) username := item.UserName if setting.UI.DefaultShowFullName && strings.TrimSpace(item.UserFullName) != "" { username = strings.TrimSpace(item.UserFullName) } + src := html.EscapeString(item.UserAvatarLink) + class := avatars.DefaultAvatarClass + " mr-3" + name := html.EscapeString(username) + avatarHTML := string(templates.AvatarHTML(src, 28, class, username)) + timeSinceText := string(timeutil.TimeSinceUnix(item.EditedUnix, ctx.Locale)) + results = append(results, map[string]interface{}{ - "name": fmt.Sprintf("%s %s %s", - html.EscapeString(item.UserAvatarLink), html.EscapeString(username), actionText, timeSinceText), + "name": avatarHTML + "" + name + " " + actionText + " " + timeSinceText, "value": item.HistoryID, }) } diff --git a/routers/web/repo/issue_dependency.go b/routers/web/repo/issue_dependency.go index d8d934ea1c..41c127be91 100644 --- a/routers/web/repo/issue_dependency.go +++ b/routers/web/repo/issue_dependency.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/issue_label.go b/routers/web/repo/issue_label.go index 7af415a8fa..01421dc927 100644 --- a/routers/web/repo/issue_label.go +++ b/routers/web/repo/issue_label.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo @@ -75,7 +74,7 @@ func RetrieveLabels(ctx *context.Context) { return } for _, l := range orgLabels { - l.CalOpenOrgIssues(ctx.Repo.Repository.ID, l.ID) + l.CalOpenOrgIssues(ctx, ctx.Repo.Repository.ID, l.ID) } ctx.Data["OrgLabels"] = orgLabels diff --git a/routers/web/repo/issue_label_test.go b/routers/web/repo/issue_label_test.go index ea078e215c..a62d2afaa8 100644 --- a/routers/web/repo/issue_label_test.go +++ b/routers/web/repo/issue_label_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/issue_lock.go b/routers/web/repo/issue_lock.go index a89ea47571..10db968a21 100644 --- a/routers/web/repo/issue_lock.go +++ b/routers/web/repo/issue_lock.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/issue_stopwatch.go b/routers/web/repo/issue_stopwatch.go index 97d4441a27..d2a7a12a1f 100644 --- a/routers/web/repo/issue_stopwatch.go +++ b/routers/web/repo/issue_stopwatch.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/issue_test.go b/routers/web/repo/issue_test.go index ad82fe0f36..f1d0aac72f 100644 --- a/routers/web/repo/issue_test.go +++ b/routers/web/repo/issue_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/issue_timetrack.go b/routers/web/repo/issue_timetrack.go index 817a2c6d20..6e9d3673cf 100644 --- a/routers/web/repo/issue_timetrack.go +++ b/routers/web/repo/issue_timetrack.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/issue_watch.go b/routers/web/repo/issue_watch.go index 5210ecf777..c23dbf0622 100644 --- a/routers/web/repo/issue_watch.go +++ b/routers/web/repo/issue_watch.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/lfs.go b/routers/web/repo/lfs.go index 67cb6837a5..82e0055ab2 100644 --- a/routers/web/repo/lfs.go +++ b/routers/web/repo/lfs.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repo @@ -478,7 +477,7 @@ func LFSPointerFiles(ctx *context.Context) { return err } if !result.Associatable { - associated, err := git_model.LFSObjectIsAssociated(pointerBlob.Oid) + associated, err := git_model.ExistsLFSObject(ctx, pointerBlob.Oid) if err != nil { return err } diff --git a/routers/web/repo/main_test.go b/routers/web/repo/main_test.go index a1ca3c3bc7..e3a09a95bd 100644 --- a/routers/web/repo/main_test.go +++ b/routers/web/repo/main_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/middlewares.go b/routers/web/repo/middlewares.go index c9e8eb4a89..9a4aa3382c 100644 --- a/routers/web/repo/middlewares.go +++ b/routers/web/repo/middlewares.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/migrate.go b/routers/web/repo/migrate.go index 393f8ed3d9..bbc349a0a5 100644 --- a/routers/web/repo/migrate.go +++ b/routers/web/repo/migrate.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/milestone.go b/routers/web/repo/milestone.go index 1e75bd79fb..d712df1001 100644 --- a/routers/web/repo/milestone.go +++ b/routers/web/repo/milestone.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo @@ -74,7 +73,7 @@ func Milestones(ctx *context.Context) { ctx.ServerError("GetMilestones", err) return } - if ctx.Repo.Repository.IsTimetrackerEnabled() { + if ctx.Repo.Repository.IsTimetrackerEnabled(ctx) { if err := miles.LoadTotalTrackedTimes(); err != nil { ctx.ServerError("LoadTotalTrackedTimes", err) return diff --git a/routers/web/repo/packages.go b/routers/web/repo/packages.go index 57db19aa32..83324711da 100644 --- a/routers/web/repo/packages.go +++ b/routers/web/repo/packages.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/patch.go b/routers/web/repo/patch.go index cd731337ba..12b26f38e9 100644 --- a/routers/web/repo/patch.go +++ b/routers/web/repo/patch.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo @@ -109,7 +108,7 @@ func NewDiffPatchPost(ctx *context.Context) { } } - if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(unit.TypePullRequests) { + if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(ctx, unit.TypePullRequests) { ctx.Redirect(ctx.Repo.RepoLink + "/compare/" + util.PathEscapeSegments(ctx.Repo.BranchName) + "..." + util.PathEscapeSegments(form.NewBranchName)) } else { ctx.Redirect(ctx.Repo.RepoLink + "/src/branch/" + util.PathEscapeSegments(branchName) + "/" + util.PathEscapeSegments(form.TreePath)) diff --git a/routers/web/repo/projects.go b/routers/web/repo/projects.go index f054ad6e54..75cd290b8f 100644 --- a/routers/web/repo/projects.go +++ b/routers/web/repo/projects.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo @@ -197,7 +196,7 @@ func DeleteProject(ctx *context.Context) { return } - if err := project_model.DeleteProjectByID(p.ID); err != nil { + if err := project_model.DeleteProjectByID(ctx, p.ID); err != nil { ctx.Flash.Error("DeleteProjectByID: " + err.Error()) } else { ctx.Flash.Success(ctx.Tr("repo.projects.deletion_success")) @@ -297,7 +296,7 @@ func ViewProject(ctx *context.Context) { boards[0].Title = ctx.Tr("repo.projects.type.uncategorized") } - issuesMap, err := issues_model.LoadIssuesFromBoardList(boards) + issuesMap, err := issues_model.LoadIssuesFromBoardList(ctx, boards) if err != nil { ctx.ServerError("LoadIssuesOfBoards", err) return @@ -314,7 +313,7 @@ func ViewProject(ctx *context.Context) { } if len(referencedIds) > 0 { - if linkedPrs, err := issues_model.Issues(&issues_model.IssuesOptions{ + if linkedPrs, err := issues_model.Issues(ctx, &issues_model.IssuesOptions{ IssueIDs: referencedIds, IsPull: util.OptionalBoolTrue, }); err == nil { diff --git a/routers/web/repo/projects_test.go b/routers/web/repo/projects_test.go index 62fb045740..c712902ea9 100644 --- a/routers/web/repo/projects_test.go +++ b/routers/web/repo/projects_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go index 41eac7cc39..bea6bfe433 100644 --- a/routers/web/repo/pull.go +++ b/routers/web/repo/pull.go @@ -1,8 +1,7 @@ // Copyright 2018 The Gitea Authors. // Copyright 2014 The Gogs Authors. // All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package repo @@ -79,7 +78,7 @@ var pullRequestTemplateCandidates = []string{ } func getRepository(ctx *context.Context, repoID int64) *repo_model.Repository { - repo, err := repo_model.GetRepositoryByID(repoID) + repo, err := repo_model.GetRepositoryByID(ctx, repoID) if err != nil { if repo_model.IsErrRepoNotExist(err) { ctx.NotFound("GetRepositoryByID", nil) @@ -160,7 +159,7 @@ func getForkRepository(ctx *context.Context) *repo_model.Repository { if !traverseParentRepo.IsFork { break } - traverseParentRepo, err = repo_model.GetRepositoryByID(traverseParentRepo.ForkID) + traverseParentRepo, err = repo_model.GetRepositoryByID(ctx, traverseParentRepo.ForkID) if err != nil { ctx.ServerError("GetRepositoryByID", err) return nil @@ -228,7 +227,7 @@ func ForkPost(ctx *context.Context) { if !traverseParentRepo.IsFork { break } - traverseParentRepo, err = repo_model.GetRepositoryByID(traverseParentRepo.ForkID) + traverseParentRepo, err = repo_model.GetRepositoryByID(ctx, traverseParentRepo.ForkID) if err != nil { ctx.ServerError("GetRepositoryByID", err) return @@ -281,7 +280,7 @@ func checkPullInfo(ctx *context.Context) *issues_model.Issue { } return nil } - if err = issue.LoadPoster(); err != nil { + if err = issue.LoadPoster(ctx); err != nil { ctx.ServerError("LoadPoster", err) return nil } @@ -297,12 +296,12 @@ func checkPullInfo(ctx *context.Context) *issues_model.Issue { return nil } - if err = issue.LoadPullRequest(); err != nil { + if err = issue.LoadPullRequest(ctx); err != nil { ctx.ServerError("LoadPullRequest", err) return nil } - if err = issue.PullRequest.LoadHeadRepoCtx(ctx); err != nil { + if err = issue.PullRequest.LoadHeadRepo(ctx); err != nil { ctx.ServerError("LoadHeadRepo", err) return nil } @@ -319,12 +318,12 @@ func checkPullInfo(ctx *context.Context) *issues_model.Issue { } func setMergeTarget(ctx *context.Context, pull *issues_model.PullRequest) { - if ctx.Repo.Owner.Name == pull.MustHeadUserName() { + if ctx.Repo.Owner.Name == pull.MustHeadUserName(ctx) { ctx.Data["HeadTarget"] = pull.HeadBranch } else if pull.HeadRepo == nil { - ctx.Data["HeadTarget"] = pull.MustHeadUserName() + ":" + pull.HeadBranch + ctx.Data["HeadTarget"] = pull.MustHeadUserName(ctx) + ":" + pull.HeadBranch } else { - ctx.Data["HeadTarget"] = pull.MustHeadUserName() + "/" + pull.HeadRepo.Name + ":" + pull.HeadBranch + ctx.Data["HeadTarget"] = pull.MustHeadUserName(ctx) + "/" + pull.HeadRepo.Name + ":" + pull.HeadBranch } ctx.Data["BaseTarget"] = pull.BaseBranch ctx.Data["HeadBranchHTMLURL"] = pull.GetHeadBranchHTMLURL() @@ -416,19 +415,19 @@ func PrepareViewPullInfo(ctx *context.Context, issue *issues_model.Issue) *git.C repo := ctx.Repo.Repository pull := issue.PullRequest - if err := pull.LoadHeadRepoCtx(ctx); err != nil { + if err := pull.LoadHeadRepo(ctx); err != nil { ctx.ServerError("LoadHeadRepo", err) return nil } - if err := pull.LoadBaseRepoCtx(ctx); err != nil { + if err := pull.LoadBaseRepo(ctx); err != nil { ctx.ServerError("LoadBaseRepo", err) return nil } setMergeTarget(ctx, pull) - if err := pull.LoadProtectedBranch(); err != nil { + if err := pull.LoadProtectedBranch(ctx); err != nil { ctx.ServerError("LoadProtectedBranch", err) return nil } @@ -606,7 +605,7 @@ func PrepareViewPullInfo(ctx *context.Context, issue *issues_model.Issue) *git.C if pull.IsWorkInProgress() { ctx.Data["IsPullWorkInProgress"] = true - ctx.Data["WorkInProgressPrefix"] = pull.GetWorkInProgressPrefix() + ctx.Data["WorkInProgressPrefix"] = pull.GetWorkInProgressPrefix(ctx) } if pull.IsFilesConflicted() { @@ -740,7 +739,7 @@ func ViewPullFiles(ctx *context.Context) { return } - if err = pull.LoadProtectedBranch(); err != nil { + if err = pull.LoadProtectedBranch(ctx); err != nil { ctx.ServerError("LoadProtectedBranch", err) return } @@ -834,11 +833,11 @@ func UpdatePullRequest(ctx *context.Context) { rebase := ctx.FormString("style") == "rebase" - if err := issue.PullRequest.LoadBaseRepoCtx(ctx); err != nil { + if err := issue.PullRequest.LoadBaseRepo(ctx); err != nil { ctx.ServerError("LoadBaseRepo", err) return } - if err := issue.PullRequest.LoadHeadRepoCtx(ctx); err != nil { + if err := issue.PullRequest.LoadHeadRepo(ctx); err != nil { ctx.ServerError("LoadHeadRepo", err) return } @@ -974,7 +973,7 @@ func MergePullRequest(ctx *context.Context) { message := strings.TrimSpace(form.MergeTitleField) if len(message) == 0 { var err error - message, err = pull_service.GetDefaultMergeMessage(ctx.Repo.GitRepo, pr, repo_model.MergeStyle(form.Do)) + message, err = pull_service.GetDefaultMergeMessage(ctx, ctx.Repo.GitRepo, pr, repo_model.MergeStyle(form.Do)) if err != nil { ctx.ServerError("GetDefaultMergeMessage", err) return @@ -1296,14 +1295,14 @@ func CleanUpPullRequest(ctx *context.Context) { return } - if err := pr.LoadHeadRepoCtx(ctx); err != nil { + if err := pr.LoadHeadRepo(ctx); err != nil { ctx.ServerError("LoadHeadRepo", err) return } else if pr.HeadRepo == nil { // Forked repository has already been deleted ctx.NotFound("CleanUpPullRequest", nil) return - } else if err = pr.LoadBaseRepoCtx(ctx); err != nil { + } else if err = pr.LoadBaseRepo(ctx); err != nil { ctx.ServerError("LoadBaseRepo", err) return } else if err = pr.HeadRepo.GetOwner(ctx); err != nil { @@ -1499,7 +1498,7 @@ func UpdatePullRequestTarget(ctx *context.Context) { } return } - notification.NotifyPullRequestChangeTargetBranch(ctx.Doer, pr, targetBranch) + notification.NotifyPullRequestChangeTargetBranch(ctx, ctx.Doer, pr, targetBranch) ctx.JSON(http.StatusOK, map[string]interface{}{ "base_branch": pr.BaseBranch, diff --git a/routers/web/repo/pull_review.go b/routers/web/repo/pull_review.go index bc64f35472..9f4cdde864 100644 --- a/routers/web/repo/pull_review.go +++ b/routers/web/repo/pull_review.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo @@ -114,7 +113,7 @@ func UpdateResolveConversation(ctx *context.Context) { return } - if err = comment.LoadIssue(); err != nil { + if err = comment.LoadIssue(ctx); err != nil { ctx.ServerError("comment.LoadIssue", err) return } @@ -169,7 +168,7 @@ func renderConversation(ctx *context.Context, comment *issues_model.Comment) { ctx.Data["comments"] = comments ctx.Data["CanMarkConversation"] = true ctx.Data["Issue"] = comment.Issue - if err = comment.Issue.LoadPullRequest(); err != nil { + if err = comment.Issue.LoadPullRequest(ctx); err != nil { ctx.ServerError("comment.Issue.LoadPullRequest", err) return } diff --git a/routers/web/repo/release.go b/routers/web/repo/release.go index 0cb85f3798..2047a1cfb9 100644 --- a/routers/web/repo/release.go +++ b/routers/web/repo/release.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo @@ -130,13 +129,13 @@ func releasesOrTags(ctx *context.Context, isTagList bool) { opts.IncludeDrafts = writeAccess } - releases, err := repo_model.GetReleasesByRepoID(ctx.Repo.Repository.ID, opts) + releases, err := repo_model.GetReleasesByRepoID(ctx, ctx.Repo.Repository.ID, opts) if err != nil { ctx.ServerError("GetReleasesByRepoID", err) return } - count, err := repo_model.GetReleaseCountByRepoID(ctx.Repo.Repository.ID, opts) + count, err := repo_model.GetReleaseCountByRepoID(ctx, ctx.Repo.Repository.ID, opts) if err != nil { ctx.ServerError("GetReleaseCountByRepoID", err) return @@ -157,7 +156,7 @@ func releasesOrTags(ctx *context.Context, isTagList bool) { for _, r := range releases { if r.Publisher, ok = cacheUsers[r.PublisherID]; !ok { - r.Publisher, err = user_model.GetUserByID(r.PublisherID) + r.Publisher, err = user_model.GetUserByID(ctx, r.PublisherID) if err != nil { if user_model.IsErrUserNotExist(err) { r.Publisher = user_model.NewGhostUser() @@ -224,7 +223,7 @@ func SingleRelease(ctx *context.Context) { return } - release.Publisher, err = user_model.GetUserByID(release.PublisherID) + release.Publisher, err = user_model.GetUserByID(ctx, release.PublisherID) if err != nil { if user_model.IsErrUserNotExist(err) { release.Publisher = user_model.NewGhostUser() @@ -266,7 +265,7 @@ func LatestRelease(ctx *context.Context) { return } - if err := release.LoadAttributes(); err != nil { + if err := release.LoadAttributes(ctx); err != nil { ctx.ServerError("LoadAttributes", err) return } @@ -289,7 +288,7 @@ func NewRelease(ctx *context.Context) { if rel != nil { rel.Repo = ctx.Repo.Repository - if err := rel.LoadAttributes(); err != nil { + if err := rel.LoadAttributes(ctx); err != nil { ctx.ServerError("LoadAttributes", err) return } @@ -454,7 +453,7 @@ func EditRelease(ctx *context.Context) { ctx.Data["IsDraft"] = rel.IsDraft rel.Repo = ctx.Repo.Repository - if err := rel.LoadAttributes(); err != nil { + if err := rel.LoadAttributes(ctx); err != nil { ctx.ServerError("LoadAttributes", err) return } diff --git a/routers/web/repo/release_test.go b/routers/web/repo/release_test.go index 16371fc860..81ae58178f 100644 --- a/routers/web/repo/release_test.go +++ b/routers/web/repo/release_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/render.go b/routers/web/repo/render.go index 28a6d2f429..f07b4e8c11 100644 --- a/routers/web/repo/render.go +++ b/routers/web/repo/render.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/repo.go b/routers/web/repo/repo.go index 3e746d3f05..8856ee6626 100644 --- a/routers/web/repo/repo.go +++ b/routers/web/repo/repo.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repo @@ -84,7 +83,7 @@ func checkContextUser(ctx *context.Context, uid int64) *user_model.User { return ctx.Doer } - org, err := user_model.GetUserByID(uid) + org, err := user_model.GetUserByID(ctx, uid) if user_model.IsErrUserNotExist(err) { return ctx.Doer } @@ -150,7 +149,7 @@ func Create(ctx *context.Context) { ctx.Data["repo_template_name"] = ctx.Tr("repo.template_select") templateID := ctx.FormInt64("template_id") if templateID > 0 { - templateRepo, err := repo_model.GetRepositoryByID(templateID) + templateRepo, err := repo_model.GetRepositoryByID(ctx, templateID) if err == nil && access_model.CheckRepoUnitUser(ctx, templateRepo, ctxUser, unit.TypeCode) { ctx.Data["repo_template"] = templateID ctx.Data["repo_template_name"] = templateRepo.Name @@ -315,12 +314,12 @@ func Action(ctx *context.Context) { } func acceptOrRejectRepoTransfer(ctx *context.Context, accept bool) error { - repoTransfer, err := models.GetPendingRepositoryTransfer(ctx.Repo.Repository) + repoTransfer, err := models.GetPendingRepositoryTransfer(ctx, ctx.Repo.Repository) if err != nil { return err } - if err := repoTransfer.LoadAttributes(); err != nil { + if err := repoTransfer.LoadAttributes(ctx); err != nil { return err } @@ -334,7 +333,7 @@ func acceptOrRejectRepoTransfer(ctx *context.Context, accept bool) error { ctx.Repo.GitRepo = nil } - if err := repo_service.TransferOwnership(repoTransfer.Doer, repoTransfer.Recipient, ctx.Repo.Repository, repoTransfer.Teams); err != nil { + if err := repo_service.TransferOwnership(ctx, repoTransfer.Doer, repoTransfer.Recipient, ctx.Repo.Repository, repoTransfer.Teams); err != nil { return err } ctx.Flash.Success(ctx.Tr("repo.settings.transfer.success")) @@ -426,7 +425,10 @@ func download(ctx *context.Context, archiveName string, archiver *repo_model.Rep } defer fr.Close() - ctx.ServeContent(downloadName, fr, archiver.CreatedUnix.AsLocalTime()) + ctx.ServeContent(fr, &context.ServeHeaderOptions{ + Filename: downloadName, + LastModified: archiver.CreatedUnix.AsLocalTime(), + }) } // InitiateDownload will enqueue an archival request, as needed. It may submit @@ -540,7 +542,7 @@ func SearchRepo(ctx *context.Context) { } var err error - repos, count, err := repo_model.SearchRepository(opts) + repos, count, err := repo_model.SearchRepository(ctx, opts) if err != nil { ctx.JSON(http.StatusInternalServerError, api.SearchError{ OK: false, diff --git a/routers/web/repo/search.go b/routers/web/repo/search.go index 3d1835c7c3..137f38d409 100644 --- a/routers/web/repo/search.go +++ b/routers/web/repo/search.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/setting.go b/routers/web/repo/setting.go index 2b5691ce88..f35adcaa10 100644 --- a/routers/web/repo/setting.go +++ b/routers/web/repo/setting.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo @@ -398,6 +397,15 @@ func SettingsPost(ctx *context.Context) { repoChanged = true } + if form.EnableCode && !unit_model.TypeCode.UnitGlobalDisabled() { + units = append(units, repo_model.RepoUnit{ + RepoID: repo.ID, + Type: unit_model.TypeCode, + }) + } else if !unit_model.TypeCode.UnitGlobalDisabled() { + deleteUnitTypes = append(deleteUnitTypes, unit_model.TypeCode) + } + if form.EnableWiki && form.EnableExternalWiki && !unit_model.TypeExternalWiki.UnitGlobalDisabled() { if !validation.IsValidExternalURL(form.ExternalWikiURL) { ctx.Flash.Error(ctx.Tr("repo.settings.external_wiki_url_error")) @@ -690,7 +698,7 @@ func SettingsPost(ctx *context.Context) { ctx.Repo.GitRepo = nil } - if err := repo_service.StartRepositoryTransfer(ctx.Doer, newOwner, repo, nil); err != nil { + if err := repo_service.StartRepositoryTransfer(ctx, ctx.Doer, newOwner, repo, nil); err != nil { if repo_model.IsErrRepoAlreadyExist(err) { ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplSettingsOptions, nil) } else if models.IsErrRepoTransferInProgress(err) { @@ -712,7 +720,7 @@ func SettingsPost(ctx *context.Context) { return } - repoTransfer, err := models.GetPendingRepositoryTransfer(ctx.Repo.Repository) + repoTransfer, err := models.GetPendingRepositoryTransfer(ctx, ctx.Repo.Repository) if err != nil { if models.IsErrNoPendingTransfer(err) { ctx.Flash.Error("repo.settings.transfer_abort_invalid") @@ -724,7 +732,7 @@ func SettingsPost(ctx *context.Context) { return } - if err := repoTransfer.LoadAttributes(); err != nil { + if err := repoTransfer.LoadAttributes(ctx); err != nil { ctx.ServerError("LoadRecipient", err) return } @@ -930,7 +938,7 @@ func CollaborationPost(ctx *context.Context) { } } - if err = repo_module.AddCollaborator(ctx.Repo.Repository, u); err != nil { + if err = repo_module.AddCollaborator(ctx, ctx.Repo.Repository, u); err != nil { ctx.ServerError("AddCollaborator", err) return } @@ -946,6 +954,7 @@ func CollaborationPost(ctx *context.Context) { // ChangeCollaborationAccessMode response for changing access of a collaboration func ChangeCollaborationAccessMode(ctx *context.Context) { if err := repo_model.ChangeCollaborationAccessMode( + ctx, ctx.Repo.Repository, ctx.FormInt64("uid"), perm.AccessMode(ctx.FormInt("mode"))); err != nil { diff --git a/routers/web/repo/setting_protected_branch.go b/routers/web/repo/setting_protected_branch.go index c4cd3486aa..975873a9ef 100644 --- a/routers/web/repo/setting_protected_branch.go +++ b/routers/web/repo/setting_protected_branch.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/settings_test.go b/routers/web/repo/settings_test.go index 4acd7df5b8..3bb202505c 100644 --- a/routers/web/repo/settings_test.go +++ b/routers/web/repo/settings_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/tag.go b/routers/web/repo/tag.go index f63a50782b..26df1dbf6c 100644 --- a/routers/web/repo/tag.go +++ b/routers/web/repo/tag.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repo @@ -124,7 +123,7 @@ func DeleteProtectedTagPost(ctx *context.Context) { return } - if err := git_model.DeleteProtectedTag(pt); err != nil { + if err := git_model.DeleteProtectedTag(ctx, pt); err != nil { ctx.ServerError("DeleteProtectedTag", err) return } @@ -137,7 +136,7 @@ func setTagsContext(ctx *context.Context) error { ctx.Data["Title"] = ctx.Tr("repo.settings") ctx.Data["PageIsSettingsTags"] = true - protectedTags, err := git_model.GetProtectedTags(ctx.Repo.Repository.ID) + protectedTags, err := git_model.GetProtectedTags(ctx, ctx.Repo.Repository.ID) if err != nil { ctx.ServerError("GetProtectedTags", err) return err diff --git a/routers/web/repo/topic.go b/routers/web/repo/topic.go index efbfc62d56..4c0b38bd91 100644 --- a/routers/web/repo/topic.go +++ b/routers/web/repo/topic.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/treelist.go b/routers/web/repo/treelist.go index 80f43a0c40..c364e7090f 100644 --- a/routers/web/repo/treelist.go +++ b/routers/web/repo/treelist.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/view.go b/routers/web/repo/view.go index d35ec48df0..f139a971fc 100644 --- a/routers/web/repo/view.go +++ b/routers/web/repo/view.go @@ -1,7 +1,6 @@ // Copyright 2017 The Gitea Authors. All rights reserved. // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package repo @@ -242,18 +241,19 @@ func findReadmeFile(ctx *context.Context, entries git.Entries, treeLink string) return readmeFile, readmeTreelink } -func renderReadmeFile(ctx *context.Context, readmeFile *namedBlob, readmeTreelink string) { - ctx.Data["RawFileLink"] = "" - ctx.Data["ReadmeInList"] = true - ctx.Data["ReadmeExist"] = true - ctx.Data["FileIsSymlink"] = readmeFile.isSymlink +type fileInfo struct { + isTextFile bool + isLFSFile bool + fileSize int64 + lfsMeta *lfs.Pointer + st typesniffer.SniffedType +} - dataRc, err := readmeFile.blob.DataAsync() +func getFileReader(repoID int64, blob *git.Blob) ([]byte, io.ReadCloser, *fileInfo, error) { + dataRc, err := blob.DataAsync() if err != nil { - ctx.ServerError("Data", err) - return + return nil, nil, nil, err } - defer dataRc.Close() buf := make([]byte, 1024) n, _ := util.ReadAtMost(dataRc, buf) @@ -262,67 +262,75 @@ func renderReadmeFile(ctx *context.Context, readmeFile *namedBlob, readmeTreelin st := typesniffer.DetectContentType(buf) isTextFile := st.IsText() - ctx.Data["FileIsText"] = isTextFile - ctx.Data["FileName"] = readmeFile.name - fileSize := int64(0) - isLFSFile := false - ctx.Data["IsLFSFile"] = false - // FIXME: what happens when README file is an image? - if isTextFile && setting.LFS.StartServer { - pointer, _ := lfs.ReadPointerFromBuffer(buf) - if pointer.IsValid() { - meta, err := git_model.GetLFSMetaObjectByOid(ctx.Repo.Repository.ID, pointer.Oid) - if err != nil && err != git_model.ErrLFSObjectNotExist { - ctx.ServerError("GetLFSMetaObject", err) - return - } - if meta != nil { - ctx.Data["IsLFSFile"] = true - isLFSFile = true - - // OK read the lfs object - var err error - dataRc, err = lfs.ReadMetaObject(pointer) - if err != nil { - ctx.ServerError("ReadMetaObject", err) - return - } - defer dataRc.Close() - - buf = make([]byte, 1024) - n, err = util.ReadAtMost(dataRc, buf) - if err != nil { - ctx.ServerError("Data", err) - return - } - buf = buf[:n] - - st = typesniffer.DetectContentType(buf) - isTextFile = st.IsText() - ctx.Data["IsTextFile"] = isTextFile - - fileSize = meta.Size - ctx.Data["FileSize"] = meta.Size - filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(readmeFile.name)) - ctx.Data["RawFileLink"] = fmt.Sprintf("%s.git/info/lfs/objects/%s/%s", ctx.Repo.Repository.HTMLURL(), url.PathEscape(meta.Oid), url.PathEscape(filenameBase64)) - } - } + if !isTextFile || !setting.LFS.StartServer { + return buf, dataRc, &fileInfo{isTextFile, false, blob.Size(), nil, st}, nil } - if !isTextFile { + pointer, _ := lfs.ReadPointerFromBuffer(buf) + if !pointer.IsValid() { // fallback to plain file + return buf, dataRc, &fileInfo{isTextFile, false, blob.Size(), nil, st}, nil + } + + meta, err := git_model.GetLFSMetaObjectByOid(repoID, pointer.Oid) + if err != git_model.ErrLFSObjectNotExist { // fallback to plain file + return buf, dataRc, &fileInfo{isTextFile, false, blob.Size(), nil, st}, nil + } + + dataRc.Close() + if err != nil { + return nil, nil, nil, err + } + + dataRc, err = lfs.ReadMetaObject(pointer) + if err != nil { + return nil, nil, nil, err + } + + buf = make([]byte, 1024) + n, err = util.ReadAtMost(dataRc, buf) + if err != nil { + dataRc.Close() + return nil, nil, nil, err + } + buf = buf[:n] + + st = typesniffer.DetectContentType(buf) + + return buf, dataRc, &fileInfo{st.IsText(), true, meta.Size, &meta.Pointer, st}, nil +} + +func renderReadmeFile(ctx *context.Context, readmeFile *namedBlob, readmeTreelink string) { + ctx.Data["RawFileLink"] = "" + ctx.Data["ReadmeInList"] = true + ctx.Data["ReadmeExist"] = true + ctx.Data["FileIsSymlink"] = readmeFile.isSymlink + + buf, dataRc, fInfo, err := getFileReader(ctx.Repo.Repository.ID, readmeFile.blob) + if err != nil { + ctx.ServerError("getFileReader", err) + return + } + defer dataRc.Close() + + ctx.Data["FileIsText"] = fInfo.isTextFile + ctx.Data["FileName"] = readmeFile.name + ctx.Data["IsLFSFile"] = fInfo.isLFSFile + + if fInfo.isLFSFile { + filenameBase64 := base64.RawURLEncoding.EncodeToString([]byte(readmeFile.name)) + ctx.Data["RawFileLink"] = fmt.Sprintf("%s.git/info/lfs/objects/%s/%s", ctx.Repo.Repository.HTMLURL(), url.PathEscape(fInfo.lfsMeta.Oid), url.PathEscape(filenameBase64)) + } + + if !fInfo.isTextFile { return } - if !isLFSFile { - fileSize = readmeFile.blob.Size() - } - - if fileSize >= setting.UI.MaxDisplayFileSize { + if fInfo.fileSize >= setting.UI.MaxDisplayFileSize { // Pretend that this is a normal text file to display 'This file is too large to be shown' ctx.Data["IsFileTooLarge"] = true ctx.Data["IsTextFile"] = true - ctx.Data["FileSize"] = fileSize + ctx.Data["FileSize"] = fInfo.fileSize return } @@ -363,16 +371,14 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st ctx.Data["IsViewFile"] = true ctx.Data["HideRepoInfo"] = true blob := entry.Blob() - dataRc, err := blob.DataAsync() + buf, dataRc, fInfo, err := getFileReader(ctx.Repo.Repository.ID, blob) if err != nil { - ctx.ServerError("DataAsync", err) + ctx.ServerError("getFileReader", err) return } defer dataRc.Close() ctx.Data["Title"] = ctx.Tr("repo.file.title", ctx.Repo.Repository.Name+"/"+path.Base(ctx.Repo.TreePath), ctx.Repo.RefName) - - fileSize := blob.Size() ctx.Data["FileIsSymlink"] = entry.IsLink() ctx.Data["FileName"] = blob.Name() ctx.Data["RawFileLink"] = rawLink + "/" + util.PathEscapeSegments(ctx.Repo.TreePath) @@ -382,68 +388,31 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st ctx.Data["FileError"] = editorconfigErr } - buf := make([]byte, 1024) - n, _ := util.ReadAtMost(dataRc, buf) - buf = buf[:n] - - st := typesniffer.DetectContentType(buf) - isTextFile := st.IsText() - - isLFSFile := false isDisplayingSource := ctx.FormString("display") == "source" isDisplayingRendered := !isDisplayingSource - // Check for LFS meta file - if isTextFile && setting.LFS.StartServer { - pointer, _ := lfs.ReadPointerFromBuffer(buf) - if pointer.IsValid() { - meta, err := git_model.GetLFSMetaObjectByOid(ctx.Repo.Repository.ID, pointer.Oid) - if err != nil && err != git_model.ErrLFSObjectNotExist { - ctx.ServerError("GetLFSMetaObject", err) - return - } - if meta != nil { - isLFSFile = true - - // OK read the lfs object - var err error - dataRc, err = lfs.ReadMetaObject(pointer) - if err != nil { - ctx.ServerError("ReadMetaObject", err) - return - } - defer dataRc.Close() - - buf = make([]byte, 1024) - n, err = util.ReadAtMost(dataRc, buf) - if err != nil { - ctx.ServerError("Data", err) - return - } - buf = buf[:n] - - st = typesniffer.DetectContentType(buf) - isTextFile = st.IsText() - - fileSize = meta.Size - ctx.Data["RawFileLink"] = ctx.Repo.RepoLink + "/media/" + ctx.Repo.BranchNameSubURL() + "/" + util.PathEscapeSegments(ctx.Repo.TreePath) - } - } + if fInfo.isLFSFile { + ctx.Data["RawFileLink"] = ctx.Repo.RepoLink + "/media/" + ctx.Repo.BranchNameSubURL() + "/" + util.PathEscapeSegments(ctx.Repo.TreePath) } - isRepresentableAsText := st.IsRepresentableAsText() + isRepresentableAsText := fInfo.st.IsRepresentableAsText() if !isRepresentableAsText { // If we can't show plain text, always try to render. isDisplayingSource = false isDisplayingRendered = true } - ctx.Data["IsLFSFile"] = isLFSFile - ctx.Data["FileSize"] = fileSize - ctx.Data["IsTextFile"] = isTextFile + ctx.Data["IsLFSFile"] = fInfo.isLFSFile + ctx.Data["FileSize"] = fInfo.fileSize + ctx.Data["IsTextFile"] = fInfo.isTextFile ctx.Data["IsRepresentableAsText"] = isRepresentableAsText ctx.Data["IsDisplayingSource"] = isDisplayingSource ctx.Data["IsDisplayingRendered"] = isDisplayingRendered - ctx.Data["IsTextSource"] = isTextFile || isDisplayingSource + + isTextSource := fInfo.isTextFile || isDisplayingSource + ctx.Data["IsTextSource"] = isTextSource + if isTextSource { + ctx.Data["CanCopyContent"] = true + } // Check LFS Lock lfsLock, err := git_model.GetTreePathLock(ctx.Repo.Repository.ID, ctx.Repo.TreePath) @@ -453,7 +422,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st return } if lfsLock != nil { - u, err := user_model.GetUserByID(lfsLock.OwnerID) + u, err := user_model.GetUserByID(ctx, lfsLock.OwnerID) if err != nil { ctx.ServerError("GetTreePathLock", err) return @@ -464,7 +433,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st } // Assume file is not editable first. - if isLFSFile { + if fInfo.isLFSFile { ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_lfs_files") } else if !isRepresentableAsText { ctx.Data["EditFileTooltip"] = ctx.Tr("repo.editor.cannot_edit_non_text_files") @@ -472,12 +441,13 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st switch { case isRepresentableAsText: - if st.IsSvgImage() { + if fInfo.st.IsSvgImage() { ctx.Data["IsImageFile"] = true + ctx.Data["CanCopyContent"] = true ctx.Data["HasSourceRenderedToggle"] = true } - if fileSize >= setting.UI.MaxDisplayFileSize { + if fInfo.fileSize >= setting.UI.MaxDisplayFileSize { ctx.Data["IsFileTooLarge"] = true break } @@ -568,7 +538,8 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st language = "" } } - fileContent, err := highlight.File(blob.Name(), language, buf) + fileContent, lexerName, err := highlight.File(blob.Name(), language, buf) + ctx.Data["LexerName"] = lexerName if err != nil { log.Error("highlight.File failed, fallback to plain text: %v", err) fileContent = highlight.PlainText(buf) @@ -583,7 +554,7 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st ctx.Data["FileContent"] = fileContent ctx.Data["LineEscapeStatus"] = statuses } - if !isLFSFile { + if !fInfo.isLFSFile { if ctx.Repo.CanEnableEditor(ctx.Doer) { if lfsLock != nil && lfsLock.OwnerID != ctx.Doer.ID { ctx.Data["CanEditFile"] = false @@ -599,16 +570,17 @@ func renderFile(ctx *context.Context, entry *git.TreeEntry, treeLink, rawLink st } } - case st.IsPDF(): + case fInfo.st.IsPDF(): ctx.Data["IsPDFFile"] = true - case st.IsVideo(): + case fInfo.st.IsVideo(): ctx.Data["IsVideoFile"] = true - case st.IsAudio(): + case fInfo.st.IsAudio(): ctx.Data["IsAudioFile"] = true - case st.IsImage() && (setting.UI.SVG.Enabled || !st.IsSvgImage()): + case fInfo.st.IsImage() && (setting.UI.SVG.Enabled || !fInfo.st.IsSvgImage()): ctx.Data["IsImageFile"] = true + ctx.Data["CanCopyContent"] = true default: - if fileSize >= setting.UI.MaxDisplayFileSize { + if fInfo.fileSize >= setting.UI.MaxDisplayFileSize { ctx.Data["IsFileTooLarge"] = true break } @@ -730,15 +702,56 @@ func checkHomeCodeViewable(ctx *context.Context) { ctx.NotFound("Home", fmt.Errorf(ctx.Tr("units.error.no_unit_allowed_repo"))) } -// Home render repository home page -func Home(ctx *context.Context) { - isFeed, _, showFeedType := feed.GetFeedType(ctx.Params(":reponame"), ctx.Req) - if isFeed { - feed.ShowRepoFeed(ctx, ctx.Repo.Repository, showFeedType) +func checkCitationFile(ctx *context.Context, entry *git.TreeEntry) { + if entry.Name() != "" { return } + tree, err := ctx.Repo.Commit.SubTree(ctx.Repo.TreePath) + if err != nil { + ctx.NotFoundOrServerError("Repo.Commit.SubTree", git.IsErrNotExist, err) + return + } + allEntries, err := tree.ListEntries() + if err != nil { + ctx.ServerError("ListEntries", err) + return + } + for _, entry := range allEntries { + if entry.Name() == "CITATION.cff" || entry.Name() == "CITATION.bib" { + ctx.Data["CitiationExist"] = true + // Read Citation file contents + blob := entry.Blob() + dataRc, err := blob.DataAsync() + if err != nil { + ctx.ServerError("DataAsync", err) + return + } + defer dataRc.Close() + buf := make([]byte, 1024) + n, err := util.ReadAtMost(dataRc, buf) + if err != nil { + ctx.ServerError("ReadAtMost", err) + return + } + buf = buf[:n] + ctx.PageData["citationFileContent"] = string(buf) + break + } + } +} - ctx.Data["FeedURL"] = ctx.Repo.Repository.HTMLURL() +// Home render repository home page +func Home(ctx *context.Context) { + if setting.EnableFeed { + isFeed, _, showFeedType := feed.GetFeedType(ctx.Params(":reponame"), ctx.Req) + if isFeed { + feed.ShowRepoFeed(ctx, ctx.Repo.Repository, showFeedType) + return + } + + ctx.Data["EnableFeed"] = true + ctx.Data["FeedURL"] = ctx.Repo.Repository.HTMLURL() + } checkHomeCodeViewable(ctx) if ctx.Written() { @@ -954,6 +967,13 @@ func renderCode(ctx *context.Context) { return } + if !ctx.Repo.Repository.IsEmpty { + checkCitationFile(ctx, entry) + if ctx.Written() { + return + } + } + renderLanguageStats(ctx) if ctx.Written() { return diff --git a/routers/web/repo/view_test.go b/routers/web/repo/view_test.go index 803906b217..73ba118823 100644 --- a/routers/web/repo/view_test.go +++ b/routers/web/repo/view_test.go @@ -1,7 +1,6 @@ // Copyright 2017 The Gitea Authors. All rights reserved. // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/repo/webhook.go b/routers/web/repo/webhook.go index 5496496e80..18d71c6435 100644 --- a/routers/web/repo/webhook.go +++ b/routers/web/repo/webhook.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo @@ -685,7 +684,7 @@ func TestWebhook(ctx *context.Context) { Commits: []*api.PayloadCommit{apiCommit}, TotalCommits: 1, HeadCommit: apiCommit, - Repo: convert.ToRepo(ctx.Repo.Repository, perm.AccessModeNone), + Repo: convert.ToRepo(ctx, ctx.Repo.Repository, perm.AccessModeNone), Pusher: apiUser, Sender: apiUser, } diff --git a/routers/web/repo/wiki.go b/routers/web/repo/wiki.go index a10e12ee63..b50a4be802 100644 --- a/routers/web/repo/wiki.go +++ b/routers/web/repo/wiki.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package repo @@ -60,7 +59,7 @@ func MustEnableWiki(ctx *context.Context) { return } - unit, err := ctx.Repo.Repository.GetUnit(unit.TypeExternalWiki) + unit, err := ctx.Repo.Repository.GetUnit(ctx, unit.TypeExternalWiki) if err == nil { ctx.Redirect(unit.ExternalWikiConfig().ExternalWikiURL) return @@ -706,7 +705,7 @@ func NewWikiPost(ctx *context.Context) { return } - notification.NotifyNewWikiPage(ctx.Doer, ctx.Repo.Repository, wikiName, form.Message) + notification.NotifyNewWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, wikiName, form.Message) ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + wiki_service.NameToSubURL(wikiName)) } @@ -750,7 +749,7 @@ func EditWikiPost(ctx *context.Context) { return } - notification.NotifyEditWikiPage(ctx.Doer, ctx.Repo.Repository, newWikiName, form.Message) + notification.NotifyEditWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, newWikiName, form.Message) ctx.Redirect(ctx.Repo.RepoLink + "/wiki/" + wiki_service.NameToSubURL(newWikiName)) } @@ -767,7 +766,7 @@ func DeleteWikiPagePost(ctx *context.Context) { return } - notification.NotifyDeleteWikiPage(ctx.Doer, ctx.Repo.Repository, wikiName) + notification.NotifyDeleteWikiPage(ctx, ctx.Doer, ctx.Repo.Repository, wikiName) ctx.JSON(http.StatusOK, map[string]interface{}{ "redirect": ctx.Repo.RepoLink + "/wiki/", diff --git a/routers/web/repo/wiki_test.go b/routers/web/repo/wiki_test.go index 34f466854f..4699f5379a 100644 --- a/routers/web/repo/wiki_test.go +++ b/routers/web/repo/wiki_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repo diff --git a/routers/web/shared/packages/packages.go b/routers/web/shared/packages/packages.go new file mode 100644 index 0000000000..b9aa40bdd2 --- /dev/null +++ b/routers/web/shared/packages/packages.go @@ -0,0 +1,225 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package packages + +import ( + "fmt" + "net/http" + "time" + + "code.gitea.io/gitea/models/db" + packages_model "code.gitea.io/gitea/models/packages" + user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/util" + "code.gitea.io/gitea/modules/web" + "code.gitea.io/gitea/services/forms" + container_service "code.gitea.io/gitea/services/packages/container" +) + +func SetPackagesContext(ctx *context.Context, owner *user_model.User) { + pcrs, err := packages_model.GetCleanupRulesByOwner(ctx, owner.ID) + if err != nil { + ctx.ServerError("GetCleanupRulesByOwner", err) + return + } + + ctx.Data["CleanupRules"] = pcrs +} + +func SetRuleAddContext(ctx *context.Context) { + setRuleEditContext(ctx, nil) +} + +func SetRuleEditContext(ctx *context.Context, owner *user_model.User) { + pcr := getCleanupRuleByContext(ctx, owner) + if pcr == nil { + return + } + + setRuleEditContext(ctx, pcr) +} + +func setRuleEditContext(ctx *context.Context, pcr *packages_model.PackageCleanupRule) { + ctx.Data["IsEditRule"] = pcr != nil + + if pcr == nil { + pcr = &packages_model.PackageCleanupRule{} + } + ctx.Data["CleanupRule"] = pcr + ctx.Data["AvailableTypes"] = packages_model.TypeList +} + +func PerformRuleAddPost(ctx *context.Context, owner *user_model.User, redirectURL string, template base.TplName) { + performRuleEditPost(ctx, owner, nil, redirectURL, template) +} + +func PerformRuleEditPost(ctx *context.Context, owner *user_model.User, redirectURL string, template base.TplName) { + pcr := getCleanupRuleByContext(ctx, owner) + if pcr == nil { + return + } + + form := web.GetForm(ctx).(*forms.PackageCleanupRuleForm) + + if form.Action == "remove" { + if err := packages_model.DeleteCleanupRuleByID(ctx, pcr.ID); err != nil { + ctx.ServerError("DeleteCleanupRuleByID", err) + return + } + + ctx.Flash.Success(ctx.Tr("packages.owner.settings.cleanuprules.success.delete")) + ctx.Redirect(redirectURL) + } else { + performRuleEditPost(ctx, owner, pcr, redirectURL, template) + } +} + +func performRuleEditPost(ctx *context.Context, owner *user_model.User, pcr *packages_model.PackageCleanupRule, redirectURL string, template base.TplName) { + isEditRule := pcr != nil + + if pcr == nil { + pcr = &packages_model.PackageCleanupRule{} + } + + form := web.GetForm(ctx).(*forms.PackageCleanupRuleForm) + + pcr.Enabled = form.Enabled + pcr.OwnerID = owner.ID + pcr.KeepCount = form.KeepCount + pcr.KeepPattern = form.KeepPattern + pcr.RemoveDays = form.RemoveDays + pcr.RemovePattern = form.RemovePattern + pcr.MatchFullName = form.MatchFullName + + ctx.Data["IsEditRule"] = isEditRule + ctx.Data["CleanupRule"] = pcr + ctx.Data["AvailableTypes"] = packages_model.TypeList + + if ctx.HasError() { + ctx.HTML(http.StatusOK, template) + return + } + + if isEditRule { + if err := packages_model.UpdateCleanupRule(ctx, pcr); err != nil { + ctx.ServerError("UpdateCleanupRule", err) + return + } + } else { + pcr.Type = packages_model.Type(form.Type) + + if has, err := packages_model.HasOwnerCleanupRuleForPackageType(ctx, owner.ID, pcr.Type); err != nil { + ctx.ServerError("HasOwnerCleanupRuleForPackageType", err) + return + } else if has { + ctx.Data["Err_Type"] = true + ctx.HTML(http.StatusOK, template) + return + } + + var err error + if pcr, err = packages_model.InsertCleanupRule(ctx, pcr); err != nil { + ctx.ServerError("InsertCleanupRule", err) + return + } + } + + ctx.Flash.Success(ctx.Tr("packages.owner.settings.cleanuprules.success.update")) + ctx.Redirect(fmt.Sprintf("%s/rules/%d", redirectURL, pcr.ID)) +} + +func SetRulePreviewContext(ctx *context.Context, owner *user_model.User) { + pcr := getCleanupRuleByContext(ctx, owner) + if pcr == nil { + return + } + + if err := pcr.CompiledPattern(); err != nil { + ctx.ServerError("CompiledPattern", err) + return + } + + olderThan := time.Now().AddDate(0, 0, -pcr.RemoveDays) + + packages, err := packages_model.GetPackagesByType(ctx, pcr.OwnerID, pcr.Type) + if err != nil { + ctx.ServerError("GetPackagesByType", err) + return + } + + versionsToRemove := make([]*packages_model.PackageDescriptor, 0, 10) + + for _, p := range packages { + pvs, _, err := packages_model.SearchVersions(ctx, &packages_model.PackageSearchOptions{ + PackageID: p.ID, + IsInternal: util.OptionalBoolFalse, + Sort: packages_model.SortCreatedDesc, + Paginator: db.NewAbsoluteListOptions(pcr.KeepCount, 200), + }) + if err != nil { + ctx.ServerError("SearchVersions", err) + return + } + for _, pv := range pvs { + if skip, err := container_service.ShouldBeSkipped(ctx, pcr, p, pv); err != nil { + ctx.ServerError("ShouldBeSkipped", err) + return + } else if skip { + continue + } + + toMatch := pv.LowerVersion + if pcr.MatchFullName { + toMatch = p.LowerName + "/" + pv.LowerVersion + } + + if pcr.KeepPatternMatcher != nil && pcr.KeepPatternMatcher.MatchString(toMatch) { + continue + } + if pv.CreatedUnix.AsLocalTime().After(olderThan) { + continue + } + if pcr.RemovePatternMatcher != nil && !pcr.RemovePatternMatcher.MatchString(toMatch) { + continue + } + + pd, err := packages_model.GetPackageDescriptor(ctx, pv) + if err != nil { + ctx.ServerError("GetPackageDescriptor", err) + return + } + versionsToRemove = append(versionsToRemove, pd) + } + } + + ctx.Data["CleanupRule"] = pcr + ctx.Data["VersionsToRemove"] = versionsToRemove +} + +func getCleanupRuleByContext(ctx *context.Context, owner *user_model.User) *packages_model.PackageCleanupRule { + id := ctx.FormInt64("id") + if id == 0 { + id = ctx.ParamsInt64("id") + } + + pcr, err := packages_model.GetCleanupRuleByID(ctx, id) + if err != nil { + if err == packages_model.ErrPackageCleanupRuleNotExist { + ctx.NotFound("", err) + } else { + ctx.ServerError("GetCleanupRuleByID", err) + } + return nil + } + + if pcr != nil && pcr.OwnerID == owner.ID { + return pcr + } + + ctx.NotFound("", fmt.Errorf("PackageCleanupRule[%v] not associated to owner %v", id, owner)) + + return nil +} diff --git a/routers/web/swagger_json.go b/routers/web/swagger_json.go index 82d72698c6..2d626c558e 100644 --- a/routers/web/swagger_json.go +++ b/routers/web/swagger_json.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package web diff --git a/routers/web/user/avatar.go b/routers/web/user/avatar.go index 05896299d2..20c2ef3e47 100644 --- a/routers/web/user/avatar.go +++ b/routers/web/user/avatar.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package user diff --git a/routers/web/user/code.go b/routers/web/user/code.go index 89bd23588b..0f95932061 100644 --- a/routers/web/user/code.go +++ b/routers/web/user/code.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package user diff --git a/routers/web/user/home.go b/routers/web/user/home.go index 95ec1aa2fa..36d9d4f019 100644 --- a/routers/web/user/home.go +++ b/routers/web/user/home.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package user @@ -202,7 +201,7 @@ func Milestones(ctx *context.Context) { return } - showRepos, _, err := repo_model.SearchRepositoryByCondition(&repoOpts, userRepoCond, false) + showRepos, _, err := repo_model.SearchRepositoryByCondition(ctx, &repoOpts, userRepoCond, false) if err != nil { ctx.ServerError("SearchRepositoryByCondition", err) return @@ -232,7 +231,7 @@ func Milestones(ctx *context.Context) { return } - if milestones[i].Repo.IsTimetrackerEnabled() { + if milestones[i].Repo.IsTimetrackerEnabled(ctx) { err := milestones[i].LoadTotalTrackedTime() if err != nil { ctx.ServerError("LoadTotalTrackedTime", err) @@ -461,7 +460,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) { // USING NON-FINAL STATE OF opts FOR A QUERY. var issueCountByRepo map[int64]int64 if !forceEmpty { - issueCountByRepo, err = issues_model.CountIssuesByRepo(opts) + issueCountByRepo, err = issues_model.CountIssuesByRepo(ctx, opts) if err != nil { ctx.ServerError("CountIssuesByRepo", err) return @@ -504,7 +503,7 @@ func buildIssueOverview(ctx *context.Context, unitType unit.Type) { // USING FINAL STATE OF opts FOR A QUERY. var issues []*issues_model.Issue if !forceEmpty { - issues, err = issues_model.Issues(opts) + issues, err = issues_model.Issues(ctx, opts) if err != nil { ctx.ServerError("Issues", err) return diff --git a/routers/web/user/home_test.go b/routers/web/user/home_test.go index 36e99bba5e..534b0b2620 100644 --- a/routers/web/user/home_test.go +++ b/routers/web/user/home_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package user @@ -27,7 +26,7 @@ func TestArchivedIssues(t *testing.T) { // Assume: User 30 has access to two Repos with Issues, one of the Repos being archived. repos, _, _ := repo_model.GetUserRepositories(&repo_model.SearchRepoOptions{Actor: ctx.Doer}) - assert.Len(t, repos, 2) + assert.Len(t, repos, 3) IsArchived := make(map[int64]bool) NumIssues := make(map[int64]int) for _, repo := range repos { diff --git a/routers/web/user/main_test.go b/routers/web/user/main_test.go index 517957a85c..925482a1d2 100644 --- a/routers/web/user/main_test.go +++ b/routers/web/user/main_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package user diff --git a/routers/web/user/notification.go b/routers/web/user/notification.go index b4753a603e..b21d52bbfd 100644 --- a/routers/web/user/notification.go +++ b/routers/web/user/notification.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package user @@ -33,20 +32,20 @@ const ( ) // GetNotificationCount is the middleware that sets the notification count in the context -func GetNotificationCount(c *context.Context) { - if strings.HasPrefix(c.Req.URL.Path, "/api") { +func GetNotificationCount(ctx *context.Context) { + if strings.HasPrefix(ctx.Req.URL.Path, "/api") { return } - if !c.IsSigned { + if !ctx.IsSigned { return } - c.Data["NotificationUnreadCount"] = func() int64 { - count, err := activities_model.GetNotificationCount(c, c.Doer, activities_model.NotificationStatusUnread) + ctx.Data["NotificationUnreadCount"] = func() int64 { + count, err := activities_model.GetNotificationCount(ctx, ctx.Doer, activities_model.NotificationStatusUnread) if err != nil { if err != goctx.Canceled { - log.Error("Unable to GetNotificationCount for user:%-v: %v", c.Doer, err) + log.Error("Unable to GetNotificationCount for user:%-v: %v", ctx.Doer, err) } return -1 } @@ -56,25 +55,25 @@ func GetNotificationCount(c *context.Context) { } // Notifications is the notifications page -func Notifications(c *context.Context) { - getNotifications(c) - if c.Written() { +func Notifications(ctx *context.Context) { + getNotifications(ctx) + if ctx.Written() { return } - if c.FormBool("div-only") { - c.Data["SequenceNumber"] = c.FormString("sequence-number") - c.HTML(http.StatusOK, tplNotificationDiv) + if ctx.FormBool("div-only") { + ctx.Data["SequenceNumber"] = ctx.FormString("sequence-number") + ctx.HTML(http.StatusOK, tplNotificationDiv) return } - c.HTML(http.StatusOK, tplNotification) + ctx.HTML(http.StatusOK, tplNotification) } -func getNotifications(c *context.Context) { +func getNotifications(ctx *context.Context) { var ( - keyword = c.FormTrim("q") + keyword = ctx.FormTrim("q") status activities_model.NotificationStatus - page = c.FormInt("page") - perPage = c.FormInt("perPage") + page = ctx.FormInt("page") + perPage = ctx.FormInt("perPage") ) if page < 1 { page = 1 @@ -90,74 +89,74 @@ func getNotifications(c *context.Context) { status = activities_model.NotificationStatusUnread } - total, err := activities_model.GetNotificationCount(c, c.Doer, status) + total, err := activities_model.GetNotificationCount(ctx, ctx.Doer, status) if err != nil { - c.ServerError("ErrGetNotificationCount", err) + ctx.ServerError("ErrGetNotificationCount", err) return } // redirect to last page if request page is more than total pages pager := context.NewPagination(int(total), perPage, page, 5) if pager.Paginater.Current() < page { - c.Redirect(fmt.Sprintf("%s/notifications?q=%s&page=%d", setting.AppSubURL, url.QueryEscape(c.FormString("q")), pager.Paginater.Current())) + ctx.Redirect(fmt.Sprintf("%s/notifications?q=%s&page=%d", setting.AppSubURL, url.QueryEscape(ctx.FormString("q")), pager.Paginater.Current())) return } statuses := []activities_model.NotificationStatus{status, activities_model.NotificationStatusPinned} - notifications, err := activities_model.NotificationsForUser(c, c.Doer, statuses, page, perPage) + notifications, err := activities_model.NotificationsForUser(ctx, ctx.Doer, statuses, page, perPage) if err != nil { - c.ServerError("ErrNotificationsForUser", err) + ctx.ServerError("ErrNotificationsForUser", err) return } failCount := 0 - repos, failures, err := notifications.LoadRepos() + repos, failures, err := notifications.LoadRepos(ctx) if err != nil { - c.ServerError("LoadRepos", err) + ctx.ServerError("LoadRepos", err) return } notifications = notifications.Without(failures) - if err := repos.LoadAttributes(); err != nil { - c.ServerError("LoadAttributes", err) + if err := repos.LoadAttributes(); err != nil { // TODO + ctx.ServerError("LoadAttributes", err) return } failCount += len(failures) - failures, err = notifications.LoadIssues() + failures, err = notifications.LoadIssues(ctx) if err != nil { - c.ServerError("LoadIssues", err) + ctx.ServerError("LoadIssues", err) return } notifications = notifications.Without(failures) failCount += len(failures) - failures, err = notifications.LoadComments() + failures, err = notifications.LoadComments(ctx) if err != nil { - c.ServerError("LoadComments", err) + ctx.ServerError("LoadComments", err) return } notifications = notifications.Without(failures) failCount += len(failures) if failCount > 0 { - c.Flash.Error(fmt.Sprintf("ERROR: %d notifications were removed due to missing parts - check the logs", failCount)) + ctx.Flash.Error(fmt.Sprintf("ERROR: %d notifications were removed due to missing parts - check the logs", failCount)) } - c.Data["Title"] = c.Tr("notifications") - c.Data["Keyword"] = keyword - c.Data["Status"] = status - c.Data["Notifications"] = notifications + ctx.Data["Title"] = ctx.Tr("notifications") + ctx.Data["Keyword"] = keyword + ctx.Data["Status"] = status + ctx.Data["Notifications"] = notifications - pager.SetDefaultParams(c) - c.Data["Page"] = pager + pager.SetDefaultParams(ctx) + ctx.Data["Page"] = pager } // NotificationStatusPost is a route for changing the status of a notification -func NotificationStatusPost(c *context.Context) { +func NotificationStatusPost(ctx *context.Context) { var ( - notificationID = c.FormInt64("notification_id") - statusStr = c.FormString("status") + notificationID = ctx.FormInt64("notification_id") + statusStr = ctx.FormString("status") status activities_model.NotificationStatus ) @@ -169,56 +168,56 @@ func NotificationStatusPost(c *context.Context) { case "pinned": status = activities_model.NotificationStatusPinned default: - c.ServerError("InvalidNotificationStatus", errors.New("Invalid notification status")) + ctx.ServerError("InvalidNotificationStatus", errors.New("Invalid notification status")) return } - if _, err := activities_model.SetNotificationStatus(notificationID, c.Doer, status); err != nil { - c.ServerError("SetNotificationStatus", err) + if _, err := activities_model.SetNotificationStatus(ctx, notificationID, ctx.Doer, status); err != nil { + ctx.ServerError("SetNotificationStatus", err) return } - if !c.FormBool("noredirect") { - url := fmt.Sprintf("%s/notifications?page=%s", setting.AppSubURL, url.QueryEscape(c.FormString("page"))) - c.Redirect(url, http.StatusSeeOther) + if !ctx.FormBool("noredirect") { + url := fmt.Sprintf("%s/notifications?page=%s", setting.AppSubURL, url.QueryEscape(ctx.FormString("page"))) + ctx.Redirect(url, http.StatusSeeOther) } - getNotifications(c) - if c.Written() { + getNotifications(ctx) + if ctx.Written() { return } - c.Data["Link"] = setting.AppURL + "notifications" - c.Data["SequenceNumber"] = c.Req.PostFormValue("sequence-number") + ctx.Data["Link"] = setting.AppURL + "notifications" + ctx.Data["SequenceNumber"] = ctx.Req.PostFormValue("sequence-number") - c.HTML(http.StatusOK, tplNotificationDiv) + ctx.HTML(http.StatusOK, tplNotificationDiv) } // NotificationPurgePost is a route for 'purging' the list of notifications - marking all unread as read -func NotificationPurgePost(c *context.Context) { - err := activities_model.UpdateNotificationStatuses(c.Doer, activities_model.NotificationStatusUnread, activities_model.NotificationStatusRead) +func NotificationPurgePost(ctx *context.Context) { + err := activities_model.UpdateNotificationStatuses(ctx, ctx.Doer, activities_model.NotificationStatusUnread, activities_model.NotificationStatusRead) if err != nil { - c.ServerError("ErrUpdateNotificationStatuses", err) + ctx.ServerError("UpdateNotificationStatuses", err) return } - c.Redirect(setting.AppSubURL+"/notifications", http.StatusSeeOther) + ctx.Redirect(setting.AppSubURL+"/notifications", http.StatusSeeOther) } // NotificationSubscriptions returns the list of subscribed issues -func NotificationSubscriptions(c *context.Context) { - page := c.FormInt("page") +func NotificationSubscriptions(ctx *context.Context) { + page := ctx.FormInt("page") if page < 1 { page = 1 } - sortType := c.FormString("sort") - c.Data["SortType"] = sortType + sortType := ctx.FormString("sort") + ctx.Data["SortType"] = sortType - state := c.FormString("state") + state := ctx.FormString("state") if !util.IsStringInSlice(state, []string{"all", "open", "closed"}, true) { state = "all" } - c.Data["State"] = state + ctx.Data["State"] = state var showClosed util.OptionalBool switch state { case "all": @@ -230,7 +229,7 @@ func NotificationSubscriptions(c *context.Context) { } var issueTypeBool util.OptionalBool - issueType := c.FormString("issueType") + issueType := ctx.FormString("issueType") switch issueType { case "issues": issueTypeBool = util.OptionalBoolFalse @@ -239,71 +238,71 @@ func NotificationSubscriptions(c *context.Context) { default: issueTypeBool = util.OptionalBoolNone } - c.Data["IssueType"] = issueType + ctx.Data["IssueType"] = issueType var labelIDs []int64 - selectedLabels := c.FormString("labels") - c.Data["Labels"] = selectedLabels + selectedLabels := ctx.FormString("labels") + ctx.Data["Labels"] = selectedLabels if len(selectedLabels) > 0 && selectedLabels != "0" { var err error labelIDs, err = base.StringsToInt64s(strings.Split(selectedLabels, ",")) if err != nil { - c.ServerError("StringsToInt64s", err) + ctx.ServerError("StringsToInt64s", err) return } } - count, err := issues_model.CountIssues(&issues_model.IssuesOptions{ - SubscriberID: c.Doer.ID, + count, err := issues_model.CountIssues(ctx, &issues_model.IssuesOptions{ + SubscriberID: ctx.Doer.ID, IsClosed: showClosed, IsPull: issueTypeBool, LabelIDs: labelIDs, }) if err != nil { - c.ServerError("CountIssues", err) + ctx.ServerError("CountIssues", err) return } - issues, err := issues_model.Issues(&issues_model.IssuesOptions{ + issues, err := issues_model.Issues(ctx, &issues_model.IssuesOptions{ ListOptions: db.ListOptions{ PageSize: setting.UI.IssuePagingNum, Page: page, }, - SubscriberID: c.Doer.ID, + SubscriberID: ctx.Doer.ID, SortType: sortType, IsClosed: showClosed, IsPull: issueTypeBool, LabelIDs: labelIDs, }) if err != nil { - c.ServerError("Issues", err) + ctx.ServerError("Issues", err) return } - commitStatuses, lastStatus, err := pull_service.GetIssuesAllCommitStatus(c, issues) + commitStatuses, lastStatus, err := pull_service.GetIssuesAllCommitStatus(ctx, issues) if err != nil { - c.ServerError("GetIssuesAllCommitStatus", err) + ctx.ServerError("GetIssuesAllCommitStatus", err) return } - c.Data["CommitLastStatus"] = lastStatus - c.Data["CommitStatuses"] = commitStatuses - c.Data["Issues"] = issues + ctx.Data["CommitLastStatus"] = lastStatus + ctx.Data["CommitStatuses"] = commitStatuses + ctx.Data["Issues"] = issues - c.Data["IssueRefEndNames"], c.Data["IssueRefURLs"] = issue_service.GetRefEndNamesAndURLs(issues, "") + ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] = issue_service.GetRefEndNamesAndURLs(issues, "") - commitStatus, err := pull_service.GetIssuesLastCommitStatus(c, issues) + commitStatus, err := pull_service.GetIssuesLastCommitStatus(ctx, issues) if err != nil { - c.ServerError("GetIssuesLastCommitStatus", err) + ctx.ServerError("GetIssuesLastCommitStatus", err) return } - c.Data["CommitStatus"] = commitStatus + ctx.Data["CommitStatus"] = commitStatus issueList := issues_model.IssueList(issues) - approvalCounts, err := issueList.GetApprovalCounts(c) + approvalCounts, err := issueList.GetApprovalCounts(ctx) if err != nil { - c.ServerError("ApprovalCounts", err) + ctx.ServerError("ApprovalCounts", err) return } - c.Data["ApprovalCounts"] = func(issueID int64, typ string) int64 { + ctx.Data["ApprovalCounts"] = func(issueID int64, typ string) int64 { counts, ok := approvalCounts[issueID] if !ok || len(counts) == 0 { return 0 @@ -322,32 +321,32 @@ func NotificationSubscriptions(c *context.Context) { return 0 } - c.Data["Status"] = 1 - c.Data["Title"] = c.Tr("notification.subscriptions") + ctx.Data["Status"] = 1 + ctx.Data["Title"] = ctx.Tr("notification.subscriptions") // redirect to last page if request page is more than total pages pager := context.NewPagination(int(count), setting.UI.IssuePagingNum, page, 5) if pager.Paginater.Current() < page { - c.Redirect(fmt.Sprintf("/notifications/subscriptions?page=%d", pager.Paginater.Current())) + ctx.Redirect(fmt.Sprintf("/notifications/subscriptions?page=%d", pager.Paginater.Current())) return } - pager.AddParam(c, "sort", "SortType") - pager.AddParam(c, "state", "State") - c.Data["Page"] = pager + pager.AddParam(ctx, "sort", "SortType") + pager.AddParam(ctx, "state", "State") + ctx.Data["Page"] = pager - c.HTML(http.StatusOK, tplNotificationSubscriptions) + ctx.HTML(http.StatusOK, tplNotificationSubscriptions) } // NotificationWatching returns the list of watching repos -func NotificationWatching(c *context.Context) { - page := c.FormInt("page") +func NotificationWatching(ctx *context.Context) { + page := ctx.FormInt("page") if page < 1 { page = 1 } var orderBy db.SearchOrderBy - c.Data["SortType"] = c.FormString("sort") - switch c.FormString("sort") { + ctx.Data["SortType"] = ctx.FormString("sort") + switch ctx.FormString("sort") { case "newest": orderBy = db.SearchOrderByNewest case "oldest": @@ -369,41 +368,41 @@ func NotificationWatching(c *context.Context) { case "fewestforks": orderBy = db.SearchOrderByForks default: - c.Data["SortType"] = "recentupdate" + ctx.Data["SortType"] = "recentupdate" orderBy = db.SearchOrderByRecentUpdated } - repos, count, err := repo_model.SearchRepository(&repo_model.SearchRepoOptions{ + repos, count, err := repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{ PageSize: setting.UI.User.RepoPagingNum, Page: page, }, - Actor: c.Doer, - Keyword: c.FormTrim("q"), + Actor: ctx.Doer, + Keyword: ctx.FormTrim("q"), OrderBy: orderBy, - Private: c.IsSigned, - WatchedByID: c.Doer.ID, + Private: ctx.IsSigned, + WatchedByID: ctx.Doer.ID, Collaborate: util.OptionalBoolFalse, - TopicOnly: c.FormBool("topic"), + TopicOnly: ctx.FormBool("topic"), IncludeDescription: setting.UI.SearchRepoDescription, }) if err != nil { - c.ServerError("ErrSearchRepository", err) + ctx.ServerError("SearchRepository", err) return } total := int(count) - c.Data["Total"] = total - c.Data["Repos"] = repos + ctx.Data["Total"] = total + ctx.Data["Repos"] = repos // redirect to last page if request page is more than total pages pager := context.NewPagination(total, setting.UI.User.RepoPagingNum, page, 5) - pager.SetDefaultParams(c) - c.Data["Page"] = pager + pager.SetDefaultParams(ctx) + ctx.Data["Page"] = pager - c.Data["Status"] = 2 - c.Data["Title"] = c.Tr("notification.watching") + ctx.Data["Status"] = 2 + ctx.Data["Title"] = ctx.Tr("notification.watching") - c.HTML(http.StatusOK, tplNotificationSubscriptions) + ctx.HTML(http.StatusOK, tplNotificationSubscriptions) } // NewAvailable returns the notification counts diff --git a/routers/web/user/package.go b/routers/web/user/package.go index 7179e2df97..3782f46b42 100644 --- a/routers/web/user/package.go +++ b/routers/web/user/package.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package user @@ -337,7 +336,7 @@ func PackageSettingsPost(ctx *context.Context) { success := func() bool { repoID := int64(0) if form.RepoID != 0 { - repo, err := repo_model.GetRepositoryByID(form.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, form.RepoID) if err != nil { log.Error("Error getting repository: %v", err) return false @@ -402,5 +401,8 @@ func DownloadPackageFile(ctx *context.Context) { } defer s.Close() - ctx.ServeContent(pf.Name, s, pf.CreatedUnix.AsLocalTime()) + ctx.ServeContent(s, &context.ServeHeaderOptions{ + Filename: pf.Name, + LastModified: pf.CreatedUnix.AsLocalTime(), + }) } diff --git a/routers/web/user/profile.go b/routers/web/user/profile.go index bc56407e55..732d45bdc3 100644 --- a/routers/web/user/profile.go +++ b/routers/web/user/profile.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package user @@ -204,7 +203,7 @@ func Profile(ctx *context.Context) { } case "stars": ctx.Data["PageIsProfileStarList"] = true - repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{ + repos, count, err = repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{ PageSize: setting.UI.User.RepoPagingNum, Page: page, @@ -236,7 +235,7 @@ func Profile(ctx *context.Context) { return } case "watching": - repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{ + repos, count, err = repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{ PageSize: setting.UI.User.RepoPagingNum, Page: page, @@ -258,7 +257,7 @@ func Profile(ctx *context.Context) { total = int(count) default: - repos, count, err = repo_model.SearchRepository(&repo_model.SearchRepoOptions{ + repos, count, err = repo_model.SearchRepository(ctx, &repo_model.SearchRepoOptions{ ListOptions: db.ListOptions{ PageSize: setting.UI.User.RepoPagingNum, Page: page, @@ -303,9 +302,9 @@ func Action(ctx *context.Context) { var err error switch ctx.FormString("action") { case "follow": - err = user_service.FollowUser(ctx.Doer.ID, ctx.ContextUser.ID) + err = user_service.FollowUser(ctx, ctx.Doer.ID, ctx.ContextUser.ID) case "unfollow": - err = user_service.UnfollowUser(ctx.Doer.ID, ctx.ContextUser.ID) + err = user_service.UnfollowUser(ctx, ctx.Doer.ID, ctx.ContextUser.ID) } if err != nil { diff --git a/routers/web/user/search.go b/routers/web/user/search.go index 328c7bade4..093de406a9 100644 --- a/routers/web/user/search.go +++ b/routers/web/user/search.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package user diff --git a/routers/web/user/setting/account.go b/routers/web/user/setting/account.go index 8b95caf2fc..95b3b4040d 100644 --- a/routers/web/user/setting/account.go +++ b/routers/web/user/setting/account.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package setting diff --git a/routers/web/user/setting/account_test.go b/routers/web/user/setting/account_test.go index 005603e7ac..5fce41f065 100644 --- a/routers/web/user/setting/account_test.go +++ b/routers/web/user/setting/account_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package setting diff --git a/routers/web/user/setting/adopt.go b/routers/web/user/setting/adopt.go index a92aa6e989..0aaf5920bc 100644 --- a/routers/web/user/setting/adopt.go +++ b/routers/web/user/setting/adopt.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package setting diff --git a/routers/web/user/setting/applications.go b/routers/web/user/setting/applications.go index e9572a07a6..23c215738d 100644 --- a/routers/web/user/setting/applications.go +++ b/routers/web/user/setting/applications.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package setting diff --git a/routers/web/user/setting/keys.go b/routers/web/user/setting/keys.go index a8d07ea47a..89be795599 100644 --- a/routers/web/user/setting/keys.go +++ b/routers/web/user/setting/keys.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package setting diff --git a/routers/web/user/setting/main_test.go b/routers/web/user/setting/main_test.go index d4df464abd..c3938b3201 100644 --- a/routers/web/user/setting/main_test.go +++ b/routers/web/user/setting/main_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package setting diff --git a/routers/web/user/setting/oauth2.go b/routers/web/user/setting/oauth2.go index 0cc05dd040..93142c21fc 100644 --- a/routers/web/user/setting/oauth2.go +++ b/routers/web/user/setting/oauth2.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/routers/web/user/setting/oauth2_common.go b/routers/web/user/setting/oauth2_common.go index 49ee5c7c2f..f6ad1b2b38 100644 --- a/routers/web/user/setting/oauth2_common.go +++ b/routers/web/user/setting/oauth2_common.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package setting diff --git a/routers/web/user/setting/packages.go b/routers/web/user/setting/packages.go new file mode 100644 index 0000000000..f6f7195adf --- /dev/null +++ b/routers/web/user/setting/packages.go @@ -0,0 +1,79 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package setting + +import ( + "net/http" + + "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/setting" + shared "code.gitea.io/gitea/routers/web/shared/packages" +) + +const ( + tplSettingsPackages base.TplName = "user/settings/packages" + tplSettingsPackagesRuleEdit base.TplName = "user/settings/packages_cleanup_rules_edit" + tplSettingsPackagesRulePreview base.TplName = "user/settings/packages_cleanup_rules_preview" +) + +func Packages(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("packages.title") + ctx.Data["PageIsSettingsPackages"] = true + + shared.SetPackagesContext(ctx, ctx.Doer) + + ctx.HTML(http.StatusOK, tplSettingsPackages) +} + +func PackagesRuleAdd(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("packages.title") + ctx.Data["PageIsSettingsPackages"] = true + + shared.SetRuleAddContext(ctx) + + ctx.HTML(http.StatusOK, tplSettingsPackagesRuleEdit) +} + +func PackagesRuleEdit(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("packages.title") + ctx.Data["PageIsSettingsPackages"] = true + + shared.SetRuleEditContext(ctx, ctx.Doer) + + ctx.HTML(http.StatusOK, tplSettingsPackagesRuleEdit) +} + +func PackagesRuleAddPost(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("settings") + ctx.Data["PageIsSettingsPackages"] = true + + shared.PerformRuleAddPost( + ctx, + ctx.Doer, + setting.AppSubURL+"/user/settings/packages", + tplSettingsPackagesRuleEdit, + ) +} + +func PackagesRuleEditPost(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("packages.title") + ctx.Data["PageIsSettingsPackages"] = true + + shared.PerformRuleEditPost( + ctx, + ctx.Doer, + setting.AppSubURL+"/user/settings/packages", + tplSettingsPackagesRuleEdit, + ) +} + +func PackagesRulePreview(ctx *context.Context) { + ctx.Data["Title"] = ctx.Tr("packages.title") + ctx.Data["PageIsSettingsPackages"] = true + + shared.SetRulePreviewContext(ctx, ctx.Doer) + + ctx.HTML(http.StatusOK, tplSettingsPackagesRulePreview) +} diff --git a/routers/web/user/setting/profile.go b/routers/web/user/setting/profile.go index ba3f5b5080..ef45ad8a86 100644 --- a/routers/web/user/setting/profile.go +++ b/routers/web/user/setting/profile.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package setting @@ -324,7 +323,7 @@ func Repos(ctx *context.Context) { } for _, repo := range userRepos { if repo.IsFork { - if err := repo.GetBaseRepo(); err != nil { + if err := repo.GetBaseRepo(ctx); err != nil { ctx.ServerError("GetBaseRepo", err) return } @@ -343,7 +342,7 @@ func Repos(ctx *context.Context) { for i := range repos { if repos[i].IsFork { - if err := repos[i].GetBaseRepo(); err != nil { + if err := repos[i].GetBaseRepo(ctx); err != nil { ctx.ServerError("GetBaseRepo", err) return } diff --git a/routers/web/user/setting/security/2fa.go b/routers/web/user/setting/security/2fa.go index 5fd81bae41..0cecb1aa37 100644 --- a/routers/web/user/setting/security/2fa.go +++ b/routers/web/user/setting/security/2fa.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package security diff --git a/routers/web/user/setting/security/openid.go b/routers/web/user/setting/security/openid.go index a378c8bf64..08fcb6b623 100644 --- a/routers/web/user/setting/security/openid.go +++ b/routers/web/user/setting/security/openid.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package security diff --git a/routers/web/user/setting/security/security.go b/routers/web/user/setting/security/security.go index 57ea24eeb1..db6faaed6e 100644 --- a/routers/web/user/setting/security/security.go +++ b/routers/web/user/setting/security/security.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package security diff --git a/routers/web/user/setting/security/webauthn.go b/routers/web/user/setting/security/webauthn.go index bb2d1f733e..ba05996a1c 100644 --- a/routers/web/user/setting/security/webauthn.go +++ b/routers/web/user/setting/security/webauthn.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package security diff --git a/routers/web/user/stop_watch.go b/routers/web/user/stop_watch.go index f40d850fc1..26c7558c11 100644 --- a/routers/web/user/stop_watch.go +++ b/routers/web/user/stop_watch.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package user diff --git a/routers/web/user/task.go b/routers/web/user/task.go index 7f5ef792ad..3818682403 100644 --- a/routers/web/user/task.go +++ b/routers/web/user/task.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package user diff --git a/routers/web/web.go b/routers/web/web.go index 48b33813c9..f9d97758a1 100644 --- a/routers/web/web.go +++ b/routers/web/web.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package web @@ -67,6 +66,7 @@ func CorsHandler() func(next http.Handler) http.Handler { // setting.CORSConfig.AllowSubdomain // FIXME: the cors middleware needs allowSubdomain option AllowedMethods: setting.CORSConfig.Methods, AllowCredentials: setting.CORSConfig.AllowCredentials, + AllowedHeaders: setting.CORSConfig.Headers, MaxAge: int(setting.CORSConfig.MaxAge.Seconds()), }) } @@ -234,8 +234,6 @@ func RegisterRoutes(m *web.Route) { ignExploreSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView || setting.Service.Explore.RequireSigninView}) ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true}) reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true}) - - bindIgnErr := web.Bind validation.AddBindingRules() linkAccountEnabled := func(ctx *context.Context) { @@ -302,6 +300,20 @@ func RegisterRoutes(m *web.Route) { } } + packagesEnabled := func(ctx *context.Context) { + if !setting.Packages.Enabled { + ctx.Error(http.StatusForbidden) + return + } + } + + feedEnabled := func(ctx *context.Context) { + if !setting.EnableFeed { + ctx.Error(http.StatusNotFound) + return + } + } + // FIXME: not all routes need go through same middleware. // Especially some AJAX requests, we can reduce middleware number to improve performance. // Routers. @@ -342,32 +354,32 @@ func RegisterRoutes(m *web.Route) { // ***** START: User ***** m.Group("/user", func() { m.Get("/login", auth.SignIn) - m.Post("/login", bindIgnErr(forms.SignInForm{}), auth.SignInPost) + m.Post("/login", web.Bind(forms.SignInForm{}), auth.SignInPost) m.Group("", func() { m.Combo("/login/openid"). Get(auth.SignInOpenID). - Post(bindIgnErr(forms.SignInOpenIDForm{}), auth.SignInOpenIDPost) + Post(web.Bind(forms.SignInOpenIDForm{}), auth.SignInOpenIDPost) }, openIDSignInEnabled) m.Group("/openid", func() { m.Combo("/connect"). Get(auth.ConnectOpenID). - Post(bindIgnErr(forms.ConnectOpenIDForm{}), auth.ConnectOpenIDPost) + Post(web.Bind(forms.ConnectOpenIDForm{}), auth.ConnectOpenIDPost) m.Group("/register", func() { m.Combo(""). Get(auth.RegisterOpenID, openIDSignUpEnabled). - Post(bindIgnErr(forms.SignUpOpenIDForm{}), auth.RegisterOpenIDPost) + Post(web.Bind(forms.SignUpOpenIDForm{}), auth.RegisterOpenIDPost) }, openIDSignUpEnabled) }, openIDSignInEnabled) m.Get("/sign_up", auth.SignUp) - m.Post("/sign_up", bindIgnErr(forms.RegisterForm{}), auth.SignUpPost) + m.Post("/sign_up", web.Bind(forms.RegisterForm{}), auth.SignUpPost) m.Get("/link_account", linkAccountEnabled, auth.LinkAccount) - m.Post("/link_account_signin", linkAccountEnabled, bindIgnErr(forms.SignInForm{}), auth.LinkAccountPostSignIn) - m.Post("/link_account_signup", linkAccountEnabled, bindIgnErr(forms.RegisterForm{}), auth.LinkAccountPostRegister) + m.Post("/link_account_signin", linkAccountEnabled, web.Bind(forms.SignInForm{}), auth.LinkAccountPostSignIn) + m.Post("/link_account_signup", linkAccountEnabled, web.Bind(forms.RegisterForm{}), auth.LinkAccountPostRegister) m.Group("/two_factor", func() { m.Get("", auth.TwoFactor) - m.Post("", bindIgnErr(forms.TwoFactorAuthForm{}), auth.TwoFactorPost) + m.Post("", web.Bind(forms.TwoFactorAuthForm{}), auth.TwoFactorPost) m.Get("/scratch", auth.TwoFactorScratch) - m.Post("/scratch", bindIgnErr(forms.TwoFactorScratchAuthForm{}), auth.TwoFactorScratchPost) + m.Post("/scratch", web.Bind(forms.TwoFactorScratchAuthForm{}), auth.TwoFactorScratchPost) }) m.Group("/webauthn", func() { m.Get("", auth.WebAuthn) @@ -379,34 +391,34 @@ func RegisterRoutes(m *web.Route) { m.Any("/user/events", routing.MarkLongPolling, events.Events) m.Group("/login/oauth", func() { - m.Get("/authorize", bindIgnErr(forms.AuthorizationForm{}), auth.AuthorizeOAuth) - m.Post("/grant", bindIgnErr(forms.GrantApplicationForm{}), auth.GrantApplicationOAuth) + m.Get("/authorize", web.Bind(forms.AuthorizationForm{}), auth.AuthorizeOAuth) + m.Post("/grant", web.Bind(forms.GrantApplicationForm{}), auth.GrantApplicationOAuth) // TODO manage redirection - m.Post("/authorize", bindIgnErr(forms.AuthorizationForm{}), auth.AuthorizeOAuth) + m.Post("/authorize", web.Bind(forms.AuthorizationForm{}), auth.AuthorizeOAuth) }, ignSignInAndCsrf, reqSignIn) m.Get("/login/oauth/userinfo", ignSignInAndCsrf, auth.InfoOAuth) - m.Post("/login/oauth/access_token", CorsHandler(), bindIgnErr(forms.AccessTokenForm{}), ignSignInAndCsrf, auth.AccessTokenOAuth) + m.Post("/login/oauth/access_token", CorsHandler(), web.Bind(forms.AccessTokenForm{}), ignSignInAndCsrf, auth.AccessTokenOAuth) m.Get("/login/oauth/keys", ignSignInAndCsrf, auth.OIDCKeys) - m.Post("/login/oauth/introspect", CorsHandler(), bindIgnErr(forms.IntrospectTokenForm{}), ignSignInAndCsrf, auth.IntrospectOAuth) + m.Post("/login/oauth/introspect", CorsHandler(), web.Bind(forms.IntrospectTokenForm{}), ignSignInAndCsrf, auth.IntrospectOAuth) m.Group("/user/settings", func() { m.Get("", user_setting.Profile) - m.Post("", bindIgnErr(forms.UpdateProfileForm{}), user_setting.ProfilePost) + m.Post("", web.Bind(forms.UpdateProfileForm{}), user_setting.ProfilePost) m.Get("/change_password", auth.MustChangePassword) - m.Post("/change_password", bindIgnErr(forms.MustChangePasswordForm{}), auth.MustChangePasswordPost) - m.Post("/avatar", bindIgnErr(forms.AvatarForm{}), user_setting.AvatarPost) + m.Post("/change_password", web.Bind(forms.MustChangePasswordForm{}), auth.MustChangePasswordPost) + m.Post("/avatar", web.Bind(forms.AvatarForm{}), user_setting.AvatarPost) m.Post("/avatar/delete", user_setting.DeleteAvatar) m.Group("/account", func() { - m.Combo("").Get(user_setting.Account).Post(bindIgnErr(forms.ChangePasswordForm{}), user_setting.AccountPost) - m.Post("/email", bindIgnErr(forms.AddEmailForm{}), user_setting.EmailPost) + m.Combo("").Get(user_setting.Account).Post(web.Bind(forms.ChangePasswordForm{}), user_setting.AccountPost) + m.Post("/email", web.Bind(forms.AddEmailForm{}), user_setting.EmailPost) m.Post("/email/delete", user_setting.DeleteEmail) m.Post("/delete", user_setting.DeleteAccount) }) m.Group("/appearance", func() { m.Get("", user_setting.Appearance) - m.Post("/language", bindIgnErr(forms.UpdateLanguageForm{}), user_setting.UpdateUserLang) + m.Post("/language", web.Bind(forms.UpdateLanguageForm{}), user_setting.UpdateUserLang) m.Post("/hidden_comments", user_setting.UpdateUserHiddenComments) - m.Post("/theme", bindIgnErr(forms.UpdateThemeForm{}), user_setting.UpdateUIThemePost) + m.Post("/theme", web.Bind(forms.UpdateThemeForm{}), user_setting.UpdateUIThemePost) }) m.Group("/security", func() { m.Get("", security.Security) @@ -414,15 +426,15 @@ func RegisterRoutes(m *web.Route) { m.Post("/regenerate_scratch", security.RegenerateScratchTwoFactor) m.Post("/disable", security.DisableTwoFactor) m.Get("/enroll", security.EnrollTwoFactor) - m.Post("/enroll", bindIgnErr(forms.TwoFactorAuthForm{}), security.EnrollTwoFactorPost) + m.Post("/enroll", web.Bind(forms.TwoFactorAuthForm{}), security.EnrollTwoFactorPost) }) m.Group("/webauthn", func() { - m.Post("/request_register", bindIgnErr(forms.WebauthnRegistrationForm{}), security.WebAuthnRegister) + m.Post("/request_register", web.Bind(forms.WebauthnRegistrationForm{}), security.WebAuthnRegister) m.Post("/register", security.WebauthnRegisterPost) - m.Post("/delete", bindIgnErr(forms.WebauthnDeleteForm{}), security.WebauthnDelete) + m.Post("/delete", web.Bind(forms.WebauthnDeleteForm{}), security.WebauthnDelete) }) m.Group("/openid", func() { - m.Post("", bindIgnErr(forms.AddOpenIDForm{}), security.OpenIDPost) + m.Post("", web.Bind(forms.AddOpenIDForm{}), security.OpenIDPost) m.Post("/delete", security.DeleteOpenID) m.Post("/toggle_visibility", security.ToggleOpenIDVisibility) }, openIDSignInEnabled) @@ -430,24 +442,39 @@ func RegisterRoutes(m *web.Route) { }) m.Group("/applications/oauth2", func() { m.Get("/{id}", user_setting.OAuth2ApplicationShow) - m.Post("/{id}", bindIgnErr(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsEdit) + m.Post("/{id}", web.Bind(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsEdit) m.Post("/{id}/regenerate_secret", user_setting.OAuthApplicationsRegenerateSecret) - m.Post("", bindIgnErr(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsPost) + m.Post("", web.Bind(forms.EditOAuth2ApplicationForm{}), user_setting.OAuthApplicationsPost) m.Post("/{id}/delete", user_setting.DeleteOAuth2Application) m.Post("/{id}/revoke/{grantId}", user_setting.RevokeOAuth2Grant) }) m.Combo("/applications").Get(user_setting.Applications). - Post(bindIgnErr(forms.NewAccessTokenForm{}), user_setting.ApplicationsPost) + Post(web.Bind(forms.NewAccessTokenForm{}), user_setting.ApplicationsPost) m.Post("/applications/delete", user_setting.DeleteApplication) m.Combo("/keys").Get(user_setting.Keys). - Post(bindIgnErr(forms.AddKeyForm{}), user_setting.KeysPost) + Post(web.Bind(forms.AddKeyForm{}), user_setting.KeysPost) m.Post("/keys/delete", user_setting.DeleteKey) + m.Group("/packages", func() { + m.Get("", user_setting.Packages) + m.Group("/rules", func() { + m.Group("/add", func() { + m.Get("", user_setting.PackagesRuleAdd) + m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), user_setting.PackagesRuleAddPost) + }) + m.Group("/{id}", func() { + m.Get("", user_setting.PackagesRuleEdit) + m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), user_setting.PackagesRuleEditPost) + m.Get("/preview", user_setting.PackagesRulePreview) + }) + }) + }, packagesEnabled) m.Get("/organization", user_setting.Organization) m.Get("/repos", user_setting.Repos) m.Post("/repos/unadopted", user_setting.AdoptOrDeleteRepository) }, reqSignIn, func(ctx *context.Context) { ctx.Data["PageIsUserSettings"] = true ctx.Data["AllThemes"] = setting.UI.Themes + ctx.Data["EnablePackages"] = setting.Packages.Enabled }) m.Group("/user", func() { @@ -478,7 +505,7 @@ func RegisterRoutes(m *web.Route) { // ***** START: Admin ***** m.Group("/admin", func() { m.Get("", adminReq, admin.Dashboard) - m.Post("", adminReq, bindIgnErr(forms.AdminDashboardForm{}), admin.DashboardPost) + m.Post("", adminReq, web.Bind(forms.AdminDashboardForm{}), admin.DashboardPost) m.Group("/config", func() { m.Get("", admin.Config) @@ -503,10 +530,10 @@ func RegisterRoutes(m *web.Route) { m.Group("/users", func() { m.Get("", admin.Users) - m.Combo("/new").Get(admin.NewUser).Post(bindIgnErr(forms.AdminCreateUserForm{}), admin.NewUserPost) - m.Combo("/{userid}").Get(admin.EditUser).Post(bindIgnErr(forms.AdminEditUserForm{}), admin.EditUserPost) + m.Combo("/new").Get(admin.NewUser).Post(web.Bind(forms.AdminCreateUserForm{}), admin.NewUserPost) + m.Combo("/{userid}").Get(admin.EditUser).Post(web.Bind(forms.AdminEditUserForm{}), admin.EditUserPost) m.Post("/{userid}/delete", admin.DeleteUser) - m.Post("/{userid}/avatar", bindIgnErr(forms.AvatarForm{}), admin.AvatarPost) + m.Post("/{userid}/avatar", web.Bind(forms.AvatarForm{}), admin.AvatarPost) m.Post("/{userid}/avatar/delete", admin.DeleteAvatar) }) @@ -525,12 +552,10 @@ func RegisterRoutes(m *web.Route) { m.Post("/delete", admin.DeleteRepo) }) - if setting.Packages.Enabled { - m.Group("/packages", func() { - m.Get("", admin.Packages) - m.Post("/delete", admin.DeletePackageVersion) - }) - } + m.Group("/packages", func() { + m.Get("", admin.Packages) + m.Post("/delete", admin.DeletePackageVersion) + }, packagesEnabled) m.Group("/hooks", func() { m.Get("", admin.DefaultOrSystemWebhooks) @@ -539,39 +564,39 @@ func RegisterRoutes(m *web.Route) { m.Get("", repo.WebHooksEdit) m.Post("/replay/{uuid}", repo.ReplayWebhook) }) - m.Post("/gitea/{id}", bindIgnErr(forms.NewWebhookForm{}), repo.GiteaHooksEditPost) - m.Post("/gogs/{id}", bindIgnErr(forms.NewGogshookForm{}), repo.GogsHooksEditPost) - m.Post("/slack/{id}", bindIgnErr(forms.NewSlackHookForm{}), repo.SlackHooksEditPost) - m.Post("/discord/{id}", bindIgnErr(forms.NewDiscordHookForm{}), repo.DiscordHooksEditPost) - m.Post("/dingtalk/{id}", bindIgnErr(forms.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost) - m.Post("/telegram/{id}", bindIgnErr(forms.NewTelegramHookForm{}), repo.TelegramHooksEditPost) - m.Post("/matrix/{id}", bindIgnErr(forms.NewMatrixHookForm{}), repo.MatrixHooksEditPost) - m.Post("/msteams/{id}", bindIgnErr(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost) - m.Post("/feishu/{id}", bindIgnErr(forms.NewFeishuHookForm{}), repo.FeishuHooksEditPost) - m.Post("/wechatwork/{id}", bindIgnErr(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksEditPost) - m.Post("/packagist/{id}", bindIgnErr(forms.NewPackagistHookForm{}), repo.PackagistHooksEditPost) + m.Post("/gitea/{id}", web.Bind(forms.NewWebhookForm{}), repo.GiteaHooksEditPost) + m.Post("/gogs/{id}", web.Bind(forms.NewGogshookForm{}), repo.GogsHooksEditPost) + m.Post("/slack/{id}", web.Bind(forms.NewSlackHookForm{}), repo.SlackHooksEditPost) + m.Post("/discord/{id}", web.Bind(forms.NewDiscordHookForm{}), repo.DiscordHooksEditPost) + m.Post("/dingtalk/{id}", web.Bind(forms.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost) + m.Post("/telegram/{id}", web.Bind(forms.NewTelegramHookForm{}), repo.TelegramHooksEditPost) + m.Post("/matrix/{id}", web.Bind(forms.NewMatrixHookForm{}), repo.MatrixHooksEditPost) + m.Post("/msteams/{id}", web.Bind(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost) + m.Post("/feishu/{id}", web.Bind(forms.NewFeishuHookForm{}), repo.FeishuHooksEditPost) + m.Post("/wechatwork/{id}", web.Bind(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksEditPost) + m.Post("/packagist/{id}", web.Bind(forms.NewPackagistHookForm{}), repo.PackagistHooksEditPost) }, webhooksEnabled) m.Group("/{configType:default-hooks|system-hooks}", func() { m.Get("/{type}/new", repo.WebhooksNew) - m.Post("/gitea/new", bindIgnErr(forms.NewWebhookForm{}), repo.GiteaHooksNewPost) - m.Post("/gogs/new", bindIgnErr(forms.NewGogshookForm{}), repo.GogsHooksNewPost) - m.Post("/slack/new", bindIgnErr(forms.NewSlackHookForm{}), repo.SlackHooksNewPost) - m.Post("/discord/new", bindIgnErr(forms.NewDiscordHookForm{}), repo.DiscordHooksNewPost) - m.Post("/dingtalk/new", bindIgnErr(forms.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost) - m.Post("/telegram/new", bindIgnErr(forms.NewTelegramHookForm{}), repo.TelegramHooksNewPost) - m.Post("/matrix/new", bindIgnErr(forms.NewMatrixHookForm{}), repo.MatrixHooksNewPost) - m.Post("/msteams/new", bindIgnErr(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost) - m.Post("/feishu/new", bindIgnErr(forms.NewFeishuHookForm{}), repo.FeishuHooksNewPost) - m.Post("/wechatwork/new", bindIgnErr(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksNewPost) - m.Post("/packagist/new", bindIgnErr(forms.NewPackagistHookForm{}), repo.PackagistHooksNewPost) + m.Post("/gitea/new", web.Bind(forms.NewWebhookForm{}), repo.GiteaHooksNewPost) + m.Post("/gogs/new", web.Bind(forms.NewGogshookForm{}), repo.GogsHooksNewPost) + m.Post("/slack/new", web.Bind(forms.NewSlackHookForm{}), repo.SlackHooksNewPost) + m.Post("/discord/new", web.Bind(forms.NewDiscordHookForm{}), repo.DiscordHooksNewPost) + m.Post("/dingtalk/new", web.Bind(forms.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost) + m.Post("/telegram/new", web.Bind(forms.NewTelegramHookForm{}), repo.TelegramHooksNewPost) + m.Post("/matrix/new", web.Bind(forms.NewMatrixHookForm{}), repo.MatrixHooksNewPost) + m.Post("/msteams/new", web.Bind(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost) + m.Post("/feishu/new", web.Bind(forms.NewFeishuHookForm{}), repo.FeishuHooksNewPost) + m.Post("/wechatwork/new", web.Bind(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksNewPost) + m.Post("/packagist/new", web.Bind(forms.NewPackagistHookForm{}), repo.PackagistHooksNewPost) }) m.Group("/auths", func() { m.Get("", admin.Authentications) - m.Combo("/new").Get(admin.NewAuthSource).Post(bindIgnErr(forms.AuthenticationForm{}), admin.NewAuthSourcePost) + m.Combo("/new").Get(admin.NewAuthSource).Post(web.Bind(forms.AuthenticationForm{}), admin.NewAuthSourcePost) m.Combo("/{authid}").Get(admin.EditAuthSource). - Post(bindIgnErr(forms.AuthenticationForm{}), admin.EditAuthSourcePost) + Post(web.Bind(forms.AuthenticationForm{}), admin.EditAuthSourcePost) m.Post("/{authid}/delete", admin.DeleteAuthSource) }) @@ -583,9 +608,9 @@ func RegisterRoutes(m *web.Route) { m.Group("/applications", func() { m.Get("", admin.Applications) - m.Post("/oauth2", bindIgnErr(forms.EditOAuth2ApplicationForm{}), admin.ApplicationsPost) + m.Post("/oauth2", web.Bind(forms.EditOAuth2ApplicationForm{}), admin.ApplicationsPost) m.Group("/oauth2/{id}", func() { - m.Combo("").Get(admin.EditApplication).Post(bindIgnErr(forms.EditOAuth2ApplicationForm{}), admin.EditApplicationPost) + m.Combo("").Get(admin.EditApplication).Post(web.Bind(forms.EditOAuth2ApplicationForm{}), admin.EditApplicationPost) m.Post("/regenerate_secret", admin.ApplicationsRegenerateSecret) m.Post("/delete", admin.DeleteApplication) }) @@ -603,15 +628,20 @@ func RegisterRoutes(m *web.Route) { m.Group("", func() { m.Get("/favicon.ico", func(ctx *context.Context) { - ctx.ServeFile(path.Join(setting.StaticRootPath, "public/img/favicon.png")) + ctx.SetServeHeaders(&context.ServeHeaderOptions{ + Filename: "favicon.png", + }) + http.ServeFile(ctx.Resp, ctx.Req, path.Join(setting.StaticRootPath, "public/img/favicon.png")) }) m.Group("/{username}", func() { m.Get(".png", func(ctx *context.Context) { ctx.Error(http.StatusNotFound) }) m.Get(".keys", user.ShowSSHKeys) m.Get(".gpg", user.ShowGPGKeys) - m.Get(".rss", feed.ShowUserFeedRSS) - m.Get(".atom", feed.ShowUserFeedAtom) + m.Get(".rss", feedEnabled, feed.ShowUserFeedRSS) + m.Get(".atom", feedEnabled, feed.ShowUserFeedAtom) m.Get("", user.Profile) + }, func(ctx *context.Context) { + ctx.Data["EnableFeed"] = setting.EnableFeed }, context_service.UserAssignmentWeb()) m.Get("/attachments/{uuid}", repo.GetAttachment) }, ignSignIn) @@ -625,7 +655,6 @@ func RegisterRoutes(m *web.Route) { reqRepoReleaseWriter := context.RequireRepoWriter(unit.TypeReleases) reqRepoReleaseReader := context.RequireRepoReader(unit.TypeReleases) reqRepoWikiWriter := context.RequireRepoWriter(unit.TypeWiki) - reqRepoIssueWriter := context.RequireRepoWriter(unit.TypeIssues) reqRepoIssueReader := context.RequireRepoReader(unit.TypeIssues) reqRepoPullsReader := context.RequireRepoReader(unit.TypePullRequests) reqRepoIssuesOrPullsWriter := context.RequireRepoWriterOr(unit.TypeIssues, unit.TypePullRequests) @@ -651,7 +680,7 @@ func RegisterRoutes(m *web.Route) { m.Group("/org", func() { m.Group("", func() { m.Get("/create", org.Create) - m.Post("/create", bindIgnErr(forms.CreateOrgForm{}), org.CreatePost) + m.Post("/create", web.Bind(forms.CreateOrgForm{}), org.CreatePost) }) m.Group("/invite/{token}", func() { @@ -681,22 +710,22 @@ func RegisterRoutes(m *web.Route) { m.Group("/{org}", func() { m.Get("/teams/new", org.NewTeam) - m.Post("/teams/new", bindIgnErr(forms.CreateTeamForm{}), org.NewTeamPost) + m.Post("/teams/new", web.Bind(forms.CreateTeamForm{}), org.NewTeamPost) m.Get("/teams/-/search", org.SearchTeam) m.Get("/teams/{team}/edit", org.EditTeam) - m.Post("/teams/{team}/edit", bindIgnErr(forms.CreateTeamForm{}), org.EditTeamPost) + m.Post("/teams/{team}/edit", web.Bind(forms.CreateTeamForm{}), org.EditTeamPost) m.Post("/teams/{team}/delete", org.DeleteTeam) m.Group("/settings", func() { m.Combo("").Get(org.Settings). - Post(bindIgnErr(forms.UpdateOrgSettingForm{}), org.SettingsPost) - m.Post("/avatar", bindIgnErr(forms.AvatarForm{}), org.SettingsAvatar) + Post(web.Bind(forms.UpdateOrgSettingForm{}), org.SettingsPost) + m.Post("/avatar", web.Bind(forms.AvatarForm{}), org.SettingsAvatar) m.Post("/avatar/delete", org.SettingsDeleteAvatar) m.Group("/applications", func() { m.Get("", org.Applications) - m.Post("/oauth2", bindIgnErr(forms.EditOAuth2ApplicationForm{}), org.OAuthApplicationsPost) + m.Post("/oauth2", web.Bind(forms.EditOAuth2ApplicationForm{}), org.OAuthApplicationsPost) m.Group("/oauth2/{id}", func() { - m.Combo("").Get(org.OAuth2ApplicationShow).Post(bindIgnErr(forms.EditOAuth2ApplicationForm{}), org.OAuth2ApplicationEdit) + m.Combo("").Get(org.OAuth2ApplicationShow).Post(web.Bind(forms.EditOAuth2ApplicationForm{}), org.OAuth2ApplicationEdit) m.Post("/regenerate_secret", org.OAuthApplicationsRegenerateSecret) m.Post("/delete", org.DeleteOAuth2Application) }) @@ -711,43 +740,59 @@ func RegisterRoutes(m *web.Route) { m.Get("", org.Webhooks) m.Post("/delete", org.DeleteWebhook) m.Get("/{type}/new", repo.WebhooksNew) - m.Post("/gitea/new", bindIgnErr(forms.NewWebhookForm{}), repo.GiteaHooksNewPost) - m.Post("/gogs/new", bindIgnErr(forms.NewGogshookForm{}), repo.GogsHooksNewPost) - m.Post("/slack/new", bindIgnErr(forms.NewSlackHookForm{}), repo.SlackHooksNewPost) - m.Post("/discord/new", bindIgnErr(forms.NewDiscordHookForm{}), repo.DiscordHooksNewPost) - m.Post("/dingtalk/new", bindIgnErr(forms.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost) - m.Post("/telegram/new", bindIgnErr(forms.NewTelegramHookForm{}), repo.TelegramHooksNewPost) - m.Post("/matrix/new", bindIgnErr(forms.NewMatrixHookForm{}), repo.MatrixHooksNewPost) - m.Post("/msteams/new", bindIgnErr(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost) - m.Post("/feishu/new", bindIgnErr(forms.NewFeishuHookForm{}), repo.FeishuHooksNewPost) - m.Post("/wechatwork/new", bindIgnErr(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksNewPost) + m.Post("/gitea/new", web.Bind(forms.NewWebhookForm{}), repo.GiteaHooksNewPost) + m.Post("/gogs/new", web.Bind(forms.NewGogshookForm{}), repo.GogsHooksNewPost) + m.Post("/slack/new", web.Bind(forms.NewSlackHookForm{}), repo.SlackHooksNewPost) + m.Post("/discord/new", web.Bind(forms.NewDiscordHookForm{}), repo.DiscordHooksNewPost) + m.Post("/dingtalk/new", web.Bind(forms.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost) + m.Post("/telegram/new", web.Bind(forms.NewTelegramHookForm{}), repo.TelegramHooksNewPost) + m.Post("/matrix/new", web.Bind(forms.NewMatrixHookForm{}), repo.MatrixHooksNewPost) + m.Post("/msteams/new", web.Bind(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost) + m.Post("/feishu/new", web.Bind(forms.NewFeishuHookForm{}), repo.FeishuHooksNewPost) + m.Post("/wechatwork/new", web.Bind(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksNewPost) m.Group("/{id}", func() { m.Get("", repo.WebHooksEdit) m.Post("/replay/{uuid}", repo.ReplayWebhook) }) - m.Post("/gitea/{id}", bindIgnErr(forms.NewWebhookForm{}), repo.GiteaHooksEditPost) - m.Post("/gogs/{id}", bindIgnErr(forms.NewGogshookForm{}), repo.GogsHooksEditPost) - m.Post("/slack/{id}", bindIgnErr(forms.NewSlackHookForm{}), repo.SlackHooksEditPost) - m.Post("/discord/{id}", bindIgnErr(forms.NewDiscordHookForm{}), repo.DiscordHooksEditPost) - m.Post("/dingtalk/{id}", bindIgnErr(forms.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost) - m.Post("/telegram/{id}", bindIgnErr(forms.NewTelegramHookForm{}), repo.TelegramHooksEditPost) - m.Post("/matrix/{id}", bindIgnErr(forms.NewMatrixHookForm{}), repo.MatrixHooksEditPost) - m.Post("/msteams/{id}", bindIgnErr(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost) - m.Post("/feishu/{id}", bindIgnErr(forms.NewFeishuHookForm{}), repo.FeishuHooksEditPost) - m.Post("/wechatwork/{id}", bindIgnErr(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksEditPost) + m.Post("/gitea/{id}", web.Bind(forms.NewWebhookForm{}), repo.GiteaHooksEditPost) + m.Post("/gogs/{id}", web.Bind(forms.NewGogshookForm{}), repo.GogsHooksEditPost) + m.Post("/slack/{id}", web.Bind(forms.NewSlackHookForm{}), repo.SlackHooksEditPost) + m.Post("/discord/{id}", web.Bind(forms.NewDiscordHookForm{}), repo.DiscordHooksEditPost) + m.Post("/dingtalk/{id}", web.Bind(forms.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost) + m.Post("/telegram/{id}", web.Bind(forms.NewTelegramHookForm{}), repo.TelegramHooksEditPost) + m.Post("/matrix/{id}", web.Bind(forms.NewMatrixHookForm{}), repo.MatrixHooksEditPost) + m.Post("/msteams/{id}", web.Bind(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost) + m.Post("/feishu/{id}", web.Bind(forms.NewFeishuHookForm{}), repo.FeishuHooksEditPost) + m.Post("/wechatwork/{id}", web.Bind(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksEditPost) }, webhooksEnabled) m.Group("/labels", func() { m.Get("", org.RetrieveLabels, org.Labels) - m.Post("/new", bindIgnErr(forms.CreateLabelForm{}), org.NewLabel) - m.Post("/edit", bindIgnErr(forms.CreateLabelForm{}), org.UpdateLabel) + m.Post("/new", web.Bind(forms.CreateLabelForm{}), org.NewLabel) + m.Post("/edit", web.Bind(forms.CreateLabelForm{}), org.UpdateLabel) m.Post("/delete", org.DeleteLabel) - m.Post("/initialize", bindIgnErr(forms.InitializeLabelsForm{}), org.InitializeLabels) + m.Post("/initialize", web.Bind(forms.InitializeLabelsForm{}), org.InitializeLabels) }) m.Route("/delete", "GET,POST", org.SettingsDelete) + + m.Group("/packages", func() { + m.Get("", org.Packages) + m.Group("/rules", func() { + m.Group("/add", func() { + m.Get("", org.PackagesRuleAdd) + m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), org.PackagesRuleAddPost) + }) + m.Group("/{id}", func() { + m.Get("", org.PackagesRuleEdit) + m.Post("", web.Bind(forms.PackageCleanupRuleForm{}), org.PackagesRuleEditPost) + m.Get("/preview", org.PackagesRulePreview) + }) + }) + }, packagesEnabled) }, func(ctx *context.Context) { ctx.Data["EnableOAuth2"] = setting.OAuth2.Enable + ctx.Data["EnablePackages"] = setting.Packages.Enabled }) }, context.OrgAssignment(true, true)) }, reqSignIn) @@ -756,12 +801,12 @@ func RegisterRoutes(m *web.Route) { // ***** START: Repository ***** m.Group("/repo", func() { m.Get("/create", repo.Create) - m.Post("/create", bindIgnErr(forms.CreateRepoForm{}), repo.CreatePost) + m.Post("/create", web.Bind(forms.CreateRepoForm{}), repo.CreatePost) m.Get("/migrate", repo.Migrate) - m.Post("/migrate", bindIgnErr(forms.MigrateRepoForm{}), repo.MigratePost) + m.Post("/migrate", web.Bind(forms.MigrateRepoForm{}), repo.MigratePost) m.Group("/fork", func() { m.Combo("/{repoid}").Get(repo.Fork). - Post(bindIgnErr(forms.CreateRepoForm{}), repo.ForkPost) + Post(web.Bind(forms.CreateRepoForm{}), repo.ForkPost) }, context.RepoIDAssignment(), context.UnitTypes(), reqRepoCodeReader) m.Get("/search", repo.SearchRepo) }, reqSignIn) @@ -778,7 +823,7 @@ func RegisterRoutes(m *web.Route) { m.Get("/files/{fileid}", user.DownloadPackageFile) m.Group("/settings", func() { m.Get("", user.PackageSettings) - m.Post("", bindIgnErr(forms.PackageSettingForm{}), user.PackageSettingsPost) + m.Post("", web.Bind(forms.PackageSettingForm{}), user.PackageSettingsPost) }, reqPackageAccess(perm.AccessModeWrite)) }) }) @@ -794,9 +839,9 @@ func RegisterRoutes(m *web.Route) { m.Group("/settings", func() { m.Group("", func() { m.Combo("").Get(repo.Settings). - Post(bindIgnErr(forms.RepoSettingForm{}), repo.SettingsPost) + Post(web.Bind(forms.RepoSettingForm{}), repo.SettingsPost) }, repo.SettingsCtxData) - m.Post("/avatar", bindIgnErr(forms.AvatarForm{}), repo.SettingsAvatar) + m.Post("/avatar", web.Bind(forms.AvatarForm{}), repo.SettingsAvatar) m.Post("/avatar/delete", repo.SettingsDeleteAvatar) m.Group("/collaboration", func() { @@ -812,16 +857,16 @@ func RegisterRoutes(m *web.Route) { m.Group("/branches", func() { m.Combo("").Get(repo.ProtectedBranch).Post(repo.ProtectedBranchPost) m.Combo("/*").Get(repo.SettingsProtectedBranch). - Post(bindIgnErr(forms.ProtectBranchForm{}), context.RepoMustNotBeArchived(), repo.SettingsProtectedBranchPost) + Post(web.Bind(forms.ProtectBranchForm{}), context.RepoMustNotBeArchived(), repo.SettingsProtectedBranchPost) }, repo.MustBeNotEmpty) - m.Post("/rename_branch", bindIgnErr(forms.RenameBranchForm{}), context.RepoMustNotBeArchived(), repo.RenameBranchPost) + m.Post("/rename_branch", web.Bind(forms.RenameBranchForm{}), context.RepoMustNotBeArchived(), repo.RenameBranchPost) m.Group("/tags", func() { m.Get("", repo.Tags) - m.Post("", bindIgnErr(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo.NewProtectedTagPost) + m.Post("", web.Bind(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo.NewProtectedTagPost) m.Post("/delete", context.RepoMustNotBeArchived(), repo.DeleteProtectedTagPost) m.Get("/{id}", repo.EditProtectedTag) - m.Post("/{id}", bindIgnErr(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo.EditProtectedTagPost) + m.Post("/{id}", web.Bind(forms.ProtectTagForm{}), context.RepoMustNotBeArchived(), repo.EditProtectedTagPost) }) m.Group("/hooks/git", func() { @@ -834,38 +879,38 @@ func RegisterRoutes(m *web.Route) { m.Get("", repo.Webhooks) m.Post("/delete", repo.DeleteWebhook) m.Get("/{type}/new", repo.WebhooksNew) - m.Post("/gitea/new", bindIgnErr(forms.NewWebhookForm{}), repo.GiteaHooksNewPost) - m.Post("/gogs/new", bindIgnErr(forms.NewGogshookForm{}), repo.GogsHooksNewPost) - m.Post("/slack/new", bindIgnErr(forms.NewSlackHookForm{}), repo.SlackHooksNewPost) - m.Post("/discord/new", bindIgnErr(forms.NewDiscordHookForm{}), repo.DiscordHooksNewPost) - m.Post("/dingtalk/new", bindIgnErr(forms.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost) - m.Post("/telegram/new", bindIgnErr(forms.NewTelegramHookForm{}), repo.TelegramHooksNewPost) - m.Post("/matrix/new", bindIgnErr(forms.NewMatrixHookForm{}), repo.MatrixHooksNewPost) - m.Post("/msteams/new", bindIgnErr(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost) - m.Post("/feishu/new", bindIgnErr(forms.NewFeishuHookForm{}), repo.FeishuHooksNewPost) - m.Post("/wechatwork/new", bindIgnErr(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksNewPost) - m.Post("/packagist/new", bindIgnErr(forms.NewPackagistHookForm{}), repo.PackagistHooksNewPost) + m.Post("/gitea/new", web.Bind(forms.NewWebhookForm{}), repo.GiteaHooksNewPost) + m.Post("/gogs/new", web.Bind(forms.NewGogshookForm{}), repo.GogsHooksNewPost) + m.Post("/slack/new", web.Bind(forms.NewSlackHookForm{}), repo.SlackHooksNewPost) + m.Post("/discord/new", web.Bind(forms.NewDiscordHookForm{}), repo.DiscordHooksNewPost) + m.Post("/dingtalk/new", web.Bind(forms.NewDingtalkHookForm{}), repo.DingtalkHooksNewPost) + m.Post("/telegram/new", web.Bind(forms.NewTelegramHookForm{}), repo.TelegramHooksNewPost) + m.Post("/matrix/new", web.Bind(forms.NewMatrixHookForm{}), repo.MatrixHooksNewPost) + m.Post("/msteams/new", web.Bind(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksNewPost) + m.Post("/feishu/new", web.Bind(forms.NewFeishuHookForm{}), repo.FeishuHooksNewPost) + m.Post("/wechatwork/new", web.Bind(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksNewPost) + m.Post("/packagist/new", web.Bind(forms.NewPackagistHookForm{}), repo.PackagistHooksNewPost) m.Group("/{id}", func() { m.Get("", repo.WebHooksEdit) m.Post("/test", repo.TestWebhook) m.Post("/replay/{uuid}", repo.ReplayWebhook) }) - m.Post("/gitea/{id}", bindIgnErr(forms.NewWebhookForm{}), repo.GiteaHooksEditPost) - m.Post("/gogs/{id}", bindIgnErr(forms.NewGogshookForm{}), repo.GogsHooksEditPost) - m.Post("/slack/{id}", bindIgnErr(forms.NewSlackHookForm{}), repo.SlackHooksEditPost) - m.Post("/discord/{id}", bindIgnErr(forms.NewDiscordHookForm{}), repo.DiscordHooksEditPost) - m.Post("/dingtalk/{id}", bindIgnErr(forms.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost) - m.Post("/telegram/{id}", bindIgnErr(forms.NewTelegramHookForm{}), repo.TelegramHooksEditPost) - m.Post("/matrix/{id}", bindIgnErr(forms.NewMatrixHookForm{}), repo.MatrixHooksEditPost) - m.Post("/msteams/{id}", bindIgnErr(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost) - m.Post("/feishu/{id}", bindIgnErr(forms.NewFeishuHookForm{}), repo.FeishuHooksEditPost) - m.Post("/wechatwork/{id}", bindIgnErr(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksEditPost) - m.Post("/packagist/{id}", bindIgnErr(forms.NewPackagistHookForm{}), repo.PackagistHooksEditPost) + m.Post("/gitea/{id}", web.Bind(forms.NewWebhookForm{}), repo.GiteaHooksEditPost) + m.Post("/gogs/{id}", web.Bind(forms.NewGogshookForm{}), repo.GogsHooksEditPost) + m.Post("/slack/{id}", web.Bind(forms.NewSlackHookForm{}), repo.SlackHooksEditPost) + m.Post("/discord/{id}", web.Bind(forms.NewDiscordHookForm{}), repo.DiscordHooksEditPost) + m.Post("/dingtalk/{id}", web.Bind(forms.NewDingtalkHookForm{}), repo.DingtalkHooksEditPost) + m.Post("/telegram/{id}", web.Bind(forms.NewTelegramHookForm{}), repo.TelegramHooksEditPost) + m.Post("/matrix/{id}", web.Bind(forms.NewMatrixHookForm{}), repo.MatrixHooksEditPost) + m.Post("/msteams/{id}", web.Bind(forms.NewMSTeamsHookForm{}), repo.MSTeamsHooksEditPost) + m.Post("/feishu/{id}", web.Bind(forms.NewFeishuHookForm{}), repo.FeishuHooksEditPost) + m.Post("/wechatwork/{id}", web.Bind(forms.NewWechatWorkHookForm{}), repo.WechatworkHooksEditPost) + m.Post("/packagist/{id}", web.Bind(forms.NewPackagistHookForm{}), repo.PackagistHooksEditPost) }, webhooksEnabled) m.Group("/keys", func() { m.Combo("").Get(repo.DeployKeys). - Post(bindIgnErr(forms.AddKeyForm{}), repo.DeployKeysPost) + Post(web.Bind(forms.AddKeyForm{}), repo.DeployKeysPost) m.Post("/delete", repo.DeleteDeployKey) }) @@ -904,7 +949,7 @@ func RegisterRoutes(m *web.Route) { m.Get("/compare", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists, ignSignIn, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff) m.Combo("/compare/*", repo.MustBeNotEmpty, reqRepoCodeReader, repo.SetEditorconfigIfExists). Get(ignSignIn, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.CompareDiff). - Post(reqSignIn, context.RepoMustNotBeArchived(), reqRepoPullsReader, repo.MustAllowPulls, bindIgnErr(forms.CreateIssueForm{}), repo.SetWhitespaceBehavior, repo.CompareAndPullRequestPost) + Post(reqSignIn, context.RepoMustNotBeArchived(), reqRepoPullsReader, repo.MustAllowPulls, web.Bind(forms.CreateIssueForm{}), repo.SetWhitespaceBehavior, repo.CompareAndPullRequestPost) m.Group("/{type:issues|pulls}", func() { m.Group("/{index}", func() { m.Get("/info", repo.GetIssueInfo) @@ -917,7 +962,7 @@ func RegisterRoutes(m *web.Route) { m.Group("/issues", func() { m.Group("/new", func() { m.Combo("").Get(context.RepoRef(), repo.NewIssue). - Post(bindIgnErr(forms.CreateIssueForm{}), repo.NewIssuePost) + Post(web.Bind(forms.CreateIssueForm{}), repo.NewIssuePost) m.Get("/choose", context.RepoRef(), repo.NewIssueChooseTemplate) }) m.Get("/search", repo.ListIssues) @@ -928,7 +973,7 @@ func RegisterRoutes(m *web.Route) { m.Group("/{index}", func() { m.Post("/title", repo.UpdateIssueTitle) m.Post("/content", repo.UpdateIssueContent) - m.Post("/deadline", bindIgnErr(structs.EditDeadlineOption{}), repo.UpdateIssueDeadline) + m.Post("/deadline", web.Bind(structs.EditDeadlineOption{}), repo.UpdateIssueDeadline) m.Post("/watch", repo.IssueWatch) m.Post("/ref", repo.UpdateIssueRef) m.Post("/viewed-files", repo.UpdateViewedFiles) @@ -936,18 +981,18 @@ func RegisterRoutes(m *web.Route) { m.Post("/add", repo.AddDependency) m.Post("/delete", repo.RemoveDependency) }) - m.Combo("/comments").Post(repo.MustAllowUserComment, bindIgnErr(forms.CreateCommentForm{}), repo.NewComment) + m.Combo("/comments").Post(repo.MustAllowUserComment, web.Bind(forms.CreateCommentForm{}), repo.NewComment) m.Group("/times", func() { - m.Post("/add", bindIgnErr(forms.AddTimeManuallyForm{}), repo.AddTimeManually) + m.Post("/add", web.Bind(forms.AddTimeManuallyForm{}), repo.AddTimeManually) m.Post("/{timeid}/delete", repo.DeleteTime) m.Group("/stopwatch", func() { m.Post("/toggle", repo.IssueStopwatch) m.Post("/cancel", repo.CancelStopwatch) }) }) - m.Post("/reactions/{action}", bindIgnErr(forms.ReactionForm{}), repo.ChangeIssueReaction) - m.Post("/lock", reqRepoIssueWriter, bindIgnErr(forms.IssueLockForm{}), repo.LockIssue) - m.Post("/unlock", reqRepoIssueWriter, repo.UnlockIssue) + m.Post("/reactions/{action}", web.Bind(forms.ReactionForm{}), repo.ChangeIssueReaction) + m.Post("/lock", reqRepoIssuesOrPullsWriter, web.Bind(forms.IssueLockForm{}), repo.LockIssue) + m.Post("/unlock", reqRepoIssuesOrPullsWriter, repo.UnlockIssue) m.Post("/delete", reqRepoAdmin, repo.DeleteIssue) }, context.RepoMustNotBeArchived()) m.Group("/{index}", func() { @@ -963,7 +1008,7 @@ func RegisterRoutes(m *web.Route) { m.Post("/projects", reqRepoIssuesOrPullsWriter, reqRepoProjectsReader, repo.UpdateIssueProject) m.Post("/assignee", reqRepoIssuesOrPullsWriter, repo.UpdateIssueAssignee) m.Post("/request_review", reqRepoIssuesOrPullsReader, repo.UpdatePullReviewRequest) - m.Post("/dismiss_review", reqRepoAdmin, bindIgnErr(forms.DismissReviewForm{}), repo.DismissReview) + m.Post("/dismiss_review", reqRepoAdmin, web.Bind(forms.DismissReviewForm{}), repo.DismissReview) m.Post("/status", reqRepoIssuesOrPullsWriter, repo.UpdateIssueStatus) m.Post("/resolve_conversation", reqRepoIssuesOrPullsReader, repo.UpdateResolveConversation) m.Post("/attachments", repo.UploadIssueAttachment) @@ -972,23 +1017,23 @@ func RegisterRoutes(m *web.Route) { m.Group("/comments/{id}", func() { m.Post("", repo.UpdateCommentContent) m.Post("/delete", repo.DeleteComment) - m.Post("/reactions/{action}", bindIgnErr(forms.ReactionForm{}), repo.ChangeCommentReaction) + m.Post("/reactions/{action}", web.Bind(forms.ReactionForm{}), repo.ChangeCommentReaction) }, context.RepoMustNotBeArchived()) m.Group("/comments/{id}", func() { m.Get("/attachments", repo.GetCommentAttachments) }) - m.Post("/markdown", bindIgnErr(structs.MarkdownOption{}), misc.Markdown) + m.Post("/markdown", web.Bind(structs.MarkdownOption{}), misc.Markdown) m.Group("/labels", func() { - m.Post("/new", bindIgnErr(forms.CreateLabelForm{}), repo.NewLabel) - m.Post("/edit", bindIgnErr(forms.CreateLabelForm{}), repo.UpdateLabel) + m.Post("/new", web.Bind(forms.CreateLabelForm{}), repo.NewLabel) + m.Post("/edit", web.Bind(forms.CreateLabelForm{}), repo.UpdateLabel) m.Post("/delete", repo.DeleteLabel) - m.Post("/initialize", bindIgnErr(forms.InitializeLabelsForm{}), repo.InitializeLabels) + m.Post("/initialize", web.Bind(forms.InitializeLabelsForm{}), repo.InitializeLabels) }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef()) m.Group("/milestones", func() { m.Combo("/new").Get(repo.NewMilestone). - Post(bindIgnErr(forms.CreateMilestoneForm{}), repo.NewMilestonePost) + Post(web.Bind(forms.CreateMilestoneForm{}), repo.NewMilestonePost) m.Get("/{id}/edit", repo.EditMilestone) - m.Post("/{id}/edit", bindIgnErr(forms.CreateMilestoneForm{}), repo.EditMilestonePost) + m.Post("/{id}/edit", web.Bind(forms.CreateMilestoneForm{}), repo.EditMilestonePost) m.Post("/{id}/{action}", repo.ChangeMilestoneStatus) m.Post("/delete", repo.DeleteMilestone) }, context.RepoMustNotBeArchived(), reqRepoIssuesOrPullsWriter, context.RepoRef()) @@ -999,23 +1044,23 @@ func RegisterRoutes(m *web.Route) { m.Group("", func() { m.Group("", func() { m.Combo("/_edit/*").Get(repo.EditFile). - Post(bindIgnErr(forms.EditRepoFileForm{}), repo.EditFilePost) + Post(web.Bind(forms.EditRepoFileForm{}), repo.EditFilePost) m.Combo("/_new/*").Get(repo.NewFile). - Post(bindIgnErr(forms.EditRepoFileForm{}), repo.NewFilePost) - m.Post("/_preview/*", bindIgnErr(forms.EditPreviewDiffForm{}), repo.DiffPreviewPost) + Post(web.Bind(forms.EditRepoFileForm{}), repo.NewFilePost) + m.Post("/_preview/*", web.Bind(forms.EditPreviewDiffForm{}), repo.DiffPreviewPost) m.Combo("/_delete/*").Get(repo.DeleteFile). - Post(bindIgnErr(forms.DeleteRepoFileForm{}), repo.DeleteFilePost) + Post(web.Bind(forms.DeleteRepoFileForm{}), repo.DeleteFilePost) m.Combo("/_upload/*", repo.MustBeAbleToUpload). Get(repo.UploadFile). - Post(bindIgnErr(forms.UploadRepoFileForm{}), repo.UploadFilePost) + Post(web.Bind(forms.UploadRepoFileForm{}), repo.UploadFilePost) m.Combo("/_diffpatch/*").Get(repo.NewDiffPatch). - Post(bindIgnErr(forms.EditRepoFileForm{}), repo.NewDiffPatchPost) + Post(web.Bind(forms.EditRepoFileForm{}), repo.NewDiffPatchPost) m.Combo("/_cherrypick/{sha:([a-f0-9]{7,40})}/*").Get(repo.CherryPick). - Post(bindIgnErr(forms.CherryPickForm{}), repo.CherryPickPost) + Post(web.Bind(forms.CherryPickForm{}), repo.CherryPickPost) }, repo.MustBeEditable) m.Group("", func() { m.Post("/upload-file", repo.UploadFileToServer) - m.Post("/upload-remove", bindIgnErr(forms.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer) + m.Post("/upload-remove", web.Bind(forms.RemoveUploadFileForm{}), repo.RemoveUploadFileFromServer) }, repo.MustBeEditable, repo.MustBeAbleToUpload) }, context.RepoRef(), canEnableEditor, context.RepoMustNotBeArchived(), repo.MustBeNotEmpty) @@ -1024,7 +1069,7 @@ func RegisterRoutes(m *web.Route) { m.Post("/branch/*", context.RepoRefByType(context.RepoRefBranch), repo.CreateBranch) m.Post("/tag/*", context.RepoRefByType(context.RepoRefTag), repo.CreateBranch) m.Post("/commit/*", context.RepoRefByType(context.RepoRefCommit), repo.CreateBranch) - }, bindIgnErr(forms.NewBranchForm{})) + }, web.Bind(forms.NewBranchForm{})) m.Post("/delete", repo.DeleteBranchPost) m.Post("/restore", repo.RestoreBranchPost) }, context.RepoMustNotBeArchived(), reqRepoCodeWriter, repo.MustBeNotEmpty) @@ -1042,7 +1087,7 @@ func RegisterRoutes(m *web.Route) { m.Get("/releases/attachments/{uuid}", repo.GetAttachment, repo.MustBeNotEmpty, reqRepoReleaseReader) m.Group("/releases", func() { m.Get("/new", repo.NewRelease) - m.Post("/new", bindIgnErr(forms.NewReleaseForm{}), repo.NewReleasePost) + m.Post("/new", web.Bind(forms.NewReleaseForm{}), repo.NewReleasePost) m.Post("/delete", repo.DeleteRelease) m.Post("/attachments", repo.UploadReleaseAttachment) m.Post("/attachments/remove", repo.DeleteAttachment) @@ -1051,7 +1096,7 @@ func RegisterRoutes(m *web.Route) { repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoCodeWriter, context.RepoRef()) m.Group("/releases", func() { m.Get("/edit/*", repo.EditRelease) - m.Post("/edit/*", bindIgnErr(forms.EditReleaseForm{}), repo.EditReleasePost) + m.Post("/edit/*", web.Bind(forms.EditReleaseForm{}), repo.EditReleasePost) }, reqSignIn, repo.MustBeNotEmpty, context.RepoMustNotBeArchived(), reqRepoReleaseWriter, func(ctx *context.Context) { var err error ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch) @@ -1100,17 +1145,17 @@ func RegisterRoutes(m *web.Route) { m.Get("/{id}", repo.ViewProject) m.Group("", func() { m.Get("/new", repo.NewProject) - m.Post("/new", bindIgnErr(forms.CreateProjectForm{}), repo.NewProjectPost) + m.Post("/new", web.Bind(forms.CreateProjectForm{}), repo.NewProjectPost) m.Group("/{id}", func() { - m.Post("", bindIgnErr(forms.EditProjectBoardForm{}), repo.AddBoardToProjectPost) + m.Post("", web.Bind(forms.EditProjectBoardForm{}), repo.AddBoardToProjectPost) m.Post("/delete", repo.DeleteProject) m.Get("/edit", repo.EditProject) - m.Post("/edit", bindIgnErr(forms.CreateProjectForm{}), repo.EditProjectPost) + m.Post("/edit", web.Bind(forms.CreateProjectForm{}), repo.EditProjectPost) m.Post("/{action:open|close}", repo.ChangeProjectStatus) m.Group("/{boardID}", func() { - m.Put("", bindIgnErr(forms.EditProjectBoardForm{}), repo.EditProjectBoard) + m.Put("", web.Bind(forms.EditProjectBoardForm{}), repo.EditProjectBoard) m.Delete("", repo.DeleteProjectBoard) m.Post("/default", repo.SetDefaultProjectBoard) @@ -1126,14 +1171,14 @@ func RegisterRoutes(m *web.Route) { Post(context.RepoMustNotBeArchived(), reqSignIn, reqRepoWikiWriter, - bindIgnErr(forms.NewWikiForm{}), + web.Bind(forms.NewWikiForm{}), repo.WikiPost) m.Combo("/*"). Get(repo.Wiki). Post(context.RepoMustNotBeArchived(), reqSignIn, reqRepoWikiWriter, - bindIgnErr(forms.NewWikiForm{}), + web.Bind(forms.NewWikiForm{}), repo.WikiPost) m.Get("/commit/{sha:[a-f0-9]{7,40}}", repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.Diff) m.Get("/commit/{sha:[a-f0-9]{7,40}}.{ext:patch|diff}", repo.RawDiff) @@ -1191,17 +1236,17 @@ func RegisterRoutes(m *web.Route) { m.Get(".diff", repo.DownloadPullDiff) m.Get(".patch", repo.DownloadPullPatch) m.Get("/commits", context.RepoRef(), repo.ViewPullCommits) - m.Post("/merge", context.RepoMustNotBeArchived(), bindIgnErr(forms.MergePullRequestForm{}), repo.MergePullRequest) + m.Post("/merge", context.RepoMustNotBeArchived(), web.Bind(forms.MergePullRequestForm{}), repo.MergePullRequest) m.Post("/cancel_auto_merge", context.RepoMustNotBeArchived(), repo.CancelAutoMergePullRequest) m.Post("/update", repo.UpdatePullRequest) - m.Post("/set_allow_maintainer_edit", bindIgnErr(forms.UpdateAllowEditsForm{}), repo.SetAllowEdits) + m.Post("/set_allow_maintainer_edit", web.Bind(forms.UpdateAllowEditsForm{}), repo.SetAllowEdits) m.Post("/cleanup", context.RepoMustNotBeArchived(), context.RepoRef(), repo.CleanUpPullRequest) m.Group("/files", func() { m.Get("", context.RepoRef(), repo.SetEditorconfigIfExists, repo.SetDiffViewStyle, repo.SetWhitespaceBehavior, repo.ViewPullFiles) m.Group("/reviews", func() { m.Get("/new_comment", repo.RenderNewCodeCommentForm) - m.Post("/comments", bindIgnErr(forms.CodeCommentForm{}), repo.CreateCodeComment) - m.Post("/submit", bindIgnErr(forms.SubmitReviewForm{}), repo.SubmitReview) + m.Post("/comments", web.Bind(forms.CodeCommentForm{}), repo.CreateCodeComment) + m.Post("/submit", web.Bind(forms.SubmitReviewForm{}), repo.SubmitReview) }, context.RepoMustNotBeArchived()) }) }, repo.MustAllowPulls) diff --git a/routers/web/webfinger.go b/routers/web/webfinger.go index 3b4977a3af..656982c9ac 100644 --- a/routers/web/webfinger.go +++ b/routers/web/webfinger.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package web diff --git a/services/activitypub/client.go b/services/activitypub/client.go index 9bcef69de1..ed5c9990d6 100644 --- a/services/activitypub/client.go +++ b/services/activitypub/client.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package activitypub diff --git a/services/activitypub/client_test.go b/services/activitypub/client_test.go index 62068d53b3..0ab512c5ba 100644 --- a/services/activitypub/client_test.go +++ b/services/activitypub/client_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package activitypub @@ -36,7 +35,7 @@ func TestActivityPubSignedPost(t *testing.T) { body, err := io.ReadAll(r.Body) assert.NoError(t, err) assert.Equal(t, expected, string(body)) - fmt.Fprintf(w, expected) + fmt.Fprint(w, expected) })) defer srv.Close() diff --git a/services/activitypub/iri.go b/services/activitypub/iri.go index f74c027222..e5752a1efb 100644 --- a/services/activitypub/iri.go +++ b/services/activitypub/iri.go @@ -76,7 +76,7 @@ func RepositoryIRIToRepository(ctx context.Context, repoIRI ap.IRI) (*repo_model } // TODO: create remote repo if not exists - return repo_model.GetRepositoryByOwnerAndName(username, reponame) + return repo_model.GetRepositoryByOwnerAndName(ctx, username, reponame) } // Returns the owner, repo name, and idx of a Ticket object IRI diff --git a/services/activitypub/keypair.go b/services/activitypub/keypair.go index fe6aba9058..299bdc43e3 100644 --- a/services/activitypub/keypair.go +++ b/services/activitypub/keypair.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package activitypub diff --git a/services/activitypub/keypair_test.go b/services/activitypub/keypair_test.go index defe498614..888254c9da 100644 --- a/services/activitypub/keypair_test.go +++ b/services/activitypub/keypair_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package activitypub diff --git a/services/activitypub/main_test.go b/services/activitypub/main_test.go index 7fa2b09265..15399ca380 100644 --- a/services/activitypub/main_test.go +++ b/services/activitypub/main_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package activitypub diff --git a/services/activitypub/objects.go b/services/activitypub/objects.go index 0169194cda..82427d36f8 100644 --- a/services/activitypub/objects.go +++ b/services/activitypub/objects.go @@ -16,11 +16,11 @@ import ( // Construct a Note object from a comment func Note(comment *issues_model.Comment) (*ap.Note, error) { - err := comment.LoadPoster() + err := comment.LoadPoster(db.DefaultContext) if err != nil { return nil, err } - err = comment.LoadIssue() + err = comment.LoadIssue(db.DefaultContext) if err != nil { return nil, err } @@ -60,7 +60,7 @@ func Ticket(issue *issues_model.Issue) (*forgefed.Ticket, error) { } ticket.Context = ap.IRI(issue.Repo.GetIRI()) - err = issue.LoadPoster() + err = issue.LoadPoster(db.DefaultContext) if err != nil { return nil, err } diff --git a/services/activitypub/user_settings.go b/services/activitypub/user_settings.go index fc9775b0f0..ec5fa59842 100644 --- a/services/activitypub/user_settings.go +++ b/services/activitypub/user_settings.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package activitypub @@ -11,7 +10,7 @@ import ( // GetKeyPair function returns a user's private and public keys func GetKeyPair(user *user_model.User) (pub, priv string, err error) { var settings map[string]*user_model.Setting - settings, err = user_model.GetUserSettings(user.ID, []string{user_model.UserActivityPubPrivPem, user_model.UserActivityPubPubPem}) + settings, err = user_model.GetSettings(user.ID, []string{user_model.UserActivityPubPrivPem, user_model.UserActivityPubPubPem}) if err != nil { return } else if len(settings) == 0 { diff --git a/services/activitypub/user_settings_test.go b/services/activitypub/user_settings_test.go index beefde232f..78ebf8e824 100644 --- a/services/activitypub/user_settings_test.go +++ b/services/activitypub/user_settings_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package activitypub diff --git a/services/agit/agit.go b/services/agit/agit.go index a7e701d6c4..b61cb6f3f5 100644 --- a/services/agit/agit.go +++ b/services/agit/agit.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package agit @@ -96,7 +95,7 @@ func ProcReceive(ctx context.Context, repo *repo_model.Repository, gitRepo *git. headBranch = curentTopicBranch } - pr, err := issues_model.GetUnmergedPullRequest(repo.ID, repo.ID, headBranch, baseBranchName, issues_model.PullRequestFlowAGit) + pr, err := issues_model.GetUnmergedPullRequest(ctx, repo.ID, repo.ID, headBranch, baseBranchName, issues_model.PullRequestFlowAGit) if err != nil { if !issues_model.IsErrPullRequestNotExist(err) { return nil, fmt.Errorf("Failed to get unmerged agit flow pull request in repository: %s/%s Error: %w", ownerName, repoName, err) @@ -116,7 +115,7 @@ func ProcReceive(ctx context.Context, repo *repo_model.Repository, gitRepo *git. description = opts.GitPushOptions["description"] } - pusher, err := user_model.GetUserByID(opts.UserID) + pusher, err := user_model.GetUserByID(ctx, opts.UserID) if err != nil { return nil, fmt.Errorf("Failed to get user. Error: %w", err) } @@ -159,7 +158,7 @@ func ProcReceive(ctx context.Context, repo *repo_model.Repository, gitRepo *git. } // update exist pull request - if err := pr.LoadBaseRepoCtx(ctx); err != nil { + if err := pr.LoadBaseRepo(ctx); err != nil { return nil, fmt.Errorf("Unable to load base repository for PR[%d] Error: %w", pr.ID, err) } @@ -199,19 +198,19 @@ func ProcReceive(ctx context.Context, repo *repo_model.Repository, gitRepo *git. } pull_service.AddToTaskQueue(pr) - pusher, err := user_model.GetUserByID(opts.UserID) + pusher, err := user_model.GetUserByID(ctx, opts.UserID) if err != nil { return nil, fmt.Errorf("Failed to get user. Error: %w", err) } - err = pr.LoadIssue() + err = pr.LoadIssue(ctx) if err != nil { return nil, fmt.Errorf("Failed to load pull issue. Error: %w", err) } - comment, err := issues_model.CreatePushPullComment(ctx, pusher, pr, oldCommitID, opts.NewCommitIDs[i]) + comment, err := pull_service.CreatePushPullComment(ctx, pusher, pr, oldCommitID, opts.NewCommitIDs[i]) if err == nil && comment != nil { - notification.NotifyPullRequestPushCommits(pusher, pr, comment) + notification.NotifyPullRequestPushCommits(ctx, pusher, pr, comment) } - notification.NotifyPullRequestSynchronized(pusher, pr) + notification.NotifyPullRequestSynchronized(ctx, pusher, pr) isForcePush := comment != nil && comment.IsForcePush results = append(results, private.HookProcReceiveRefResult{ diff --git a/services/asymkey/deploy_key.go b/services/asymkey/deploy_key.go index aa0925ab13..f5ca54b723 100644 --- a/services/asymkey/deploy_key.go +++ b/services/asymkey/deploy_key.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey @@ -13,7 +12,7 @@ import ( // DeleteDeployKey deletes deploy key from its repository authorized_keys file if needed. func DeleteDeployKey(doer *user_model.User, id int64) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/services/asymkey/main_test.go b/services/asymkey/main_test.go index cb3d059456..3fa88340fd 100644 --- a/services/asymkey/main_test.go +++ b/services/asymkey/main_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package asymkey diff --git a/services/asymkey/sign.go b/services/asymkey/sign.go index edfd0f6cad..227e0bbf33 100644 --- a/services/asymkey/sign.go +++ b/services/asymkey/sign.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey @@ -272,7 +271,7 @@ Loop: // SignMerge determines if we should sign a PR merge commit to the base repository func SignMerge(ctx context.Context, pr *issues_model.PullRequest, u *user_model.User, tmpBasePath, baseCommit, headCommit string) (bool, string, *git.Signature, error) { - if err := pr.LoadBaseRepoCtx(ctx); err != nil { + if err := pr.LoadBaseRepo(ctx); err != nil { log.Error("Unable to get Base Repo for pull request") return false, "", nil, err } diff --git a/services/asymkey/ssh_key.go b/services/asymkey/ssh_key.go index 143c807a10..0809458107 100644 --- a/services/asymkey/ssh_key.go +++ b/services/asymkey/ssh_key.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey @@ -26,7 +25,7 @@ func DeletePublicKey(doer *user_model.User, id int64) (err error) { } } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/services/asymkey/ssh_key_test.go b/services/asymkey/ssh_key_test.go index 9bc23a719c..32c31a4332 100644 --- a/services/asymkey/ssh_key_test.go +++ b/services/asymkey/ssh_key_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package asymkey diff --git a/services/attachment/attachment.go b/services/attachment/attachment.go index 557cc808a3..7fdacc6aae 100644 --- a/services/attachment/attachment.go +++ b/services/attachment/attachment.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package attachment @@ -25,7 +24,7 @@ func NewAttachment(attach *repo_model.Attachment, file io.Reader) (*repo_model.A return nil, fmt.Errorf("attachment %s should belong to a repository", attach.Name) } - err := db.WithTx(func(ctx context.Context) error { + err := db.WithTx(db.DefaultContext, func(ctx context.Context) error { attach.UUID = uuid.New().String() size, err := storage.Attachments.Save(attach.RelativePath(), file, -1) if err != nil { @@ -40,19 +39,14 @@ func NewAttachment(attach *repo_model.Attachment, file io.Reader) (*repo_model.A } // UploadAttachment upload new attachment into storage and update database -func UploadAttachment(file io.Reader, actorID, repoID, releaseID int64, fileName, allowedTypes string) (*repo_model.Attachment, error) { +func UploadAttachment(file io.Reader, allowedTypes string, opts *repo_model.Attachment) (*repo_model.Attachment, error) { buf := make([]byte, 1024) n, _ := util.ReadAtMost(file, buf) buf = buf[:n] - if err := upload.Verify(buf, fileName, allowedTypes); err != nil { + if err := upload.Verify(buf, opts.Name, allowedTypes); err != nil { return nil, err } - return NewAttachment(&repo_model.Attachment{ - RepoID: repoID, - UploaderID: actorID, - ReleaseID: releaseID, - Name: fileName, - }, io.MultiReader(bytes.NewReader(buf), file)) + return NewAttachment(opts, io.MultiReader(bytes.NewReader(buf), file)) } diff --git a/services/attachment/attachment_test.go b/services/attachment/attachment_test.go index 561792db2f..72d1b2ab3a 100644 --- a/services/attachment/attachment_test.go +++ b/services/attachment/attachment_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package attachment diff --git a/services/auth/auth.go b/services/auth/auth.go index 3a5bb9d27e..00e277c41a 100644 --- a/services/auth/auth.go +++ b/services/auth/auth.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth diff --git a/services/auth/auth_test.go b/services/auth/auth_test.go index 8a9dee6cef..f4e3cdf0d3 100644 --- a/services/auth/auth_test.go +++ b/services/auth/auth_test.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth diff --git a/services/auth/basic.go b/services/auth/basic.go index 9b32ad29af..839aaa7a4e 100644 --- a/services/auth/basic.go +++ b/services/auth/basic.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth @@ -75,7 +74,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore if uid != 0 { log.Trace("Basic Authorization: Valid OAuthAccessToken for user[%d]", uid) - u, err := user_model.GetUserByID(uid) + u, err := user_model.GetUserByID(req.Context(), uid) if err != nil { log.Error("GetUserByID: %v", err) return nil @@ -88,7 +87,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore token, err := auth_model.GetAccessTokenBySHA(authToken) if err == nil { log.Trace("Basic Authorization: Valid AccessToken for user[%d]", uid) - u, err := user_model.GetUserByID(token.UID) + u, err := user_model.GetUserByID(req.Context(), token.UID) if err != nil { log.Error("GetUserByID: %v", err) return nil diff --git a/services/auth/group.go b/services/auth/group.go index bbafe64b49..a9112029c5 100644 --- a/services/auth/group.go +++ b/services/auth/group.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package auth diff --git a/services/auth/httpsign.go b/services/auth/httpsign.go index 67053d2b77..e73db4f248 100644 --- a/services/auth/httpsign.go +++ b/services/auth/httpsign.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package auth @@ -73,7 +72,7 @@ func (h *HTTPSign) Verify(req *http.Request, w http.ResponseWriter, store DataSt } } - u, err := user_model.GetUserByID(publicKey.OwnerID) + u, err := user_model.GetUserByID(req.Context(), publicKey.OwnerID) if err != nil { log.Error("GetUserByID: %v", err) return nil diff --git a/services/auth/interface.go b/services/auth/interface.go index ecc9ad2ca6..d238a40856 100644 --- a/services/auth/interface.go +++ b/services/auth/interface.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth diff --git a/services/auth/oauth2.go b/services/auth/oauth2.go index 8f038d6104..7aea3eadf3 100644 --- a/services/auth/oauth2.go +++ b/services/auth/oauth2.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth @@ -124,7 +123,7 @@ func (o *OAuth2) Verify(req *http.Request, w http.ResponseWriter, store DataStor } log.Trace("OAuth2 Authorization: Found token for user[%d]", id) - user, err := user_model.GetUserByID(id) + user, err := user_model.GetUserByID(req.Context(), id) if err != nil { if !user_model.IsErrUserNotExist(err) { log.Error("GetUserByName: %v", err) diff --git a/services/auth/reverseproxy.go b/services/auth/reverseproxy.go index 8dec1c8ea7..2d5b6611b5 100644 --- a/services/auth/reverseproxy.go +++ b/services/auth/reverseproxy.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth diff --git a/services/auth/session.go b/services/auth/session.go index 1ec94aa0af..ef2c35d58a 100644 --- a/services/auth/session.go +++ b/services/auth/session.go @@ -1,12 +1,12 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth import ( "net/http" + "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/log" ) @@ -56,7 +56,7 @@ func SessionUser(sess SessionStore) *user_model.User { } // Get user object - user, err := user_model.GetUserByID(id) + user, err := user_model.GetUserByID(db.DefaultContext, id) if err != nil { if !user_model.IsErrUserNotExist(err) { log.Error("GetUserById: %v", err) diff --git a/services/auth/signin.go b/services/auth/signin.go index 3ccf68c3a7..2af15c4133 100644 --- a/services/auth/signin.go +++ b/services/auth/signin.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package auth diff --git a/services/auth/source.go b/services/auth/source.go index b7108292d5..aae3a78102 100644 --- a/services/auth/source.go +++ b/services/auth/source.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package auth diff --git a/services/auth/source/db/assert_interface_test.go b/services/auth/source/db/assert_interface_test.go index f39aaeb1e4..62387c78f0 100644 --- a/services/auth/source/db/assert_interface_test.go +++ b/services/auth/source/db/assert_interface_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package db_test diff --git a/services/auth/source/db/authenticate.go b/services/auth/source/db/authenticate.go index f062f66ae0..ec89984499 100644 --- a/services/auth/source/db/authenticate.go +++ b/services/auth/source/db/authenticate.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package db diff --git a/services/auth/source/db/source.go b/services/auth/source/db/source.go index ecab6d5f35..3f4113c790 100644 --- a/services/auth/source/db/source.go +++ b/services/auth/source/db/source.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package db diff --git a/services/auth/source/ldap/assert_interface_test.go b/services/auth/source/ldap/assert_interface_test.go index 8fc6903cf3..33347687dc 100644 --- a/services/auth/source/ldap/assert_interface_test.go +++ b/services/auth/source/ldap/assert_interface_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package ldap_test diff --git a/services/auth/source/ldap/security_protocol.go b/services/auth/source/ldap/security_protocol.go index bb0c7770a1..af83ce191d 100644 --- a/services/auth/source/ldap/security_protocol.go +++ b/services/auth/source/ldap/security_protocol.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package ldap diff --git a/services/auth/source/ldap/source.go b/services/auth/source/ldap/source.go index ad97e2dd49..dc4cb2c940 100644 --- a/services/auth/source/ldap/source.go +++ b/services/auth/source/ldap/source.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package ldap diff --git a/services/auth/source/ldap/source_authenticate.go b/services/auth/source/ldap/source_authenticate.go index 785cb8ed31..321cf5540d 100644 --- a/services/auth/source/ldap/source_authenticate.go +++ b/services/auth/source/ldap/source_authenticate.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package ldap diff --git a/services/auth/source/ldap/source_group_sync.go b/services/auth/source/ldap/source_group_sync.go index e797e015b2..95a6084922 100644 --- a/services/auth/source/ldap/source_group_sync.go +++ b/services/auth/source/ldap/source_group_sync.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package ldap diff --git a/services/auth/source/ldap/source_search.go b/services/auth/source/ldap/source_search.go index 6ea84ec288..6b6b56db2f 100644 --- a/services/auth/source/ldap/source_search.go +++ b/services/auth/source/ldap/source_search.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2020 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. +// SPDX-License-Identifier: MIT package ldap diff --git a/services/auth/source/ldap/source_sync.go b/services/auth/source/ldap/source_sync.go index eb5ee8463f..73e8309aca 100644 --- a/services/auth/source/ldap/source_sync.go +++ b/services/auth/source/ldap/source_sync.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package ldap diff --git a/services/auth/source/ldap/util.go b/services/auth/source/ldap/util.go index f27de37c87..bd11e2d119 100644 --- a/services/auth/source/ldap/util.go +++ b/services/auth/source/ldap/util.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package ldap diff --git a/services/auth/source/oauth2/assert_interface_test.go b/services/auth/source/oauth2/assert_interface_test.go index 0ec7361ca8..56fe0e4aa8 100644 --- a/services/auth/source/oauth2/assert_interface_test.go +++ b/services/auth/source/oauth2/assert_interface_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2_test diff --git a/services/auth/source/oauth2/init.go b/services/auth/source/oauth2/init.go index e4eedd34cb..32fe545c90 100644 --- a/services/auth/source/oauth2/init.go +++ b/services/auth/source/oauth2/init.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/oauth2/jwtsigningkey.go b/services/auth/source/oauth2/jwtsigningkey.go index 352f932746..93c1574379 100644 --- a/services/auth/source/oauth2/jwtsigningkey.go +++ b/services/auth/source/oauth2/jwtsigningkey.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/oauth2/providers.go b/services/auth/source/oauth2/providers.go index aa3ee3842d..7ba370855a 100644 --- a/services/auth/source/oauth2/providers.go +++ b/services/auth/source/oauth2/providers.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/oauth2/providers_base.go b/services/auth/source/oauth2/providers_base.go index b6b6d0bbd2..61654d8eaa 100644 --- a/services/auth/source/oauth2/providers_base.go +++ b/services/auth/source/oauth2/providers_base.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/oauth2/providers_custom.go b/services/auth/source/oauth2/providers_custom.go index c3ebdf9df0..b5fe179441 100644 --- a/services/auth/source/oauth2/providers_custom.go +++ b/services/auth/source/oauth2/providers_custom.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/oauth2/providers_openid.go b/services/auth/source/oauth2/providers_openid.go index 80ee56d4a4..2433cd3c7f 100644 --- a/services/auth/source/oauth2/providers_openid.go +++ b/services/auth/source/oauth2/providers_openid.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/oauth2/providers_simple.go b/services/auth/source/oauth2/providers_simple.go index 39d3d74f6d..731c1b59a9 100644 --- a/services/auth/source/oauth2/providers_simple.go +++ b/services/auth/source/oauth2/providers_simple.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/oauth2/source.go b/services/auth/source/oauth2/source.go index 457686ba1f..0abebc04ec 100644 --- a/services/auth/source/oauth2/source.go +++ b/services/auth/source/oauth2/source.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/oauth2/source_authenticate.go b/services/auth/source/oauth2/source_authenticate.go index fdc18411a7..e3e2a9e192 100644 --- a/services/auth/source/oauth2/source_authenticate.go +++ b/services/auth/source/oauth2/source_authenticate.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/oauth2/source_callout.go b/services/auth/source/oauth2/source_callout.go index 7447e5d453..8d70bee248 100644 --- a/services/auth/source/oauth2/source_callout.go +++ b/services/auth/source/oauth2/source_callout.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/oauth2/source_name.go b/services/auth/source/oauth2/source_name.go index 0b794ad650..eee789eff7 100644 --- a/services/auth/source/oauth2/source_name.go +++ b/services/auth/source/oauth2/source_name.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/oauth2/source_register.go b/services/auth/source/oauth2/source_register.go index f61de7e1d6..3527d54b65 100644 --- a/services/auth/source/oauth2/source_register.go +++ b/services/auth/source/oauth2/source_register.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/oauth2/store.go b/services/auth/source/oauth2/store.go index f00264f997..394bf99463 100644 --- a/services/auth/source/oauth2/store.go +++ b/services/auth/source/oauth2/store.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/oauth2/token.go b/services/auth/source/oauth2/token.go index 0c69913ff4..c5a064054e 100644 --- a/services/auth/source/oauth2/token.go +++ b/services/auth/source/oauth2/token.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/oauth2/urlmapping.go b/services/auth/source/oauth2/urlmapping.go index 43c8dde9a5..d0442d58a8 100644 --- a/services/auth/source/oauth2/urlmapping.go +++ b/services/auth/source/oauth2/urlmapping.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package oauth2 diff --git a/services/auth/source/pam/assert_interface_test.go b/services/auth/source/pam/assert_interface_test.go index d8754cdf77..8e7648b8d3 100644 --- a/services/auth/source/pam/assert_interface_test.go +++ b/services/auth/source/pam/assert_interface_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package pam_test diff --git a/services/auth/source/pam/source.go b/services/auth/source/pam/source.go index 957c89dc85..96b182e185 100644 --- a/services/auth/source/pam/source.go +++ b/services/auth/source/pam/source.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package pam diff --git a/services/auth/source/pam/source_authenticate.go b/services/auth/source/pam/source_authenticate.go index 16ddc0598e..48cd905a0a 100644 --- a/services/auth/source/pam/source_authenticate.go +++ b/services/auth/source/pam/source_authenticate.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package pam diff --git a/services/auth/source/smtp/assert_interface_test.go b/services/auth/source/smtp/assert_interface_test.go index c7fae6431f..6c9cde66e1 100644 --- a/services/auth/source/smtp/assert_interface_test.go +++ b/services/auth/source/smtp/assert_interface_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package smtp_test diff --git a/services/auth/source/smtp/auth.go b/services/auth/source/smtp/auth.go index 487c049722..6446fcd706 100644 --- a/services/auth/source/smtp/auth.go +++ b/services/auth/source/smtp/auth.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package smtp @@ -58,10 +57,10 @@ var ErrUnsupportedLoginType = errors.New("Login source is unknown") func Authenticate(a smtp.Auth, source *Source) error { tlsConfig := &tls.Config{ InsecureSkipVerify: source.SkipVerify, - ServerName: source.Addr, + ServerName: source.Host, } - conn, err := net.Dial("tcp", net.JoinHostPort(source.Addr, strconv.Itoa(source.Port))) + conn, err := net.Dial("tcp", net.JoinHostPort(source.Host, strconv.Itoa(source.Port))) if err != nil { return err } @@ -71,7 +70,7 @@ func Authenticate(a smtp.Auth, source *Source) error { conn = tls.Client(conn, tlsConfig) } - client, err := smtp.NewClient(conn, source.Addr) + client, err := smtp.NewClient(conn, source.Host) if err != nil { return fmt.Errorf("failed to create NewClient: %w", err) } diff --git a/services/auth/source/smtp/source.go b/services/auth/source/smtp/source.go index b2286d42a0..2a648e421e 100644 --- a/services/auth/source/smtp/source.go +++ b/services/auth/source/smtp/source.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package smtp @@ -19,7 +18,7 @@ import ( // Source holds configuration for the SMTP login source. type Source struct { Auth string - Addr string + Host string Port int AllowedDomains string `xorm:"TEXT"` ForceSMTPS bool diff --git a/services/auth/source/smtp/source_authenticate.go b/services/auth/source/smtp/source_authenticate.go index 63fd3e5511..00aaa8e084 100644 --- a/services/auth/source/smtp/source_authenticate.go +++ b/services/auth/source/smtp/source_authenticate.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package smtp @@ -32,7 +31,7 @@ func (source *Source) Authenticate(user *user_model.User, userName, password str var auth smtp.Auth switch source.Auth { case PlainAuthentication: - auth = smtp.PlainAuth("", userName, password, source.Addr) + auth = smtp.PlainAuth("", userName, password, source.Host) case LoginAuthentication: auth = &loginAuthenticator{userName, password} case CRAMMD5Authentication: diff --git a/services/auth/source/sspi/assert_interface_test.go b/services/auth/source/sspi/assert_interface_test.go index 3344245186..03d836dd6f 100644 --- a/services/auth/source/sspi/assert_interface_test.go +++ b/services/auth/source/sspi/assert_interface_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package sspi_test diff --git a/services/auth/source/sspi/source.go b/services/auth/source/sspi/source.go index e6e63ee1eb..bdd6ef451c 100644 --- a/services/auth/source/sspi/source.go +++ b/services/auth/source/sspi/source.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package sspi diff --git a/services/auth/sspi_windows.go b/services/auth/sspi_windows.go index 757d596c4c..988afb4730 100644 --- a/services/auth/sspi_windows.go +++ b/services/auth/sspi_windows.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package auth diff --git a/services/auth/sync.go b/services/auth/sync.go index b7f3232a30..e42e8a51a7 100644 --- a/services/auth/sync.go +++ b/services/auth/sync.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package auth diff --git a/services/automerge/automerge.go b/services/automerge/automerge.go index 3ee8af2344..15d94e7920 100644 --- a/services/automerge/automerge.go +++ b/services/automerge/automerge.go @@ -1,6 +1,5 @@ // Copyright 2021 Gitea. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package automerge @@ -63,7 +62,7 @@ func addToQueue(pr *issues_model.PullRequest, sha string) { // ScheduleAutoMerge if schedule is false and no error, pull can be merged directly func ScheduleAutoMerge(ctx context.Context, doer *user_model.User, pull *issues_model.PullRequest, style repo_model.MergeStyle, message string) (scheduled bool, err error) { - err = db.WithTx(func(ctx context.Context) error { + err = db.WithTx(ctx, func(ctx context.Context) error { lastCommitStatus, err := pull_service.GetPullRequestCommitStatusState(ctx, pull) if err != nil { return err @@ -81,20 +80,20 @@ func ScheduleAutoMerge(ctx context.Context, doer *user_model.User, pull *issues_ _, err = issues_model.CreateAutoMergeComment(ctx, issues_model.CommentTypePRScheduledToAutoMerge, pull, doer) return err - }, ctx) + }) return scheduled, err } // RemoveScheduledAutoMerge cancels a previously scheduled pull request func RemoveScheduledAutoMerge(ctx context.Context, doer *user_model.User, pull *issues_model.PullRequest) error { - return db.WithTx(func(ctx context.Context) error { + return db.WithTx(ctx, func(ctx context.Context) error { if err := pull_model.DeleteScheduledAutoMerge(ctx, pull.ID); err != nil { return err } _, err := issues_model.CreateAutoMergeComment(ctx, issues_model.CommentTypePRUnScheduledToAutoMerge, pull, doer) return err - }, ctx) + }) } // MergeScheduledPullRequest merges a previously scheduled pull request when all checks succeeded @@ -188,8 +187,8 @@ func handlePull(pullID int64, sha string) { // We get the latest sha commit hash again to handle the case where the check of a previous push // did not succeed or was not finished yet. - if err = pr.LoadHeadRepoCtx(ctx); err != nil { - log.Error("pull[%d] LoadHeadRepoCtx: %v", pr.ID, err) + if err = pr.LoadHeadRepo(ctx); err != nil { + log.Error("pull[%d] LoadHeadRepo: %v", pr.ID, err) return } @@ -219,7 +218,7 @@ func handlePull(pullID int64, sha string) { } // Merge if all checks succeeded - doer, err := user_model.GetUserByIDCtx(ctx, scheduledPRM.DoerID) + doer, err := user_model.GetUserByID(ctx, scheduledPRM.DoerID) if err != nil { log.Error("GetUserByIDCtx: %v", err) return @@ -244,8 +243,8 @@ func handlePull(pullID int64, sha string) { if pr.BaseRepoID == pr.HeadRepoID { baseGitRepo = headGitRepo } else { - if err = pr.LoadBaseRepoCtx(ctx); err != nil { - log.Error("LoadBaseRepoCtx: %v", err) + if err = pr.LoadBaseRepo(ctx); err != nil { + log.Error("LoadBaseRepo: %v", err) return } diff --git a/services/comments/comments.go b/services/comments/comments.go deleted file mode 100644 index d2406ba07a..0000000000 --- a/services/comments/comments.go +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2019 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 comments - -import ( - "strings" - - "code.gitea.io/gitea/models/db" - issues_model "code.gitea.io/gitea/models/issues" - repo_model "code.gitea.io/gitea/models/repo" - user_model "code.gitea.io/gitea/models/user" - "code.gitea.io/gitea/modules/notification" - "code.gitea.io/gitea/modules/timeutil" - "code.gitea.io/gitea/services/activitypub" -) - -// CreateIssueComment creates a plain issue comment. -func CreateIssueComment(doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, content string, attachments []string) (*issues_model.Comment, error) { - comment, err := issues_model.CreateComment(&issues_model.CreateCommentOptions{ - Type: issues_model.CommentTypeComment, - Doer: doer, - Repo: repo, - Issue: issue, - Content: content, - Attachments: attachments, - }) - if err != nil { - return nil, err - } - - if strings.Contains(repo.OwnerName, "@") { - // Federated comment - note, err := activitypub.Note(comment) - if err != nil { - return nil, err - } - create := activitypub.Create(repo.OriginalURL+"/inbox", note) - err = activitypub.Send(doer, create) - if err != nil { - return nil, err - } - } - - mentions, err := issues_model.FindAndUpdateIssueMentions(db.DefaultContext, issue, doer, comment.Content) - if err != nil { - return nil, err - } - - notification.NotifyCreateIssueComment(doer, repo, issue, comment, mentions) - - return comment, nil -} - -// UpdateComment updates information of comment. -func UpdateComment(c *issues_model.Comment, doer *user_model.User, oldContent string) error { - needsContentHistory := c.Content != oldContent && - (c.Type == issues_model.CommentTypeComment || c.Type == issues_model.CommentTypeReview || c.Type == issues_model.CommentTypeCode) - if needsContentHistory { - hasContentHistory, err := issues_model.HasIssueContentHistory(db.DefaultContext, c.IssueID, c.ID) - if err != nil { - return err - } - if !hasContentHistory { - if err = issues_model.SaveIssueContentHistory(db.DefaultContext, c.PosterID, c.IssueID, c.ID, - c.CreatedUnix, oldContent, true); err != nil { - return err - } - } - } - - if err := issues_model.UpdateComment(c, doer); err != nil { - return err - } - - if needsContentHistory { - err := issues_model.SaveIssueContentHistory(db.DefaultContext, doer.ID, c.IssueID, c.ID, timeutil.TimeStampNow(), c.Content, false) - if err != nil { - return err - } - } - - notification.NotifyUpdateComment(doer, c, oldContent) - - return nil -} - -// DeleteComment deletes the comment -func DeleteComment(doer *user_model.User, comment *issues_model.Comment) error { - ctx, committer, err := db.TxContext() - if err != nil { - return err - } - defer committer.Close() - - if err := issues_model.DeleteComment(ctx, comment); err != nil { - return err - } - if err := committer.Commit(); err != nil { - return err - } - - notification.NotifyDeleteComment(doer, comment) - - return nil -} diff --git a/services/context/user.go b/services/context/user.go index 1c92d24d4a..9dc84c3ac1 100644 --- a/services/context/user.go +++ b/services/context/user.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package context diff --git a/services/cron/cron.go b/services/cron/cron.go index 8e19e04416..bda8f12f12 100644 --- a/services/cron/cron.go +++ b/services/cron/cron.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package cron diff --git a/services/cron/setting.go b/services/cron/setting.go index eb13242e94..952a4d17ab 100644 --- a/services/cron/setting.go +++ b/services/cron/setting.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package cron diff --git a/services/cron/tasks.go b/services/cron/tasks.go index 6ff5964d1e..1c5493c898 100644 --- a/services/cron/tasks.go +++ b/services/cron/tasks.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package cron diff --git a/services/cron/tasks_basic.go b/services/cron/tasks_basic.go index ca35f5be57..05aef6623d 100644 --- a/services/cron/tasks_basic.go +++ b/services/cron/tasks_basic.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package cron @@ -64,7 +63,7 @@ func registerRepoHealthCheck() { for _, arg := range rhcConfig.Args { args = append(args, git.CmdArg(arg)) } - return repo_service.GitFsck(ctx, rhcConfig.Timeout, args) + return repo_service.GitFsckRepos(ctx, rhcConfig.Timeout, args) }) } diff --git a/services/cron/tasks_extended.go b/services/cron/tasks_extended.go index c730477cbd..4486be0c2f 100644 --- a/services/cron/tasks_extended.go +++ b/services/cron/tasks_extended.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package cron diff --git a/services/externalaccount/link.go b/services/externalaccount/link.go index 95ada22542..dcdc57ee48 100644 --- a/services/externalaccount/link.go +++ b/services/externalaccount/link.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package externalaccount diff --git a/services/externalaccount/user.go b/services/externalaccount/user.go index e5cd443770..87d2e02b48 100644 --- a/services/externalaccount/user.go +++ b/services/externalaccount/user.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package externalaccount diff --git a/services/forms/admin.go b/services/forms/admin.go index 537b9f982c..a749f863f3 100644 --- a/services/forms/admin.go +++ b/services/forms/admin.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package forms diff --git a/services/forms/auth_form.go b/services/forms/auth_form.go index 9064be2cca..0cede07f95 100644 --- a/services/forms/auth_form.go +++ b/services/forms/auth_form.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package forms @@ -45,7 +44,7 @@ type AuthenticationForm struct { IsActive bool IsSyncEnabled bool SMTPAuth string - SMTPAddr string + SMTPHost string SMTPPort int AllowedDomains string SecurityProtocol int `binding:"Range(0,2)"` diff --git a/services/forms/org.go b/services/forms/org.go index c7ee911345..d753531371 100644 --- a/services/forms/org.go +++ b/services/forms/org.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package forms diff --git a/services/forms/package_form.go b/services/forms/package_form.go new file mode 100644 index 0000000000..734bb05dc6 --- /dev/null +++ b/services/forms/package_form.go @@ -0,0 +1,30 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package forms + +import ( + "net/http" + + "code.gitea.io/gitea/modules/context" + "code.gitea.io/gitea/modules/web/middleware" + + "gitea.com/go-chi/binding" +) + +type PackageCleanupRuleForm struct { + ID int64 + Enabled bool + Type string `binding:"Required;In(composer,conan,container,generic,helm,maven,npm,nuget,pub,pypi,rubygems,vagrant)"` + KeepCount int `binding:"In(0,1,5,10,25,50,100)"` + KeepPattern string `binding:"RegexPattern"` + RemoveDays int `binding:"In(0,7,14,30,60,90,180)"` + RemovePattern string `binding:"RegexPattern"` + MatchFullName bool + Action string `binding:"Required;In(save,remove)"` +} + +func (f *PackageCleanupRuleForm) Validate(req *http.Request, errs binding.Errors) binding.Errors { + ctx := context.GetContext(req) + return middleware.Validate(errs, ctx.Data, f, ctx.Locale) +} diff --git a/services/forms/repo_branch_form.go b/services/forms/repo_branch_form.go index 011926092f..bf1183fc43 100644 --- a/services/forms/repo_branch_form.go +++ b/services/forms/repo_branch_form.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package forms diff --git a/services/forms/repo_form.go b/services/forms/repo_form.go index 64f47aadd5..89a013d9af 100644 --- a/services/forms/repo_form.go +++ b/services/forms/repo_form.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2017 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. +// SPDX-License-Identifier: MIT package forms @@ -135,6 +134,7 @@ type RepoSettingForm struct { EnablePrune bool // Advanced settings + EnableCode bool EnableWiki bool EnableExternalWiki bool ExternalWikiURL string diff --git a/services/forms/repo_form_test.go b/services/forms/repo_form_test.go index 198437f7ea..2c5a8e2c0f 100644 --- a/services/forms/repo_form_test.go +++ b/services/forms/repo_form_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package forms diff --git a/services/forms/repo_tag_form.go b/services/forms/repo_tag_form.go index 337e7fe1ea..1209d2346f 100644 --- a/services/forms/repo_tag_form.go +++ b/services/forms/repo_tag_form.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package forms diff --git a/services/forms/user_form.go b/services/forms/user_form.go index ed8ccf12ea..cd2c45261b 100644 --- a/services/forms/user_form.go +++ b/services/forms/user_form.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2018 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. +// SPDX-License-Identifier: MIT package forms @@ -91,13 +90,10 @@ func (f *InstallForm) Validate(req *http.Request, errs binding.Errors) binding.E // RegisterForm form for registering type RegisterForm struct { - UserName string `binding:"Required;Username;MaxSize(40)"` - Email string `binding:"Required;MaxSize(254)"` - Password string `binding:"MaxSize(255)"` - Retype string - GRecaptchaResponse string `form:"g-recaptcha-response"` - HcaptchaResponse string `form:"h-captcha-response"` - McaptchaResponse string `form:"m-captcha-response"` + UserName string `binding:"Required;Username;MaxSize(40)"` + Email string `binding:"Required;MaxSize(254)"` + Password string `binding:"MaxSize(255)"` + Retype string } // Validate validates the fields diff --git a/services/forms/user_form_auth_openid.go b/services/forms/user_form_auth_openid.go index d1ed0a23c7..f95eb98405 100644 --- a/services/forms/user_form_auth_openid.go +++ b/services/forms/user_form_auth_openid.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package forms @@ -27,11 +26,8 @@ func (f *SignInOpenIDForm) Validate(req *http.Request, errs binding.Errors) bind // SignUpOpenIDForm form for signin up with OpenID type SignUpOpenIDForm struct { - UserName string `binding:"Required;Username;MaxSize(40)"` - Email string `binding:"Required;Email;MaxSize(254)"` - GRecaptchaResponse string `form:"g-recaptcha-response"` - HcaptchaResponse string `form:"h-captcha-response"` - McaptchaResponse string `form:"m-captcha-response"` + UserName string `binding:"Required;Username;MaxSize(40)"` + Email string `binding:"Required;Email;MaxSize(254)"` } // Validate validates the fields diff --git a/services/forms/user_form_hidden_comments.go b/services/forms/user_form_hidden_comments.go index 35c1a6dd2a..7eb800a020 100644 --- a/services/forms/user_form_hidden_comments.go +++ b/services/forms/user_form_hidden_comments.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package forms diff --git a/services/forms/user_form_test.go b/services/forms/user_form_test.go index 9f67143d12..463b39d0bf 100644 --- a/services/forms/user_form_test.go +++ b/services/forms/user_form_test.go @@ -1,6 +1,5 @@ // Copyright 2018 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package forms diff --git a/services/gitdiff/csv.go b/services/gitdiff/csv.go index 642c9937dd..5781d7e909 100644 --- a/services/gitdiff/csv.go +++ b/services/gitdiff/csv.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package gitdiff diff --git a/services/gitdiff/csv_test.go b/services/gitdiff/csv_test.go index 2c15b42d91..ac53e2d1ef 100644 --- a/services/gitdiff/csv_test.go +++ b/services/gitdiff/csv_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package gitdiff diff --git a/services/gitdiff/gitdiff.go b/services/gitdiff/gitdiff.go index 3c8c5c81a5..d3ee93ec94 100644 --- a/services/gitdiff/gitdiff.go +++ b/services/gitdiff/gitdiff.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package gitdiff @@ -280,7 +279,8 @@ func DiffInlineWithUnicodeEscape(s template.HTML, locale translation.Locale) Dif // DiffInlineWithHighlightCode makes a DiffInline with code highlight and hidden unicode characters escaped func DiffInlineWithHighlightCode(fileName, language, code string, locale translation.Locale) DiffInline { - status, content := charset.EscapeControlHTML(highlight.Code(fileName, language, code), locale) + highlighted, _ := highlight.Code(fileName, language, code) + status, content := charset.EscapeControlHTML(highlighted, locale) return DiffInline{EscapeStatus: status, Content: template.HTML(content)} } diff --git a/services/gitdiff/gitdiff_test.go b/services/gitdiff/gitdiff_test.go index a7fd677fef..267f0e4cff 100644 --- a/services/gitdiff/gitdiff_test.go +++ b/services/gitdiff/gitdiff_test.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package gitdiff diff --git a/services/gitdiff/highlightdiff.go b/services/gitdiff/highlightdiff.go index 4ceada4d7e..f1e2b1d3cb 100644 --- a/services/gitdiff/highlightdiff.go +++ b/services/gitdiff/highlightdiff.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package gitdiff @@ -91,8 +90,8 @@ func (hcd *highlightCodeDiff) diffWithHighlight(filename, language, codeA, codeB hcd.collectUsedRunes(codeA) hcd.collectUsedRunes(codeB) - highlightCodeA := highlight.Code(filename, language, codeA) - highlightCodeB := highlight.Code(filename, language, codeB) + highlightCodeA, _ := highlight.Code(filename, language, codeA) + highlightCodeB, _ := highlight.Code(filename, language, codeB) highlightCodeA = hcd.convertToPlaceholders(highlightCodeA) highlightCodeB = hcd.convertToPlaceholders(highlightCodeB) diff --git a/services/gitdiff/highlightdiff_test.go b/services/gitdiff/highlightdiff_test.go index 205f9a0773..545a060e20 100644 --- a/services/gitdiff/highlightdiff_test.go +++ b/services/gitdiff/highlightdiff_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package gitdiff diff --git a/services/gitdiff/main_test.go b/services/gitdiff/main_test.go index 0d36a600f6..a5ac274b8f 100644 --- a/services/gitdiff/main_test.go +++ b/services/gitdiff/main_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package gitdiff diff --git a/services/issue/assignee.go b/services/issue/assignee.go index e24f8500c9..e5e1456c3f 100644 --- a/services/issue/assignee.go +++ b/services/issue/assignee.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issue @@ -51,13 +50,13 @@ func ToggleAssignee(issue *issues_model.Issue, doer *user_model.User, assigneeID return } - assignee, err1 := user_model.GetUserByID(assigneeID) + assignee, err1 := user_model.GetUserByID(db.DefaultContext, assigneeID) if err1 != nil { err = err1 return } - notification.NotifyIssueChangeAssignee(doer, issue, assignee, removed, comment) + notification.NotifyIssueChangeAssignee(db.DefaultContext, doer, issue, assignee, removed, comment) return removed, comment, err } @@ -75,7 +74,7 @@ func ReviewRequest(issue *issues_model.Issue, doer, reviewer *user_model.User, i } if comment != nil { - notification.NotifyPullReviewRequest(doer, issue, reviewer, isAdd, comment) + notification.NotifyPullReviewRequest(db.DefaultContext, doer, issue, reviewer, isAdd, comment) } return comment, err @@ -246,7 +245,7 @@ func TeamReviewRequest(issue *issues_model.Issue, doer *user_model.User, reviewe } // notify all user in this team - if err = comment.LoadIssue(); err != nil { + if err = comment.LoadIssue(db.DefaultContext); err != nil { return } @@ -262,7 +261,7 @@ func TeamReviewRequest(issue *issues_model.Issue, doer *user_model.User, reviewe continue } comment.AssigneeID = member.ID - notification.NotifyPullReviewRequest(doer, issue, member, isAdd, comment) + notification.NotifyPullReviewRequest(db.DefaultContext, doer, issue, member, isAdd, comment) } return comment, err diff --git a/services/issue/assignee_test.go b/services/issue/assignee_test.go index 5c8b822499..114ace078e 100644 --- a/services/issue/assignee_test.go +++ b/services/issue/assignee_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issue @@ -23,7 +22,7 @@ func TestDeleteNotPassedAssignee(t *testing.T) { assert.NoError(t, err) assert.EqualValues(t, 1, len(issue.Assignees)) - user1, err := user_model.GetUserByID(1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him + user1, err := user_model.GetUserByID(db.DefaultContext, 1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him assert.NoError(t, err) // Check if he got removed diff --git a/services/issue/comments.go b/services/issue/comments.go new file mode 100644 index 0000000000..506eafcf91 --- /dev/null +++ b/services/issue/comments.go @@ -0,0 +1,151 @@ +// Copyright 2019 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package issue + +import ( + "context" + "fmt" + "strings" + + "code.gitea.io/gitea/models/db" + issues_model "code.gitea.io/gitea/models/issues" + repo_model "code.gitea.io/gitea/models/repo" + user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/notification" + "code.gitea.io/gitea/modules/timeutil" + "code.gitea.io/gitea/services/activitypub" +) + +// CreateComment creates comment of issue or commit. +func CreateComment(opts *issues_model.CreateCommentOptions) (comment *issues_model.Comment, err error) { + ctx, committer, err := db.TxContext(db.DefaultContext) + if err != nil { + return nil, err + } + defer committer.Close() + + comment, err = issues_model.CreateComment(ctx, opts) + if err != nil { + return nil, err + } + + if err = committer.Commit(); err != nil { + return nil, err + } + + return comment, nil +} + +// CreateRefComment creates a commit reference comment to issue. +func CreateRefComment(doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, content, commitSHA string) error { + if len(commitSHA) == 0 { + return fmt.Errorf("cannot create reference with empty commit SHA") + } + + // Check if same reference from same commit has already existed. + has, err := db.GetEngine(db.DefaultContext).Get(&issues_model.Comment{ + Type: issues_model.CommentTypeCommitRef, + IssueID: issue.ID, + CommitSHA: commitSHA, + }) + if err != nil { + return fmt.Errorf("check reference comment: %w", err) + } else if has { + return nil + } + + _, err = CreateComment(&issues_model.CreateCommentOptions{ + Type: issues_model.CommentTypeCommitRef, + Doer: doer, + Repo: repo, + Issue: issue, + CommitSHA: commitSHA, + Content: content, + }) + return err +} + +// CreateIssueComment creates a plain issue comment. +func CreateIssueComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, content string, attachments []string) (*issues_model.Comment, error) { + comment, err := CreateComment(&issues_model.CreateCommentOptions{ + Type: issues_model.CommentTypeComment, + Doer: doer, + Repo: repo, + Issue: issue, + Content: content, + Attachments: attachments, + }) + if err != nil { + return nil, err + } + + if strings.Contains(repo.OwnerName, "@") { + // Federated comment + note, err := activitypub.Note(comment) + if err != nil { + return nil, err + } + create := activitypub.Create(repo.OriginalURL+"/inbox", note) + err = activitypub.Send(doer, create) + if err != nil { + return nil, err + } + } + + mentions, err := issues_model.FindAndUpdateIssueMentions(ctx, issue, doer, comment.Content) + if err != nil { + return nil, err + } + + notification.NotifyCreateIssueComment(ctx, doer, repo, issue, comment, mentions) + + return comment, nil +} + +// UpdateComment updates information of comment. +func UpdateComment(ctx context.Context, c *issues_model.Comment, doer *user_model.User, oldContent string) error { + needsContentHistory := c.Content != oldContent && + (c.Type == issues_model.CommentTypeComment || c.Type == issues_model.CommentTypeReview || c.Type == issues_model.CommentTypeCode) + if needsContentHistory { + hasContentHistory, err := issues_model.HasIssueContentHistory(ctx, c.IssueID, c.ID) + if err != nil { + return err + } + if !hasContentHistory { + if err = issues_model.SaveIssueContentHistory(ctx, c.PosterID, c.IssueID, c.ID, + c.CreatedUnix, oldContent, true); err != nil { + return err + } + } + } + + if err := issues_model.UpdateComment(c, doer); err != nil { + return err + } + + if needsContentHistory { + err := issues_model.SaveIssueContentHistory(ctx, doer.ID, c.IssueID, c.ID, timeutil.TimeStampNow(), c.Content, false) + if err != nil { + return err + } + } + + notification.NotifyUpdateComment(ctx, doer, c, oldContent) + + return nil +} + +// DeleteComment deletes the comment +func DeleteComment(ctx context.Context, doer *user_model.User, comment *issues_model.Comment) error { + err := db.AutoTx(ctx, func(ctx context.Context) error { + return issues_model.DeleteComment(ctx, comment) + }) + if err != nil { + return err + } + + notification.NotifyDeleteComment(ctx, doer, comment) + + return nil +} diff --git a/services/issue/commit.go b/services/issue/commit.go index c8cfa6cc8a..db31fc66bb 100644 --- a/services/issue/commit.go +++ b/services/issue/commit.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package issue @@ -120,7 +119,7 @@ func UpdateIssuesCommit(doer *user_model.User, repo *repo_model.Repository, comm // issue is from another repo if len(ref.Owner) > 0 && len(ref.Name) > 0 { - refRepo, err = repo_model.GetRepositoryByOwnerAndName(ref.Owner, ref.Name) + refRepo, err = repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, ref.Owner, ref.Name) if err != nil { if repo_model.IsErrRepoNotExist(err) { log.Warn("Repository referenced in commit but does not exist: %v", err) @@ -159,7 +158,7 @@ func UpdateIssuesCommit(doer *user_model.User, repo *repo_model.Repository, comm } message := fmt.Sprintf(`%s`, html.EscapeString(repo.Link()), html.EscapeString(url.PathEscape(c.Sha1)), html.EscapeString(strings.SplitN(c.Message, "\n", 2)[0])) - if err = issues_model.CreateRefComment(doer, refRepo, refIssue, message, c.Sha1); err != nil { + if err = CreateRefComment(doer, refRepo, refIssue, message, c.Sha1); err != nil { return err } diff --git a/services/issue/commit_test.go b/services/issue/commit_test.go index 8469bf1ac1..590e7adce9 100644 --- a/services/issue/commit_test.go +++ b/services/issue/commit_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issue diff --git a/services/issue/content.go b/services/issue/content.go index 6f493892f4..819ac3f20f 100644 --- a/services/issue/content.go +++ b/services/issue/content.go @@ -1,10 +1,10 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issue import ( + "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/notification" @@ -18,7 +18,7 @@ func ChangeContent(issue *issues_model.Issue, doer *user_model.User, content str return err } - notification.NotifyIssueChangeContent(doer, issue, oldContent) + notification.NotifyIssueChangeContent(db.DefaultContext, doer, issue, oldContent) return nil } diff --git a/services/issue/issue.go b/services/issue/issue.go index e9b44d4051..61194bf1dd 100644 --- a/services/issue/issue.go +++ b/services/issue/issue.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issue @@ -19,7 +18,6 @@ import ( "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/notification" "code.gitea.io/gitea/modules/storage" - "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/services/activitypub" ) @@ -53,12 +51,12 @@ func NewIssue(repo *repo_model.Repository, issue *issues_model.Issue, labelIDs [ return err } - notification.NotifyNewIssue(issue, mentions) + notification.NotifyNewIssue(db.DefaultContext, issue, mentions) if len(issue.Labels) > 0 { - notification.NotifyIssueChangeLabels(issue.Poster, issue, issue.Labels, nil) + notification.NotifyIssueChangeLabels(db.DefaultContext, issue.Poster, issue, issue.Labels, nil) } if issue.Milestone != nil { - notification.NotifyIssueChangeMilestone(issue.Poster, issue, 0) + notification.NotifyIssueChangeMilestone(db.DefaultContext, issue.Poster, issue, 0) } return nil @@ -73,7 +71,7 @@ func ChangeTitle(issue *issues_model.Issue, doer *user_model.User, title string) return } - notification.NotifyIssueChangeTitle(doer, issue, oldTitle) + notification.NotifyIssueChangeTitle(db.DefaultContext, doer, issue, oldTitle) return nil } @@ -87,7 +85,7 @@ func ChangeIssueRef(issue *issues_model.Issue, doer *user_model.User, ref string return err } - notification.NotifyIssueChangeRef(doer, issue, oldRef) + notification.NotifyIssueChangeRef(db.DefaultContext, doer, issue, oldRef) return nil } @@ -150,10 +148,10 @@ func UpdateAssignees(issue *issues_model.Issue, oneAssignee string, multipleAssi // DeleteIssue deletes an issue func DeleteIssue(doer *user_model.User, gitRepo *git.Repository, issue *issues_model.Issue) error { // load issue before deleting it - if err := issue.LoadAttributes(db.DefaultContext); err != nil { + if err := issue.LoadAttributes(gitRepo.Ctx); err != nil { return err } - if err := issue.LoadPullRequest(); err != nil { + if err := issue.LoadPullRequest(gitRepo.Ctx); err != nil { return err } @@ -169,7 +167,7 @@ func DeleteIssue(doer *user_model.User, gitRepo *git.Repository, issue *issues_m } } - notification.NotifyDeleteIssue(doer, issue) + notification.NotifyDeleteIssue(gitRepo.Ctx, doer, issue) return nil } @@ -177,7 +175,7 @@ func DeleteIssue(doer *user_model.User, gitRepo *git.Repository, issue *issues_m // AddAssigneeIfNotAssigned adds an assignee only if he isn't already assigned to the issue. // Also checks for access of assigned user func AddAssigneeIfNotAssigned(issue *issues_model.Issue, doer *user_model.User, assigneeID int64) (err error) { - assignee, err := user_model.GetUserByID(assigneeID) + assignee, err := user_model.GetUserByID(db.DefaultContext, assigneeID) if err != nil { return err } @@ -216,7 +214,7 @@ func GetRefEndNamesAndURLs(issues []*issues_model.Issue, repoLink string) (map[i for _, issue := range issues { if issue.Ref != "" { issueRefEndNames[issue.ID] = git.RefEndName(issue.Ref) - issueRefURLs[issue.ID] = git.RefURL(repoLink, util.PathEscapeSegments(issue.Ref)) + issueRefURLs[issue.ID] = git.RefURL(repoLink, issue.Ref) } } return issueRefEndNames, issueRefURLs @@ -224,7 +222,7 @@ func GetRefEndNamesAndURLs(issues []*issues_model.Issue, repoLink string) (map[i // deleteIssue deletes the issue func deleteIssue(issue *issues_model.Issue) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -235,9 +233,16 @@ func deleteIssue(issue *issues_model.Issue) error { return err } - if err := repo_model.UpdateRepoIssueNumbers(ctx, issue.RepoID, issue.IsPull, issue.IsClosed); err != nil { + // update the total issue numbers + if err := repo_model.UpdateRepoIssueNumbers(ctx, issue.RepoID, issue.IsPull, false); err != nil { return err } + // if the issue is closed, update the closed issue numbers + if issue.IsClosed { + if err := repo_model.UpdateRepoIssueNumbers(ctx, issue.RepoID, issue.IsPull, true); err != nil { + return err + } + } if err := issues_model.UpdateMilestoneCounters(ctx, issue.MilestoneID); err != nil { return fmt.Errorf("error updating counters for milestone id %d: %w", diff --git a/services/issue/issue_test.go b/services/issue/issue_test.go index 20f3a3296c..b67d2e2e79 100644 --- a/services/issue/issue_test.go +++ b/services/issue/issue_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package issue @@ -67,7 +66,7 @@ func TestIssue_DeleteIssue(t *testing.T) { } // check issue dependencies - user, err := user_model.GetUserByID(1) + user, err := user_model.GetUserByID(db.DefaultContext, 1) assert.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) assert.NoError(t, err) diff --git a/services/issue/label.go b/services/issue/label.go index bc5f9b910e..c18abbfcda 100644 --- a/services/issue/label.go +++ b/services/issue/label.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issue @@ -18,7 +17,7 @@ func ClearLabels(issue *issues_model.Issue, doer *user_model.User) (err error) { return } - notification.NotifyIssueClearLabels(doer, issue) + notification.NotifyIssueClearLabels(db.DefaultContext, doer, issue) return nil } @@ -29,7 +28,7 @@ func AddLabel(issue *issues_model.Issue, doer *user_model.User, label *issues_mo return err } - notification.NotifyIssueChangeLabels(doer, issue, []*issues_model.Label{label}, nil) + notification.NotifyIssueChangeLabels(db.DefaultContext, doer, issue, []*issues_model.Label{label}, nil) return nil } @@ -39,13 +38,13 @@ func AddLabels(issue *issues_model.Issue, doer *user_model.User, labels []*issue return err } - notification.NotifyIssueChangeLabels(doer, issue, labels, nil) + notification.NotifyIssueChangeLabels(db.DefaultContext, doer, issue, labels, nil) return nil } // RemoveLabel removes a label from issue by given ID. func RemoveLabel(issue *issues_model.Issue, doer *user_model.User, label *issues_model.Label) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -74,7 +73,7 @@ func RemoveLabel(issue *issues_model.Issue, doer *user_model.User, label *issues return err } - notification.NotifyIssueChangeLabels(doer, issue, nil, []*issues_model.Label{label}) + notification.NotifyIssueChangeLabels(db.DefaultContext, doer, issue, nil, []*issues_model.Label{label}) return nil } @@ -89,6 +88,6 @@ func ReplaceLabels(issue *issues_model.Issue, doer *user_model.User, labels []*i return err } - notification.NotifyIssueChangeLabels(doer, issue, labels, old) + notification.NotifyIssueChangeLabels(db.DefaultContext, doer, issue, labels, old) return nil } diff --git a/services/issue/label_test.go b/services/issue/label_test.go index 482db95139..af220601f1 100644 --- a/services/issue/label_test.go +++ b/services/issue/label_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package issue diff --git a/services/issue/main_test.go b/services/issue/main_test.go index 689ae744f6..0f2427122f 100644 --- a/services/issue/main_test.go +++ b/services/issue/main_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issue diff --git a/services/issue/milestone.go b/services/issue/milestone.go index 756a8625de..a9be8bd887 100644 --- a/services/issue/milestone.go +++ b/services/issue/milestone.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issue @@ -55,7 +54,7 @@ func changeMilestoneAssign(ctx context.Context, doer *user_model.User, issue *is OldMilestoneID: oldMilestoneID, MilestoneID: issue.MilestoneID, } - if _, err := issues_model.CreateCommentCtx(ctx, opts); err != nil { + if _, err := issues_model.CreateComment(ctx, opts); err != nil { return err } } @@ -65,7 +64,7 @@ func changeMilestoneAssign(ctx context.Context, doer *user_model.User, issue *is // ChangeMilestoneAssign changes assignment of milestone for issue. func ChangeMilestoneAssign(issue *issues_model.Issue, doer *user_model.User, oldMilestoneID int64) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -79,7 +78,7 @@ func ChangeMilestoneAssign(issue *issues_model.Issue, doer *user_model.User, old return fmt.Errorf("Commit: %w", err) } - notification.NotifyIssueChangeMilestone(doer, issue, oldMilestoneID) + notification.NotifyIssueChangeMilestone(db.DefaultContext, doer, issue, oldMilestoneID) return nil } diff --git a/services/issue/milestone_test.go b/services/issue/milestone_test.go index 087c256700..069117d1f1 100644 --- a/services/issue/milestone_test.go +++ b/services/issue/milestone_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issue diff --git a/services/issue/status.go b/services/issue/status.go index 0da5c88762..782ce0bd96 100644 --- a/services/issue/status.go +++ b/services/issue/status.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package issue @@ -38,7 +37,7 @@ func changeStatusCtx(ctx context.Context, issue *issues_model.Issue, doer *user_ } } - notification.NotifyIssueChangeStatus(doer, issue, comment, closed) + notification.NotifyIssueChangeStatus(ctx, doer, issue, comment, closed) return nil } diff --git a/services/lfs/locks.go b/services/lfs/locks.go index e87589d124..0dc51f063c 100644 --- a/services/lfs/locks.go +++ b/services/lfs/locks.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package lfs @@ -40,7 +39,7 @@ func handleLockListOut(ctx *context.Context, repo *repo_model.Repository, lock * return } ctx.JSON(http.StatusOK, api.LFSLockList{ - Locks: []*api.LFSLock{convert.ToLFSLock(lock)}, + Locks: []*api.LFSLock{convert.ToLFSLock(ctx, lock)}, }) } @@ -48,7 +47,7 @@ func handleLockListOut(ctx *context.Context, repo *repo_model.Repository, lock * func GetListLockHandler(ctx *context.Context) { rv := getRequestContext(ctx) - repository, err := repo_model.GetRepositoryByOwnerAndName(rv.User, rv.Repo) + repository, err := repo_model.GetRepositoryByOwnerAndName(ctx, rv.User, rv.Repo) if err != nil { log.Debug("Could not find repository: %s/%s - %s", rv.User, rv.Repo, err) ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") @@ -57,7 +56,7 @@ func GetListLockHandler(ctx *context.Context) { }) return } - repository.MustOwner() + repository.MustOwner(ctx) authenticated := authenticate(ctx, repository, rv.Authorization, true, false) if !authenticated { @@ -118,7 +117,7 @@ func GetListLockHandler(ctx *context.Context) { lockListAPI := make([]*api.LFSLock, len(lockList)) next := "" for i, l := range lockList { - lockListAPI[i] = convert.ToLFSLock(l) + lockListAPI[i] = convert.ToLFSLock(ctx, l) } if limit > 0 && len(lockList) == limit { next = strconv.Itoa(cursor + 1) @@ -135,7 +134,7 @@ func PostLockHandler(ctx *context.Context) { repoName := strings.TrimSuffix(ctx.Params("reponame"), ".git") authorization := ctx.Req.Header.Get("Authorization") - repository, err := repo_model.GetRepositoryByOwnerAndName(userName, repoName) + repository, err := repo_model.GetRepositoryByOwnerAndName(ctx, userName, repoName) if err != nil { log.Error("Unable to get repository: %s/%s Error: %v", userName, repoName, err) ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") @@ -144,7 +143,7 @@ func PostLockHandler(ctx *context.Context) { }) return } - repository.MustOwner() + repository.MustOwner(ctx) authenticated := authenticate(ctx, repository, authorization, true, true) if !authenticated { @@ -175,7 +174,7 @@ func PostLockHandler(ctx *context.Context) { if err != nil { if git_model.IsErrLFSLockAlreadyExist(err) { ctx.JSON(http.StatusConflict, api.LFSLockError{ - Lock: convert.ToLFSLock(lock), + Lock: convert.ToLFSLock(ctx, lock), Message: "already created lock", }) return @@ -193,7 +192,7 @@ func PostLockHandler(ctx *context.Context) { }) return } - ctx.JSON(http.StatusCreated, api.LFSLockResponse{Lock: convert.ToLFSLock(lock)}) + ctx.JSON(http.StatusCreated, api.LFSLockResponse{Lock: convert.ToLFSLock(ctx, lock)}) } // VerifyLockHandler list locks for verification @@ -202,7 +201,7 @@ func VerifyLockHandler(ctx *context.Context) { repoName := strings.TrimSuffix(ctx.Params("reponame"), ".git") authorization := ctx.Req.Header.Get("Authorization") - repository, err := repo_model.GetRepositoryByOwnerAndName(userName, repoName) + repository, err := repo_model.GetRepositoryByOwnerAndName(ctx, userName, repoName) if err != nil { log.Error("Unable to get repository: %s/%s Error: %v", userName, repoName, err) ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") @@ -211,7 +210,7 @@ func VerifyLockHandler(ctx *context.Context) { }) return } - repository.MustOwner() + repository.MustOwner(ctx) authenticated := authenticate(ctx, repository, authorization, true, true) if !authenticated { @@ -250,9 +249,9 @@ func VerifyLockHandler(ctx *context.Context) { lockTheirsListAPI := make([]*api.LFSLock, 0, len(lockList)) for _, l := range lockList { if l.OwnerID == ctx.Doer.ID { - lockOursListAPI = append(lockOursListAPI, convert.ToLFSLock(l)) + lockOursListAPI = append(lockOursListAPI, convert.ToLFSLock(ctx, l)) } else { - lockTheirsListAPI = append(lockTheirsListAPI, convert.ToLFSLock(l)) + lockTheirsListAPI = append(lockTheirsListAPI, convert.ToLFSLock(ctx, l)) } } ctx.JSON(http.StatusOK, api.LFSLockListVerify{ @@ -268,7 +267,7 @@ func UnLockHandler(ctx *context.Context) { repoName := strings.TrimSuffix(ctx.Params("reponame"), ".git") authorization := ctx.Req.Header.Get("Authorization") - repository, err := repo_model.GetRepositoryByOwnerAndName(userName, repoName) + repository, err := repo_model.GetRepositoryByOwnerAndName(ctx, userName, repoName) if err != nil { log.Error("Unable to get repository: %s/%s Error: %v", userName, repoName, err) ctx.Resp.Header().Set("WWW-Authenticate", "Basic realm=gitea-lfs") @@ -277,7 +276,7 @@ func UnLockHandler(ctx *context.Context) { }) return } - repository.MustOwner() + repository.MustOwner(ctx) authenticated := authenticate(ctx, repository, authorization, true, true) if !authenticated { @@ -316,5 +315,5 @@ func UnLockHandler(ctx *context.Context) { }) return } - ctx.JSON(http.StatusOK, api.LFSLockResponse{Lock: convert.ToLFSLock(lock)}) + ctx.JSON(http.StatusOK, api.LFSLockResponse{Lock: convert.ToLFSLock(ctx, lock)}) } diff --git a/services/lfs/server.go b/services/lfs/server.go index 830112fac6..8fd2759132 100644 --- a/services/lfs/server.go +++ b/services/lfs/server.go @@ -1,10 +1,10 @@ // 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. +// SPDX-License-Identifier: MIT package lfs import ( + stdCtx "context" "crypto/sha256" "encoding/base64" "encoding/hex" @@ -409,7 +409,7 @@ func getAuthenticatedMeta(ctx *context.Context, rc *requestContext, p lfs_module } func getAuthenticatedRepository(ctx *context.Context, rc *requestContext, requireWrite bool) *repo_model.Repository { - repository, err := repo_model.GetRepositoryByOwnerAndName(rc.User, rc.Repo) + repository, err := repo_model.GetRepositoryByOwnerAndName(ctx, rc.User, rc.Repo) if err != nil { log.Error("Unable to get repository: %s/%s Error: %v", rc.User, rc.Repo, err) writeStatus(ctx, http.StatusNotFound) @@ -507,7 +507,7 @@ func authenticate(ctx *context.Context, repository *repo_model.Repository, autho return true } - user, err := parseToken(authorization, repository, accessMode) + user, err := parseToken(ctx, authorization, repository, accessMode) if err != nil { // Most of these are Warn level - the true internal server errors are logged in parseToken already log.Warn("Authentication failure for provided token with Error: %v", err) @@ -517,7 +517,7 @@ func authenticate(ctx *context.Context, repository *repo_model.Repository, autho return true } -func handleLFSToken(tokenSHA string, target *repo_model.Repository, mode perm.AccessMode) (*user_model.User, error) { +func handleLFSToken(ctx stdCtx.Context, tokenSHA string, target *repo_model.Repository, mode perm.AccessMode) (*user_model.User, error) { if !strings.Contains(tokenSHA, ".") { return nil, nil } @@ -544,7 +544,7 @@ func handleLFSToken(tokenSHA string, target *repo_model.Repository, mode perm.Ac return nil, fmt.Errorf("invalid token claim") } - u, err := user_model.GetUserByID(claims.UserID) + u, err := user_model.GetUserByID(ctx, claims.UserID) if err != nil { log.Error("Unable to GetUserById[%d]: Error: %v", claims.UserID, err) return nil, err @@ -552,7 +552,7 @@ func handleLFSToken(tokenSHA string, target *repo_model.Repository, mode perm.Ac return u, nil } -func parseToken(authorization string, target *repo_model.Repository, mode perm.AccessMode) (*user_model.User, error) { +func parseToken(ctx stdCtx.Context, authorization string, target *repo_model.Repository, mode perm.AccessMode) (*user_model.User, error) { if authorization == "" { return nil, fmt.Errorf("no token") } @@ -566,7 +566,7 @@ func parseToken(authorization string, target *repo_model.Repository, mode perm.A case "bearer": fallthrough case "token": - return handleLFSToken(tokenSHA, target, mode) + return handleLFSToken(ctx, tokenSHA, target, mode) } return nil, fmt.Errorf("token not found") } diff --git a/services/mailer/mail.go b/services/mailer/mail.go index 85a7d107e5..674011bede 100644 --- a/services/mailer/mail.go +++ b/services/mailer/mail.go @@ -1,7 +1,6 @@ // Copyright 2016 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package mailer @@ -18,7 +17,6 @@ import ( "time" activities_model "code.gitea.io/gitea/models/activities" - "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" @@ -265,7 +263,7 @@ func composeIssueCommentMessages(ctx *mailCommentContext, lang string, recipient "Issue": ctx.Issue, "Comment": ctx.Comment, "IsPull": ctx.Issue.IsPull, - "User": ctx.Issue.Repo.MustOwner(), + "User": ctx.Issue.Repo.MustOwner(ctx), "Repo": ctx.Issue.Repo.FullName(), "Doer": ctx.Doer, "IsMention": fromMention, @@ -395,13 +393,13 @@ func sanitizeSubject(subject string) string { } // SendIssueAssignedMail composes and sends issue assigned email -func SendIssueAssignedMail(issue *issues_model.Issue, doer *user_model.User, content string, comment *issues_model.Comment, recipients []*user_model.User) error { +func SendIssueAssignedMail(ctx context.Context, issue *issues_model.Issue, doer *user_model.User, content string, comment *issues_model.Comment, recipients []*user_model.User) error { if setting.MailService == nil { // No mail service configured return nil } - if err := issue.LoadRepo(db.DefaultContext); err != nil { + if err := issue.LoadRepo(ctx); err != nil { log.Error("Unable to load repo [%d] for issue #%d [%d]. Error: %v", issue.RepoID, issue.Index, issue.ID, err) return err } @@ -417,7 +415,7 @@ func SendIssueAssignedMail(issue *issues_model.Issue, doer *user_model.User, con for lang, tos := range langMap { msgs, err := composeIssueCommentMessages(&mailCommentContext{ - Context: context.TODO(), // TODO: use a correct context + Context: ctx, Issue: issue, Doer: doer, ActionType: activities_model.ActionType(0), diff --git a/services/mailer/mail_comment.go b/services/mailer/mail_comment.go index af07821c29..1812441d5a 100644 --- a/services/mailer/mail_comment.go +++ b/services/mailer/mail_comment.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package mailer diff --git a/services/mailer/mail_issue.go b/services/mailer/mail_issue.go index 61e276805d..be5279aac5 100644 --- a/services/mailer/mail_issue.go +++ b/services/mailer/mail_issue.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package mailer @@ -45,13 +44,13 @@ const ( func mailIssueCommentToParticipants(ctx *mailCommentContext, mentions []*user_model.User) error { // Required by the mail composer; make sure to load these before calling the async function if err := ctx.Issue.LoadRepo(ctx); err != nil { - return fmt.Errorf("LoadRepo(): %w", err) + return fmt.Errorf("LoadRepo: %w", err) } - if err := ctx.Issue.LoadPoster(); err != nil { - return fmt.Errorf("LoadPoster(): %w", err) + if err := ctx.Issue.LoadPoster(ctx); err != nil { + return fmt.Errorf("LoadPoster: %w", err) } - if err := ctx.Issue.LoadPullRequest(); err != nil { - return fmt.Errorf("LoadPullRequest(): %w", err) + if err := ctx.Issue.LoadPullRequest(ctx); err != nil { + return fmt.Errorf("LoadPullRequest: %w", err) } // Enough room to avoid reallocations @@ -61,14 +60,14 @@ func mailIssueCommentToParticipants(ctx *mailCommentContext, mentions []*user_mo unfiltered[0] = ctx.Issue.PosterID // =========== Assignees =========== - ids, err := issues_model.GetAssigneeIDsByIssue(ctx.Issue.ID) + ids, err := issues_model.GetAssigneeIDsByIssue(ctx, ctx.Issue.ID) if err != nil { return fmt.Errorf("GetAssigneeIDsByIssue(%d): %w", ctx.Issue.ID, err) } unfiltered = append(unfiltered, ids...) // =========== Participants (i.e. commenters, reviewers) =========== - ids, err = issues_model.GetParticipantsIDsByIssueID(ctx.Issue.ID) + ids, err = issues_model.GetParticipantsIDsByIssueID(ctx, ctx.Issue.ID) if err != nil { return fmt.Errorf("GetParticipantsIDsByIssueID(%d): %w", ctx.Issue.ID, err) } @@ -110,7 +109,7 @@ func mailIssueCommentToParticipants(ctx *mailCommentContext, mentions []*user_mo } visited.AddMultiple(ids...) - unfilteredUsers, err := user_model.GetMaileableUsersByIDs(unfiltered, false) + unfilteredUsers, err := user_model.GetMaileableUsersByIDs(ctx, unfiltered, false) if err != nil { return err } @@ -173,7 +172,7 @@ func mailIssueCommentBatch(ctx *mailCommentContext, users []*user_model.User, vi // MailParticipants sends new issue thread created emails to repository watchers // and mentioned people. -func MailParticipants(issue *issues_model.Issue, doer *user_model.User, opType activities_model.ActionType, mentions []*user_model.User) error { +func MailParticipants(ctx context.Context, issue *issues_model.Issue, doer *user_model.User, opType activities_model.ActionType, mentions []*user_model.User) error { if setting.MailService == nil { // No mail service configured return nil @@ -188,7 +187,7 @@ func MailParticipants(issue *issues_model.Issue, doer *user_model.User, opType a forceDoerNotification := opType == activities_model.ActionAutoMergePullRequest if err := mailIssueCommentToParticipants( &mailCommentContext{ - Context: context.TODO(), // TODO: use a correct context + Context: ctx, Issue: issue, Doer: doer, ActionType: opType, diff --git a/services/mailer/mail_release.go b/services/mailer/mail_release.go index 6df3fbbf1d..96227270c8 100644 --- a/services/mailer/mail_release.go +++ b/services/mailer/mail_release.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package mailer @@ -36,7 +35,7 @@ func MailNewRelease(ctx context.Context, rel *repo_model.Release) { return } - recipients, err := user_model.GetMaileableUsersByIDs(watcherIDList, false) + recipients, err := user_model.GetMaileableUsersByIDs(ctx, watcherIDList, false) if err != nil { log.Error("user_model.GetMaileableUsersByIDs: %v", err) return diff --git a/services/mailer/mail_repo.go b/services/mailer/mail_repo.go index 6fe9df0926..5fa13f5044 100644 --- a/services/mailer/mail_repo.go +++ b/services/mailer/mail_repo.go @@ -1,14 +1,13 @@ // 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. +// SPDX-License-Identifier: MIT package mailer import ( "bytes" + "context" "fmt" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" @@ -18,14 +17,14 @@ import ( ) // SendRepoTransferNotifyMail triggers a notification e-mail when a pending repository transfer was created -func SendRepoTransferNotifyMail(doer, newOwner *user_model.User, repo *repo_model.Repository) error { +func SendRepoTransferNotifyMail(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository) error { if setting.MailService == nil { // No mail service configured return nil } if newOwner.IsOrganization() { - users, err := organization.GetUsersWhoCanCreateOrgRepo(db.DefaultContext, newOwner.ID) + users, err := organization.GetUsersWhoCanCreateOrgRepo(ctx, newOwner.ID) if err != nil { return err } diff --git a/services/mailer/mail_team_invite.go b/services/mailer/mail_team_invite.go index c2b2a00e76..54e82b0234 100644 --- a/services/mailer/mail_team_invite.go +++ b/services/mailer/mail_team_invite.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package mailer @@ -27,7 +26,7 @@ func MailTeamInvite(ctx context.Context, inviter *user_model.User, team *org_mod return nil } - org, err := user_model.GetUserByIDCtx(ctx, team.OrgID) + org, err := user_model.GetUserByID(ctx, team.OrgID) if err != nil { return err } diff --git a/services/mailer/mail_test.go b/services/mailer/mail_test.go index acb1f69961..6ed4fed9bd 100644 --- a/services/mailer/mail_test.go +++ b/services/mailer/mail_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package mailer diff --git a/services/mailer/mailer.go b/services/mailer/mailer.go index 46b0c8e2f4..6149644600 100644 --- a/services/mailer/mailer.go +++ b/services/mailer/mailer.go @@ -1,7 +1,6 @@ // Copyright 2014 The Gogs Authors. All rights reserved. // Copyright 2017 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. +// SPDX-License-Identifier: MIT package mailer @@ -166,7 +165,7 @@ func (s *smtpSender) Send(from string, to []string, msg io.WriterTo) error { defer conn.Close() var tlsconfig *tls.Config - if opts.Protocol == "smtps" || opts.Protocol == "smtp+startls" { + if opts.Protocol == "smtps" || opts.Protocol == "smtp+starttls" { tlsconfig = &tls.Config{ InsecureSkipVerify: opts.ForceTrustServerCert, ServerName: opts.SMTPAddr, @@ -208,7 +207,7 @@ func (s *smtpSender) Send(from string, to []string, msg io.WriterTo) error { } } - if opts.Protocol == "smtp+startls" { + if opts.Protocol == "smtp+starttls" { hasStartTLS, _ := client.Extension("STARTTLS") if hasStartTLS { if err = client.StartTLS(tlsconfig); err != nil { diff --git a/services/mailer/mailer_test.go b/services/mailer/mailer_test.go index b94fce8443..79c5231218 100644 --- a/services/mailer/mailer_test.go +++ b/services/mailer/mailer_test.go @@ -1,6 +1,5 @@ // Copyright 2021 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package mailer diff --git a/services/mailer/main_test.go b/services/mailer/main_test.go index 0bd154113f..16a6a26545 100644 --- a/services/mailer/main_test.go +++ b/services/mailer/main_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package mailer diff --git a/services/markup/main_test.go b/services/markup/main_test.go index 8efd08e69d..ce892435a1 100644 --- a/services/markup/main_test.go +++ b/services/markup/main_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package markup diff --git a/services/markup/processorhelper.go b/services/markup/processorhelper.go index 5042884e5e..2897f203a9 100644 --- a/services/markup/processorhelper.go +++ b/services/markup/processorhelper.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package markup diff --git a/services/markup/processorhelper_test.go b/services/markup/processorhelper_test.go index f7eab3d958..6c9c1c27e7 100644 --- a/services/markup/processorhelper_test.go +++ b/services/markup/processorhelper_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package markup diff --git a/services/migrations/codebase.go b/services/migrations/codebase.go index edeb276773..c02c8e13a2 100644 --- a/services/migrations/codebase.go +++ b/services/migrations/codebase.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/codebase_test.go b/services/migrations/codebase_test.go index 03b5946d71..68721e0641 100644 --- a/services/migrations/codebase_test.go +++ b/services/migrations/codebase_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/common.go b/services/migrations/common.go index 052975c9e7..34d7c93ddf 100644 --- a/services/migrations/common.go +++ b/services/migrations/common.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/dump.go b/services/migrations/dump.go index 4ab4539c89..cc8518d4a2 100644 --- a/services/migrations/dump.go +++ b/services/migrations/dump.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package migrations @@ -26,7 +25,7 @@ import ( "code.gitea.io/gitea/modules/structs" "github.com/google/uuid" - "gopkg.in/yaml.v2" + "gopkg.in/yaml.v3" ) var _ base.Uploader = &RepositoryDumper{} diff --git a/services/migrations/error.go b/services/migrations/error.go index d26fa8112c..46d303ac8e 100644 --- a/services/migrations/error.go +++ b/services/migrations/error.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/git.go b/services/migrations/git.go index 3198f934ca..22ffd5e765 100644 --- a/services/migrations/git.go +++ b/services/migrations/git.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/gitbucket.go b/services/migrations/gitbucket.go index 21d8c672dd..65c138ed04 100644 --- a/services/migrations/gitbucket.go +++ b/services/migrations/gitbucket.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/gitea_downloader.go b/services/migrations/gitea_downloader.go index 9775af1cdc..470090b501 100644 --- a/services/migrations/gitea_downloader.go +++ b/services/migrations/gitea_downloader.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/gitea_downloader_test.go b/services/migrations/gitea_downloader_test.go index 601b0a7c79..c37c70947e 100644 --- a/services/migrations/gitea_downloader_test.go +++ b/services/migrations/gitea_downloader_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/gitea_uploader.go b/services/migrations/gitea_uploader.go index 8a7533b3d1..f3848e616c 100644 --- a/services/migrations/gitea_uploader.go +++ b/services/migrations/gitea_uploader.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migrations @@ -110,7 +109,7 @@ func (g *GiteaLocalUploader) CreateRepo(repo *base.Repository, opts base.Migrate Status: repo_model.RepositoryBeingMigrated, }) } else { - r, err = repo_model.GetRepositoryByID(opts.MigrateToRepoID) + r, err = repo_model.GetRepositoryByID(g.ctx, opts.MigrateToRepoID) } if err != nil { return err diff --git a/services/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go index 68a7182b07..6a942b9b57 100644 --- a/services/migrations/gitea_uploader_test.go +++ b/services/migrations/gitea_uploader_test.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migrations @@ -84,7 +83,7 @@ func TestGiteaUploadRepo(t *testing.T) { assert.NoError(t, err) assert.Len(t, labels, 12) - releases, err := repo_model.GetReleasesByRepoID(repo.ID, repo_model.FindReleasesOptions{ + releases, err := repo_model.GetReleasesByRepoID(db.DefaultContext, repo.ID, repo_model.FindReleasesOptions{ ListOptions: db.ListOptions{ PageSize: 10, Page: 0, @@ -94,7 +93,7 @@ func TestGiteaUploadRepo(t *testing.T) { assert.NoError(t, err) assert.Len(t, releases, 8) - releases, err = repo_model.GetReleasesByRepoID(repo.ID, repo_model.FindReleasesOptions{ + releases, err = repo_model.GetReleasesByRepoID(db.DefaultContext, repo.ID, repo_model.FindReleasesOptions{ ListOptions: db.ListOptions{ PageSize: 10, Page: 0, @@ -104,14 +103,14 @@ func TestGiteaUploadRepo(t *testing.T) { assert.NoError(t, err) assert.Len(t, releases, 1) - issues, err := issues_model.Issues(&issues_model.IssuesOptions{ + issues, err := issues_model.Issues(db.DefaultContext, &issues_model.IssuesOptions{ RepoID: repo.ID, IsPull: util.OptionalBoolFalse, SortType: "oldest", }) assert.NoError(t, err) assert.Len(t, issues, 15) - assert.NoError(t, issues[0].LoadDiscussComments()) + assert.NoError(t, issues[0].LoadDiscussComments(db.DefaultContext)) assert.Empty(t, issues[0].Comments) pulls, _, err := issues_model.PullRequests(repo.ID, &issues_model.PullRequestsOptions{ @@ -119,8 +118,8 @@ func TestGiteaUploadRepo(t *testing.T) { }) assert.NoError(t, err) assert.Len(t, pulls, 30) - assert.NoError(t, pulls[0].LoadIssue()) - assert.NoError(t, pulls[0].Issue.LoadDiscussComments()) + assert.NoError(t, pulls[0].LoadIssue(db.DefaultContext)) + assert.NoError(t, pulls[0].Issue.LoadDiscussComments(db.DefaultContext)) assert.Len(t, pulls[0].Issue.Comments, 2) } diff --git a/services/migrations/github.go b/services/migrations/github.go index e5683fb530..48dd90323d 100644 --- a/services/migrations/github.go +++ b/services/migrations/github.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/github_test.go b/services/migrations/github_test.go index 90c1fcaef5..2b89e6dc0f 100644 --- a/services/migrations/github_test.go +++ b/services/migrations/github_test.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migrations @@ -18,7 +17,11 @@ import ( func TestGitHubDownloadRepo(t *testing.T) { GithubLimitRateRemaining = 3 // Wait at 3 remaining since we could have 3 CI in // - downloader := NewGithubDownloaderV3(context.Background(), "https://github.com", "", "", os.Getenv("GITHUB_READ_TOKEN"), "go-gitea", "test_repo") + token := os.Getenv("GITHUB_READ_TOKEN") + if token == "" { + t.Skip("Skipping GitHub migration test because GITHUB_READ_TOKEN is empty") + } + downloader := NewGithubDownloaderV3(context.Background(), "https://github.com", "", "", token, "go-gitea", "test_repo") err := downloader.RefreshRate() assert.NoError(t, err) diff --git a/services/migrations/gitlab.go b/services/migrations/gitlab.go index b8bb0c77b5..44e1d70713 100644 --- a/services/migrations/gitlab.go +++ b/services/migrations/gitlab.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/gitlab_test.go b/services/migrations/gitlab_test.go index 829964b384..1d8c5989bb 100644 --- a/services/migrations/gitlab_test.go +++ b/services/migrations/gitlab_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/gogs.go b/services/migrations/gogs.go index 14bc734c4e..d01934ac6d 100644 --- a/services/migrations/gogs.go +++ b/services/migrations/gogs.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/gogs_test.go b/services/migrations/gogs_test.go index 501161b610..610af183de 100644 --- a/services/migrations/gogs_test.go +++ b/services/migrations/gogs_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/http_client.go b/services/migrations/http_client.go index 0d683693a1..9e3caec191 100644 --- a/services/migrations/http_client.go +++ b/services/migrations/http_client.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/main_test.go b/services/migrations/main_test.go index ad9bc9c731..30875f6e5b 100644 --- a/services/migrations/main_test.go +++ b/services/migrations/main_test.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/migrate.go b/services/migrations/migrate.go index dfb21b884b..a3b9d1cfa8 100644 --- a/services/migrations/migrate.go +++ b/services/migrations/migrate.go @@ -1,7 +1,6 @@ // Copyright 2019 The Gitea Authors. All rights reserved. // Copyright 2018 Jonas Franz. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/migrate_test.go b/services/migrations/migrate_test.go index 3fc4034777..03efa6185b 100644 --- a/services/migrations/migrate_test.go +++ b/services/migrations/migrate_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/onedev.go b/services/migrations/onedev.go index 8cc826c3b4..d4b1b73d37 100644 --- a/services/migrations/onedev.go +++ b/services/migrations/onedev.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/onedev_test.go b/services/migrations/onedev_test.go index 6a17eb334b..48412fec64 100644 --- a/services/migrations/onedev_test.go +++ b/services/migrations/onedev_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/migrations/restore.go b/services/migrations/restore.go index c3fbcbb25f..fd337b22c7 100644 --- a/services/migrations/restore.go +++ b/services/migrations/restore.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package migrations @@ -13,7 +12,7 @@ import ( base "code.gitea.io/gitea/modules/migration" - "gopkg.in/yaml.v2" + "gopkg.in/yaml.v3" ) // RepositoryRestorer implements an Downloader from the local directory diff --git a/services/migrations/update.go b/services/migrations/update.go index cdec73cd1b..48b61885e8 100644 --- a/services/migrations/update.go +++ b/services/migrations/update.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package migrations diff --git a/services/mirror/mirror.go b/services/mirror/mirror.go index 3b4a8e5f8a..9e569a70e3 100644 --- a/services/mirror/mirror.go +++ b/services/mirror/mirror.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package mirror diff --git a/services/mirror/mirror_pull.go b/services/mirror/mirror_pull.go index 6002e6b8ed..98e8d122a5 100644 --- a/services/mirror/mirror_pull.go +++ b/services/mirror/mirror_pull.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package mirror @@ -459,18 +458,18 @@ func SyncPullMirror(ctx context.Context, repoID int64) bool { log.Error("SyncMirrors [repo: %-v]: unable to GetRefCommitID [ref_name: %s]: %v", m.Repo, result.refName, err) continue } - notification.NotifySyncPushCommits(m.Repo.MustOwner(), m.Repo, &repo_module.PushUpdateOptions{ + notification.NotifySyncPushCommits(ctx, m.Repo.MustOwner(ctx), m.Repo, &repo_module.PushUpdateOptions{ RefFullName: result.refName, OldCommitID: git.EmptySHA, NewCommitID: commitID, }, repo_module.NewPushCommits()) - notification.NotifySyncCreateRef(m.Repo.MustOwner(), m.Repo, tp, result.refName, commitID) + notification.NotifySyncCreateRef(ctx, m.Repo.MustOwner(ctx), m.Repo, tp, result.refName, commitID) continue } // Delete reference if result.newCommitID == gitShortEmptySha { - notification.NotifySyncDeleteRef(m.Repo.MustOwner(), m.Repo, tp, result.refName) + notification.NotifySyncDeleteRef(ctx, m.Repo.MustOwner(ctx), m.Repo, tp, result.refName) continue } @@ -498,7 +497,7 @@ func SyncPullMirror(ctx context.Context, repoID int64) bool { theCommits.CompareURL = m.Repo.ComposeCompareURL(oldCommitID, newCommitID) - notification.NotifySyncPushCommits(m.Repo.MustOwner(), m.Repo, &repo_module.PushUpdateOptions{ + notification.NotifySyncPushCommits(ctx, m.Repo.MustOwner(ctx), m.Repo, &repo_module.PushUpdateOptions{ RefFullName: result.refName, OldCommitID: oldCommitID, NewCommitID: newCommitID, diff --git a/services/mirror/mirror_push.go b/services/mirror/mirror_push.go index 60611130ba..c0c68a3f54 100644 --- a/services/mirror/mirror_push.go +++ b/services/mirror/mirror_push.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package mirror diff --git a/services/org/org.go b/services/org/org.go index 39845610d2..e45fb305de 100644 --- a/services/org/org.go +++ b/services/org/org.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package org @@ -19,7 +18,7 @@ import ( // DeleteOrganization completely and permanently deletes everything of organization. func DeleteOrganization(org *organization.Organization) error { - ctx, commiter, err := db.TxContext() + ctx, commiter, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/services/org/org_test.go b/services/org/org_test.go index c4e6088a71..cc22595c6f 100644 --- a/services/org/org_test.go +++ b/services/org/org_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package org diff --git a/services/org/repo.go b/services/org/repo.go index 769419d45b..179249c7a8 100644 --- a/services/org/repo.go +++ b/services/org/repo.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package org @@ -22,7 +21,7 @@ func TeamAddRepository(t *organization.Team, repo *repo_model.Repository) (err e return nil } - return db.WithTx(func(ctx context.Context) error { + return db.WithTx(db.DefaultContext, func(ctx context.Context) error { return models.AddRepository(ctx, t, repo) }) } diff --git a/services/org/repo_test.go b/services/org/repo_test.go index 21158bfa21..40b0d17077 100644 --- a/services/org/repo_test.go +++ b/services/org/repo_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package org diff --git a/services/org/team_invite.go b/services/org/team_invite.go index 1108a46da5..3f28044dbf 100644 --- a/services/org/team_invite.go +++ b/services/org/team_invite.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package org diff --git a/services/packages/auth.go b/services/packages/auth.go index 50212fccfd..9b84ac79a6 100644 --- a/services/packages/auth.go +++ b/services/packages/auth.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package packages diff --git a/services/packages/container/blob_uploader.go b/services/packages/container/blob_uploader.go index 762f9e5259..ba92b05073 100644 --- a/services/packages/container/blob_uploader.go +++ b/services/packages/container/blob_uploader.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package container diff --git a/services/packages/container/cleanup.go b/services/packages/container/cleanup.go index d23a481f27..d6d4d152c8 100644 --- a/services/packages/container/cleanup.go +++ b/services/packages/container/cleanup.go @@ -1,18 +1,16 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package container import ( "context" - "strings" "time" packages_model "code.gitea.io/gitea/models/packages" container_model "code.gitea.io/gitea/models/packages/container" - user_model "code.gitea.io/gitea/models/user" container_module "code.gitea.io/gitea/modules/packages/container" + "code.gitea.io/gitea/modules/packages/container/oci" "code.gitea.io/gitea/modules/util" ) @@ -82,24 +80,30 @@ func cleanupExpiredUploadedBlobs(ctx context.Context, olderThan time.Duration) e return nil } -// UpdateRepositoryNames updates the repository name property for all packages of the specific owner -func UpdateRepositoryNames(ctx context.Context, owner *user_model.User, newOwnerName string) error { - ps, err := packages_model.GetPackagesByType(ctx, owner.ID, packages_model.TypeContainer) - if err != nil { - return err +func ShouldBeSkipped(ctx context.Context, pcr *packages_model.PackageCleanupRule, p *packages_model.Package, pv *packages_model.PackageVersion) (bool, error) { + // Always skip the "latest" tag + if pv.LowerVersion == "latest" { + return true, nil } - newOwnerName = strings.ToLower(newOwnerName) - - for _, p := range ps { - if err := packages_model.DeletePropertyByName(ctx, packages_model.PropertyTypePackage, p.ID, container_module.PropertyRepository); err != nil { - return err + // Check if the version is a digest (or untagged) + if oci.Digest(pv.LowerVersion).Validate() { + // Check if there is another manifest referencing this version + has, err := packages_model.ExistVersion(ctx, &packages_model.PackageSearchOptions{ + PackageID: p.ID, + Properties: map[string]string{ + container_module.PropertyManifestReference: pv.LowerVersion, + }, + }) + if err != nil { + return false, err } - if _, err := packages_model.InsertProperty(ctx, packages_model.PropertyTypePackage, p.ID, container_module.PropertyRepository, newOwnerName+"/"+p.LowerName); err != nil { - return err + // Skip it if the version is referenced + if has { + return true, nil } } - return nil + return false, nil } diff --git a/services/packages/container/common.go b/services/packages/container/common.go new file mode 100644 index 0000000000..5a14ed5b7a --- /dev/null +++ b/services/packages/container/common.go @@ -0,0 +1,35 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package container + +import ( + "context" + "strings" + + packages_model "code.gitea.io/gitea/models/packages" + user_model "code.gitea.io/gitea/models/user" + container_module "code.gitea.io/gitea/modules/packages/container" +) + +// UpdateRepositoryNames updates the repository name property for all packages of the specific owner +func UpdateRepositoryNames(ctx context.Context, owner *user_model.User, newOwnerName string) error { + ps, err := packages_model.GetPackagesByType(ctx, owner.ID, packages_model.TypeContainer) + if err != nil { + return err + } + + newOwnerName = strings.ToLower(newOwnerName) + + for _, p := range ps { + if err := packages_model.DeletePropertyByName(ctx, packages_model.PropertyTypePackage, p.ID, container_module.PropertyRepository); err != nil { + return err + } + + if _, err := packages_model.InsertProperty(ctx, packages_model.PropertyTypePackage, p.ID, container_module.PropertyRepository, newOwnerName+"/"+p.LowerName); err != nil { + return err + } + } + + return nil +} diff --git a/services/packages/packages.go b/services/packages/packages.go index 96132eac09..49f5a2fac4 100644 --- a/services/packages/packages.go +++ b/services/packages/packages.go @@ -1,11 +1,12 @@ // 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. +// SPDX-License-Identifier: MIT package packages import ( "context" + "encoding/hex" + "errors" "fmt" "io" "strings" @@ -19,10 +20,17 @@ import ( "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/notification" packages_module "code.gitea.io/gitea/modules/packages" + "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/util" container_service "code.gitea.io/gitea/services/packages/container" ) +var ( + ErrQuotaTypeSize = errors.New("maximum allowed package type size exceeded") + ErrQuotaTotalSize = errors.New("maximum allowed package storage quota exceeded") + ErrQuotaTotalCount = errors.New("maximum allowed package count exceeded") +) + // PackageInfo describes a package type PackageInfo struct { Owner *user_model.User @@ -50,6 +58,7 @@ type PackageFileInfo struct { // PackageFileCreationInfo describes a package file to create type PackageFileCreationInfo struct { PackageFileInfo + Creator *user_model.User Data packages_module.HashedSizeReader IsLead bool Properties map[string]string @@ -67,7 +76,7 @@ func CreatePackageOrAddFileToExisting(pvci *PackageCreationInfo, pfci *PackageFi } func createPackageAndAddFile(pvci *PackageCreationInfo, pfci *PackageFileCreationInfo, allowDuplicate bool) (*packages_model.PackageVersion, *packages_model.PackageFile, error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, nil, err } @@ -78,7 +87,7 @@ func createPackageAndAddFile(pvci *PackageCreationInfo, pfci *PackageFileCreatio return nil, nil, err } - pf, pb, blobCreated, err := addFileToPackageVersion(ctx, pv, pfci) + pf, pb, blobCreated, err := addFileToPackageVersion(ctx, pv, &pvci.PackageInfo, pfci) removeBlob := false defer func() { if blobCreated && removeBlob { @@ -99,12 +108,12 @@ func createPackageAndAddFile(pvci *PackageCreationInfo, pfci *PackageFileCreatio } if created { - pd, err := packages_model.GetPackageDescriptor(ctx, pv) + pd, err := packages_model.GetPackageDescriptor(db.DefaultContext, pv) if err != nil { return nil, nil, err } - notification.NotifyPackageCreate(pvci.Creator, pd) + notification.NotifyPackageCreate(db.DefaultContext, pvci.Creator, pd) } return pv, pf, nil @@ -164,6 +173,10 @@ func createPackageAndVersion(ctx context.Context, pvci *PackageCreationInfo, all } if versionCreated { + if err := checkCountQuotaExceeded(ctx, pvci.Creator, pvci.Owner); err != nil { + return nil, false, err + } + for name, value := range pvci.VersionProperties { if _, err := packages_model.InsertProperty(ctx, packages_model.PropertyTypeVersion, pv.ID, name, value); err != nil { log.Error("Error setting package version property: %v", err) @@ -177,7 +190,7 @@ func createPackageAndVersion(ctx context.Context, pvci *PackageCreationInfo, all // AddFileToExistingPackage adds a file to an existing package. If the package does not exist, ErrPackageNotExist is returned func AddFileToExistingPackage(pvi *PackageInfo, pfci *PackageFileCreationInfo) (*packages_model.PackageVersion, *packages_model.PackageFile, error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, nil, err } @@ -188,7 +201,7 @@ func AddFileToExistingPackage(pvi *PackageInfo, pfci *PackageFileCreationInfo) ( return nil, nil, err } - pf, pb, blobCreated, err := addFileToPackageVersion(ctx, pv, pfci) + pf, pb, blobCreated, err := addFileToPackageVersion(ctx, pv, pvi, pfci) removeBlob := false defer func() { if removeBlob { @@ -217,16 +230,20 @@ func NewPackageBlob(hsr packages_module.HashedSizeReader) *packages_model.Packag return &packages_model.PackageBlob{ Size: hsr.Size(), - HashMD5: fmt.Sprintf("%x", hashMD5), - HashSHA1: fmt.Sprintf("%x", hashSHA1), - HashSHA256: fmt.Sprintf("%x", hashSHA256), - HashSHA512: fmt.Sprintf("%x", hashSHA512), + HashMD5: hex.EncodeToString(hashMD5), + HashSHA1: hex.EncodeToString(hashSHA1), + HashSHA256: hex.EncodeToString(hashSHA256), + HashSHA512: hex.EncodeToString(hashSHA512), } } -func addFileToPackageVersion(ctx context.Context, pv *packages_model.PackageVersion, pfci *PackageFileCreationInfo) (*packages_model.PackageFile, *packages_model.PackageBlob, bool, error) { +func addFileToPackageVersion(ctx context.Context, pv *packages_model.PackageVersion, pvi *PackageInfo, pfci *PackageFileCreationInfo) (*packages_model.PackageFile, *packages_model.PackageBlob, bool, error) { log.Trace("Adding package file: %v, %s", pv.ID, pfci.Filename) + if err := checkSizeQuotaExceeded(ctx, pfci.Creator, pvi.Owner, pvi.PackageType, pfci.Data.Size()); err != nil { + return nil, nil, false, err + } + pb, exists, err := packages_model.GetOrInsertBlob(ctx, NewPackageBlob(pfci.Data)) if err != nil { log.Error("Error inserting package blob: %v", err) @@ -285,6 +302,80 @@ func addFileToPackageVersion(ctx context.Context, pv *packages_model.PackageVers return pf, pb, !exists, nil } +func checkCountQuotaExceeded(ctx context.Context, doer, owner *user_model.User) error { + if doer.IsAdmin { + return nil + } + + if setting.Packages.LimitTotalOwnerCount > -1 { + totalCount, err := packages_model.CountVersions(ctx, &packages_model.PackageSearchOptions{ + OwnerID: owner.ID, + IsInternal: util.OptionalBoolFalse, + }) + if err != nil { + log.Error("CountVersions failed: %v", err) + return err + } + if totalCount > setting.Packages.LimitTotalOwnerCount { + return ErrQuotaTotalCount + } + } + + return nil +} + +func checkSizeQuotaExceeded(ctx context.Context, doer, owner *user_model.User, packageType packages_model.Type, uploadSize int64) error { + if doer.IsAdmin { + return nil + } + + var typeSpecificSize int64 + switch packageType { + case packages_model.TypeComposer: + typeSpecificSize = setting.Packages.LimitSizeComposer + case packages_model.TypeConan: + typeSpecificSize = setting.Packages.LimitSizeConan + case packages_model.TypeContainer: + typeSpecificSize = setting.Packages.LimitSizeContainer + case packages_model.TypeGeneric: + typeSpecificSize = setting.Packages.LimitSizeGeneric + case packages_model.TypeHelm: + typeSpecificSize = setting.Packages.LimitSizeHelm + case packages_model.TypeMaven: + typeSpecificSize = setting.Packages.LimitSizeMaven + case packages_model.TypeNpm: + typeSpecificSize = setting.Packages.LimitSizeNpm + case packages_model.TypeNuGet: + typeSpecificSize = setting.Packages.LimitSizeNuGet + case packages_model.TypePub: + typeSpecificSize = setting.Packages.LimitSizePub + case packages_model.TypePyPI: + typeSpecificSize = setting.Packages.LimitSizePyPI + case packages_model.TypeRubyGems: + typeSpecificSize = setting.Packages.LimitSizeRubyGems + case packages_model.TypeVagrant: + typeSpecificSize = setting.Packages.LimitSizeVagrant + } + if typeSpecificSize > -1 && typeSpecificSize < uploadSize { + return ErrQuotaTypeSize + } + + if setting.Packages.LimitTotalOwnerSize > -1 { + totalSize, err := packages_model.CalculateBlobSize(ctx, &packages_model.PackageFileSearchOptions{ + OwnerID: owner.ID, + }) + if err != nil { + log.Error("CalculateBlobSize failed: %v", err) + return err + } + if totalSize+uploadSize > setting.Packages.LimitTotalOwnerSize { + return ErrQuotaTotalSize + } + } + + return nil +} + // RemovePackageVersionByNameAndVersion deletes a package version and all associated files func RemovePackageVersionByNameAndVersion(doer *user_model.User, pvi *PackageInfo) error { pv, err := packages_model.GetVersionByNameAndVersion(db.DefaultContext, pvi.Owner.ID, pvi.PackageType, pvi.Name, pvi.Version) @@ -297,7 +388,7 @@ func RemovePackageVersionByNameAndVersion(doer *user_model.User, pvi *PackageInf // RemovePackageVersion deletes the package version and all associated files func RemovePackageVersion(doer *user_model.User, pv *packages_model.PackageVersion) error { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -318,7 +409,7 @@ func RemovePackageVersion(doer *user_model.User, pv *packages_model.PackageVersi return err } - notification.NotifyPackageDelete(doer, pd) + notification.NotifyPackageDelete(db.DefaultContext, doer, pd) return nil } @@ -352,13 +443,80 @@ func DeletePackageFile(ctx context.Context, pf *packages_model.PackageFile) erro } // Cleanup removes expired package data -func Cleanup(unused context.Context, olderThan time.Duration) error { - ctx, committer, err := db.TxContext() +func Cleanup(taskCtx context.Context, olderThan time.Duration) error { + ctx, committer, err := db.TxContext(taskCtx) if err != nil { return err } defer committer.Close() + err = packages_model.IterateEnabledCleanupRules(ctx, func(ctx context.Context, pcr *packages_model.PackageCleanupRule) error { + select { + case <-taskCtx.Done(): + return db.ErrCancelledf("While processing package cleanup rules") + default: + } + + if err := pcr.CompiledPattern(); err != nil { + return fmt.Errorf("CleanupRule [%d]: CompilePattern failed: %w", pcr.ID, err) + } + + olderThan := time.Now().AddDate(0, 0, -pcr.RemoveDays) + + packages, err := packages_model.GetPackagesByType(ctx, pcr.OwnerID, pcr.Type) + if err != nil { + return fmt.Errorf("CleanupRule [%d]: GetPackagesByType failed: %w", pcr.ID, err) + } + + for _, p := range packages { + pvs, _, err := packages_model.SearchVersions(ctx, &packages_model.PackageSearchOptions{ + PackageID: p.ID, + IsInternal: util.OptionalBoolFalse, + Sort: packages_model.SortCreatedDesc, + Paginator: db.NewAbsoluteListOptions(pcr.KeepCount, 200), + }) + if err != nil { + return fmt.Errorf("CleanupRule [%d]: SearchVersions failed: %w", pcr.ID, err) + } + for _, pv := range pvs { + if skip, err := container_service.ShouldBeSkipped(ctx, pcr, p, pv); err != nil { + return fmt.Errorf("CleanupRule [%d]: container.ShouldBeSkipped failed: %w", pcr.ID, err) + } else if skip { + log.Debug("Rule[%d]: keep '%s/%s' (container)", pcr.ID, p.Name, pv.Version) + continue + } + + toMatch := pv.LowerVersion + if pcr.MatchFullName { + toMatch = p.LowerName + "/" + pv.LowerVersion + } + + if pcr.KeepPatternMatcher != nil && pcr.KeepPatternMatcher.MatchString(toMatch) { + log.Debug("Rule[%d]: keep '%s/%s' (keep pattern)", pcr.ID, p.Name, pv.Version) + continue + } + if pv.CreatedUnix.AsLocalTime().After(olderThan) { + log.Debug("Rule[%d]: keep '%s/%s' (remove days)", pcr.ID, p.Name, pv.Version) + continue + } + if pcr.RemovePatternMatcher != nil && !pcr.RemovePatternMatcher.MatchString(toMatch) { + log.Debug("Rule[%d]: keep '%s/%s' (remove pattern)", pcr.ID, p.Name, pv.Version) + continue + } + + log.Debug("Rule[%d]: remove '%s/%s'", pcr.ID, p.Name, pv.Version) + + if err := DeletePackageVersionAndReferences(ctx, pv); err != nil { + return fmt.Errorf("CleanupRule [%d]: DeletePackageVersionAndReferences failed: %w", pcr.ID, err) + } + } + } + return nil + }) + if err != nil { + return err + } + if err := container_service.Cleanup(ctx, olderThan); err != nil { return err } diff --git a/services/pull/check.go b/services/pull/check.go index 830ff640b5..ed4b18107c 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -1,7 +1,6 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package pull @@ -48,7 +47,7 @@ var ( func AddToTaskQueue(pr *issues_model.PullRequest) { err := prPatchCheckerQueue.PushFunc(strconv.FormatInt(pr.ID, 10), func() error { pr.Status = issues_model.PullRequestStatusChecking - err := pr.UpdateColsIfNotMerged("status") + err := pr.UpdateColsIfNotMerged(db.DefaultContext, "status") if err != nil { log.Error("AddToTaskQueue.UpdateCols[%d].(add to queue): %v", pr.ID, err) } else { @@ -63,12 +62,12 @@ func AddToTaskQueue(pr *issues_model.PullRequest) { // CheckPullMergable check if the pull mergable based on all conditions (branch protection, merge options, ...) func CheckPullMergable(stdCtx context.Context, doer *user_model.User, perm *access_model.Permission, pr *issues_model.PullRequest, manuallMerge, force bool) error { - return db.WithTx(func(ctx context.Context) error { + return db.WithTx(stdCtx, func(ctx context.Context) error { if pr.HasMerged { return ErrHasMerged } - if err := pr.LoadIssueCtx(ctx); err != nil { + if err := pr.LoadIssue(ctx); err != nil { return err } else if pr.Issue.IsClosed { return ErrIsClosed @@ -122,12 +121,12 @@ func CheckPullMergable(stdCtx context.Context, doer *user_model.User, perm *acce } return nil - }, stdCtx) + }) } // isSignedIfRequired check if merge will be signed if required func isSignedIfRequired(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User) (bool, error) { - if err := pr.LoadProtectedBranchCtx(ctx); err != nil { + if err := pr.LoadProtectedBranch(ctx); err != nil { return false, err } @@ -142,7 +141,7 @@ func isSignedIfRequired(ctx context.Context, pr *issues_model.PullRequest, doer // checkAndUpdateStatus checks if pull request is possible to leaving checking status, // and set to be either conflict or mergeable. -func checkAndUpdateStatus(pr *issues_model.PullRequest) { +func checkAndUpdateStatus(ctx context.Context, pr *issues_model.PullRequest) { // Status is not changed to conflict means mergeable. if pr.Status == issues_model.PullRequestStatusChecking { pr.Status = issues_model.PullRequestStatusMergeable @@ -155,7 +154,7 @@ func checkAndUpdateStatus(pr *issues_model.PullRequest) { } if !has { - if err := pr.UpdateColsIfNotMerged("merge_base", "status", "conflicted_files", "changed_protected_files"); err != nil { + if err := pr.UpdateColsIfNotMerged(ctx, "merge_base", "status", "conflicted_files", "changed_protected_files"); err != nil { log.Error("Update[%d]: %v", pr.ID, err) } } @@ -166,7 +165,7 @@ func checkAndUpdateStatus(pr *issues_model.PullRequest) { func getMergeCommit(ctx context.Context, pr *issues_model.PullRequest) (*git.Commit, error) { if pr.BaseRepo == nil { var err error - pr.BaseRepo, err = repo_model.GetRepositoryByID(pr.BaseRepoID) + pr.BaseRepo, err = repo_model.GetRepositoryByID(ctx, pr.BaseRepoID) if err != nil { return nil, fmt.Errorf("GetRepositoryByID: %w", err) } @@ -232,12 +231,12 @@ func getMergeCommit(ctx context.Context, pr *issues_model.PullRequest) (*git.Com // manuallyMerged checks if a pull request got manually merged // When a pull request got manually merged mark the pull request as merged func manuallyMerged(ctx context.Context, pr *issues_model.PullRequest) bool { - if err := pr.LoadBaseRepoCtx(ctx); err != nil { + if err := pr.LoadBaseRepo(ctx); err != nil { log.Error("PullRequest[%d].LoadBaseRepo: %v", pr.ID, err) return false } - if unit, err := pr.BaseRepo.GetUnit(unit.TypePullRequests); err == nil { + if unit, err := pr.BaseRepo.GetUnit(ctx, unit.TypePullRequests); err == nil { config := unit.PullRequestsConfig() if !config.AutodetectManualMerge { return false @@ -278,7 +277,7 @@ func manuallyMerged(ctx context.Context, pr *issues_model.PullRequest) bool { return false } - notification.NotifyMergePullRequest(pr, merger) + notification.NotifyMergePullRequest(ctx, merger, pr) log.Info("manuallyMerged[%d]: Marked as manually merged into %s/%s by commit id: %s", pr.ID, pr.BaseRepo.Name, pr.BaseBranch, commit.ID.String()) return true @@ -346,7 +345,7 @@ func testPR(id int64) { } return } - checkAndUpdateStatus(pr) + checkAndUpdateStatus(ctx, pr) } // CheckPrsForBaseBranch check all pulls with bseBrannch diff --git a/services/pull/check_test.go b/services/pull/check_test.go index b4de02b5e2..590065250f 100644 --- a/services/pull/check_test.go +++ b/services/pull/check_test.go @@ -1,7 +1,6 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package pull diff --git a/services/pull/comment.go b/services/pull/comment.go new file mode 100644 index 0000000000..068aca6cd1 --- /dev/null +++ b/services/pull/comment.go @@ -0,0 +1,162 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package pull + +import ( + "context" + + issues_model "code.gitea.io/gitea/models/issues" + repo_model "code.gitea.io/gitea/models/repo" + user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/git" + "code.gitea.io/gitea/modules/json" + issue_service "code.gitea.io/gitea/services/issue" +) + +type commitBranchCheckItem struct { + Commit *git.Commit + Checked bool +} + +func commitBranchCheck(gitRepo *git.Repository, startCommit *git.Commit, endCommitID, baseBranch string, commitList map[string]*commitBranchCheckItem) error { + if startCommit.ID.String() == endCommitID { + return nil + } + + checkStack := make([]string, 0, 10) + checkStack = append(checkStack, startCommit.ID.String()) + + for len(checkStack) > 0 { + commitID := checkStack[0] + checkStack = checkStack[1:] + + item, ok := commitList[commitID] + if !ok { + continue + } + + if item.Commit.ID.String() == endCommitID { + continue + } + + if err := item.Commit.LoadBranchName(); err != nil { + return err + } + + if item.Commit.Branch == baseBranch { + continue + } + + if item.Checked { + continue + } + + item.Checked = true + + parentNum := item.Commit.ParentCount() + for i := 0; i < parentNum; i++ { + parentCommit, err := item.Commit.Parent(i) + if err != nil { + return err + } + checkStack = append(checkStack, parentCommit.ID.String()) + } + } + return nil +} + +// getCommitIDsFromRepo get commit IDs from repo in between oldCommitID and newCommitID +// isForcePush will be true if oldCommit isn't on the branch +// Commit on baseBranch will skip +func getCommitIDsFromRepo(ctx context.Context, repo *repo_model.Repository, oldCommitID, newCommitID, baseBranch string) (commitIDs []string, isForcePush bool, err error) { + repoPath := repo.RepoPath() + gitRepo, closer, err := git.RepositoryFromContextOrOpen(ctx, repoPath) + if err != nil { + return nil, false, err + } + defer closer.Close() + + oldCommit, err := gitRepo.GetCommit(oldCommitID) + if err != nil { + return nil, false, err + } + + if err = oldCommit.LoadBranchName(); err != nil { + return nil, false, err + } + + if len(oldCommit.Branch) == 0 { + commitIDs = make([]string, 2) + commitIDs[0] = oldCommitID + commitIDs[1] = newCommitID + + return commitIDs, true, err + } + + newCommit, err := gitRepo.GetCommit(newCommitID) + if err != nil { + return nil, false, err + } + + commits, err := newCommit.CommitsBeforeUntil(oldCommitID) + if err != nil { + return nil, false, err + } + + commitIDs = make([]string, 0, len(commits)) + commitChecks := make(map[string]*commitBranchCheckItem) + + for _, commit := range commits { + commitChecks[commit.ID.String()] = &commitBranchCheckItem{ + Commit: commit, + Checked: false, + } + } + + if err = commitBranchCheck(gitRepo, newCommit, oldCommitID, baseBranch, commitChecks); err != nil { + return + } + + for i := len(commits) - 1; i >= 0; i-- { + commitID := commits[i].ID.String() + if item, ok := commitChecks[commitID]; ok && item.Checked { + commitIDs = append(commitIDs, commitID) + } + } + + return commitIDs, isForcePush, err +} + +// CreatePushPullComment create push code to pull base comment +func CreatePushPullComment(ctx context.Context, pusher *user_model.User, pr *issues_model.PullRequest, oldCommitID, newCommitID string) (comment *issues_model.Comment, err error) { + if pr.HasMerged || oldCommitID == "" || newCommitID == "" { + return nil, nil + } + + ops := &issues_model.CreateCommentOptions{ + Type: issues_model.CommentTypePullRequestPush, + Doer: pusher, + Repo: pr.BaseRepo, + } + + var data issues_model.PushActionContent + + data.CommitIDs, data.IsForcePush, err = getCommitIDsFromRepo(ctx, pr.BaseRepo, oldCommitID, newCommitID, pr.BaseBranch) + if err != nil { + return nil, err + } + + ops.Issue = pr.Issue + + dataJSON, err := json.Marshal(data) + if err != nil { + return nil, err + } + + ops.Content = string(dataJSON) + + comment, err = issue_service.CreateComment(ops) + + return comment, err +} diff --git a/services/pull/commit_status.go b/services/pull/commit_status.go index 5d846129f6..e075248a36 100644 --- a/services/pull/commit_status.go +++ b/services/pull/commit_status.go @@ -1,7 +1,6 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package pull @@ -84,7 +83,7 @@ func IsCommitStatusContextSuccess(commitStatuses []*git_model.CommitStatus, requ // IsPullCommitStatusPass returns if all required status checks PASS func IsPullCommitStatusPass(ctx context.Context, pr *issues_model.PullRequest) (bool, error) { - if err := pr.LoadProtectedBranchCtx(ctx); err != nil { + if err := pr.LoadProtectedBranch(ctx); err != nil { return false, errors.Wrap(err, "GetLatestCommitStatus") } if pr.ProtectedBranch == nil || !pr.ProtectedBranch.EnableStatusCheck { @@ -101,7 +100,7 @@ func IsPullCommitStatusPass(ctx context.Context, pr *issues_model.PullRequest) ( // GetPullRequestCommitStatusState returns pull request merged commit status state func GetPullRequestCommitStatusState(ctx context.Context, pr *issues_model.PullRequest) (structs.CommitStatusState, error) { // Ensure HeadRepo is loaded - if err := pr.LoadHeadRepoCtx(ctx); err != nil { + if err := pr.LoadHeadRepo(ctx); err != nil { return "", errors.Wrap(err, "LoadHeadRepo") } @@ -129,7 +128,7 @@ func GetPullRequestCommitStatusState(ctx context.Context, pr *issues_model.PullR return "", err } - if err := pr.LoadBaseRepoCtx(ctx); err != nil { + if err := pr.LoadBaseRepo(ctx); err != nil { return "", errors.Wrap(err, "LoadBaseRepo") } @@ -138,7 +137,7 @@ func GetPullRequestCommitStatusState(ctx context.Context, pr *issues_model.PullR return "", errors.Wrap(err, "GetLatestCommitStatus") } - if err := pr.LoadProtectedBranchCtx(ctx); err != nil { + if err := pr.LoadProtectedBranch(ctx); err != nil { return "", errors.Wrap(err, "LoadProtectedBranch") } var requiredContexts []string diff --git a/services/pull/edits.go b/services/pull/edits.go index 2938f2b108..c7550dcb07 100644 --- a/services/pull/edits.go +++ b/services/pull/edits.go @@ -1,7 +1,6 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package pull @@ -23,7 +22,7 @@ func SetAllowEdits(ctx context.Context, doer *user_model.User, pr *issues_model. return ErrUserHasNoPermissionForAction } - if err := pr.LoadHeadRepo(); err != nil { + if err := pr.LoadHeadRepo(ctx); err != nil { return err } diff --git a/services/pull/lfs.go b/services/pull/lfs.go index 8cca0a91b7..4b9826bedd 100644 --- a/services/pull/lfs.go +++ b/services/pull/lfs.go @@ -1,7 +1,6 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package pull diff --git a/services/pull/main_test.go b/services/pull/main_test.go index 5471686e72..2014b19275 100644 --- a/services/pull/main_test.go +++ b/services/pull/main_test.go @@ -1,7 +1,6 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package pull diff --git a/services/pull/merge.go b/services/pull/merge.go index 56ee9c9a73..1c42c1c17b 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -1,7 +1,6 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package pull @@ -40,22 +39,22 @@ import ( ) // GetDefaultMergeMessage returns default message used when merging pull request -func GetDefaultMergeMessage(baseGitRepo *git.Repository, pr *issues_model.PullRequest, mergeStyle repo_model.MergeStyle) (string, error) { - if err := pr.LoadHeadRepo(); err != nil { +func GetDefaultMergeMessage(ctx context.Context, baseGitRepo *git.Repository, pr *issues_model.PullRequest, mergeStyle repo_model.MergeStyle) (string, error) { + if err := pr.LoadHeadRepo(ctx); err != nil { return "", err } - if err := pr.LoadBaseRepo(); err != nil { + if err := pr.LoadBaseRepo(ctx); err != nil { return "", err } if pr.BaseRepo == nil { return "", repo_model.ErrRepoNotExist{ID: pr.BaseRepoID} } - if err := pr.LoadIssue(); err != nil { + if err := pr.LoadIssue(ctx); err != nil { return "", err } - isExternalTracker := pr.BaseRepo.UnitEnabled(unit.TypeExternalTracker) + isExternalTracker := pr.BaseRepo.UnitEnabled(ctx, unit.TypeExternalTracker) issueReference := "#" if isExternalTracker { issueReference = "!" @@ -90,7 +89,7 @@ func GetDefaultMergeMessage(baseGitRepo *git.Repository, pr *issues_model.PullRe vars["HeadRepoOwnerName"] = pr.HeadRepo.OwnerName vars["HeadRepoName"] = pr.HeadRepo.Name } - refs, err := pr.ResolveCrossReferences(baseGitRepo.Ctx) + refs, err := pr.ResolveCrossReferences(ctx) if err == nil { closeIssueIndexes := make([]string, 0, len(refs)) closeWord := "close" @@ -134,10 +133,10 @@ func GetDefaultMergeMessage(baseGitRepo *git.Repository, pr *issues_model.PullRe // Merge merges pull request to base repository. // Caller should check PR is ready to be merged (review and status checks) func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.User, baseGitRepo *git.Repository, mergeStyle repo_model.MergeStyle, expectedHeadCommitID, message string, wasAutoMerged bool) error { - if err := pr.LoadHeadRepo(); err != nil { + if err := pr.LoadHeadRepo(ctx); err != nil { log.Error("LoadHeadRepo: %v", err) return fmt.Errorf("LoadHeadRepo: %w", err) - } else if err := pr.LoadBaseRepo(); err != nil { + } else if err := pr.LoadBaseRepo(ctx); err != nil { log.Error("LoadBaseRepo: %v", err) return fmt.Errorf("LoadBaseRepo: %w", err) } @@ -146,11 +145,11 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U defer pullWorkingPool.CheckOut(fmt.Sprint(pr.ID)) // Removing an auto merge pull and ignore if not exist - if err := pull_model.DeleteScheduledAutoMerge(db.DefaultContext, pr.ID); err != nil && !db.IsErrNotExist(err) { + if err := pull_model.DeleteScheduledAutoMerge(ctx, pr.ID); err != nil && !db.IsErrNotExist(err) { return err } - prUnit, err := pr.BaseRepo.GetUnit(unit.TypePullRequests) + prUnit, err := pr.BaseRepo.GetUnit(ctx, unit.TypePullRequests) if err != nil { log.Error("pr.BaseRepo.GetUnit(unit.TypePullRequests): %v", err) return err @@ -179,24 +178,24 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U pr.MergerID = doer.ID if _, err := pr.SetMerged(hammerCtx); err != nil { - log.Error("setMerged [%d]: %v", pr.ID, err) + log.Error("SetMerged [%d]: %v", pr.ID, err) } - if err := pr.LoadIssueCtx(hammerCtx); err != nil { - log.Error("loadIssue [%d]: %v", pr.ID, err) + if err := pr.LoadIssue(hammerCtx); err != nil { + log.Error("LoadIssue [%d]: %v", pr.ID, err) } if err := pr.Issue.LoadRepo(hammerCtx); err != nil { - log.Error("loadRepo for issue [%d]: %v", pr.ID, err) + log.Error("LoadRepo for issue [%d]: %v", pr.ID, err) } if err := pr.Issue.Repo.GetOwner(hammerCtx); err != nil { - log.Error("GetOwner for issue repo [%d]: %v", pr.ID, err) + log.Error("GetOwner for PR [%d]: %v", pr.ID, err) } if wasAutoMerged { - notification.NotifyAutoMergePullRequest(pr, doer) + notification.NotifyAutoMergePullRequest(hammerCtx, doer, pr) } else { - notification.NotifyMergePullRequest(pr, doer) + notification.NotifyMergePullRequest(hammerCtx, doer, pr) } // Reset cached commit count @@ -210,7 +209,7 @@ func Merge(ctx context.Context, pr *issues_model.PullRequest, doer *user_model.U } for _, ref := range refs { - if err = ref.LoadIssueCtx(hammerCtx); err != nil { + if err = ref.LoadIssue(hammerCtx); err != nil { return err } if err = ref.Issue.LoadRepo(hammerCtx); err != nil { @@ -511,7 +510,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode return "", err } - if err = pr.Issue.LoadPoster(); err != nil { + if err = pr.Issue.LoadPoster(ctx); err != nil { log.Error("LoadPoster: %v", err) return "", fmt.Errorf("LoadPoster: %w", err) } @@ -753,7 +752,7 @@ func IsUserAllowedToMerge(ctx context.Context, pr *issues_model.PullRequest, p a return false, nil } - err := pr.LoadProtectedBranchCtx(ctx) + err := pr.LoadProtectedBranch(ctx) if err != nil { return false, err } @@ -767,11 +766,11 @@ func IsUserAllowedToMerge(ctx context.Context, pr *issues_model.PullRequest, p a // CheckPullBranchProtections checks whether the PR is ready to be merged (reviews and status checks) func CheckPullBranchProtections(ctx context.Context, pr *issues_model.PullRequest, skipProtectedFilesCheck bool) (err error) { - if err = pr.LoadBaseRepoCtx(ctx); err != nil { + if err = pr.LoadBaseRepo(ctx); err != nil { return fmt.Errorf("LoadBaseRepo: %w", err) } - if err = pr.LoadProtectedBranchCtx(ctx); err != nil { + if err = pr.LoadProtectedBranch(ctx); err != nil { return fmt.Errorf("LoadProtectedBranch: %w", err) } if pr.ProtectedBranch == nil { @@ -828,8 +827,8 @@ func MergedManually(pr *issues_model.PullRequest, doer *user_model.User, baseGit pullWorkingPool.CheckIn(fmt.Sprint(pr.ID)) defer pullWorkingPool.CheckOut(fmt.Sprint(pr.ID)) - if err := db.WithTx(func(ctx context.Context) error { - prUnit, err := pr.BaseRepo.GetUnitCtx(ctx, unit.TypePullRequests) + if err := db.WithTx(db.DefaultContext, func(ctx context.Context) error { + prUnit, err := pr.BaseRepo.GetUnit(ctx, unit.TypePullRequests) if err != nil { return err } @@ -878,7 +877,7 @@ func MergedManually(pr *issues_model.PullRequest, doer *user_model.User, baseGit return err } - notification.NotifyMergePullRequest(pr, doer) + notification.NotifyMergePullRequest(baseGitRepo.Ctx, doer, pr) log.Info("manuallyMerged[%d]: Marked as manually merged into %s/%s by commit id: %s", pr.ID, pr.BaseRepo.Name, pr.BaseBranch, commitID) return nil } diff --git a/services/pull/patch.go b/services/pull/patch.go index 9b87ac22e2..e0da410c4d 100644 --- a/services/pull/patch.go +++ b/services/pull/patch.go @@ -1,7 +1,6 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package pull @@ -15,6 +14,7 @@ import ( "strings" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/modules/container" @@ -30,7 +30,7 @@ import ( // DownloadDiffOrPatch will write the patch for the pr to the writer func DownloadDiffOrPatch(ctx context.Context, pr *issues_model.PullRequest, w io.Writer, patch, binary bool) error { - if err := pr.LoadBaseRepoCtx(ctx); err != nil { + if err := pr.LoadBaseRepo(ctx); err != nil { log.Error("Unable to load base repository ID %d for pr #%d [%d]", pr.BaseRepoID, pr.Index, pr.ID) return err } @@ -53,6 +53,8 @@ var patchErrorSuffices = []string{ ": patch does not apply", ": already exists in working directory", "unrecognized input", + ": No such file or directory", + ": does not exist in index", } // TestPatch will test whether a simple patch will apply @@ -354,7 +356,7 @@ func checkConflicts(ctx context.Context, pr *issues_model.PullRequest, gitRepo * } // 5. Now get the pull request configuration to check if we need to ignore whitespace - prUnit, err := pr.BaseRepo.GetUnit(unit.TypePullRequests) + prUnit, err := pr.BaseRepo.GetUnit(ctx, unit.TypePullRequests) if err != nil { return false, err } @@ -416,6 +418,7 @@ func checkConflicts(ctx context.Context, pr *issues_model.PullRequest, gitRepo * scanner := bufio.NewScanner(stderrReader) for scanner.Scan() { line := scanner.Text() + log.Trace("PullRequest[%d].testPatch: stderr: %s", pr.ID, line) if strings.HasPrefix(line, prefix) { conflict = true filepath := strings.TrimSpace(strings.Split(line[len(prefix):], ":")[0]) @@ -534,7 +537,7 @@ func checkPullFilesProtection(pr *issues_model.PullRequest, gitRepo *git.Reposit return nil } - if err := pr.LoadProtectedBranch(); err != nil { + if err := pr.LoadProtectedBranch(db.DefaultContext); err != nil { return err } diff --git a/services/pull/patch_unmerged.go b/services/pull/patch_unmerged.go index 3f1bb7d523..c60c48d923 100644 --- a/services/pull/patch_unmerged.go +++ b/services/pull/patch_unmerged.go @@ -1,7 +1,6 @@ // 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. +// SPDX-License-Identifier: MIT package pull diff --git a/services/pull/pull.go b/services/pull/pull.go index 5f8bd6b671..afb0fa2442 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package pull @@ -82,12 +81,12 @@ func NewPullRequest(ctx context.Context, repo *repo_model.Repository, pull *issu return err } - notification.NotifyNewPullRequest(pr, mentions) + notification.NotifyNewPullRequest(prCtx, pr, mentions) if len(pull.Labels) > 0 { - notification.NotifyIssueChangeLabels(pull.Poster, pull, pull.Labels, nil) + notification.NotifyIssueChangeLabels(prCtx, pull.Poster, pull, pull.Labels, nil) } if pull.Milestone != nil { - notification.NotifyIssueChangeMilestone(pull.Poster, pull, 0) + notification.NotifyIssueChangeMilestone(prCtx, pull.Poster, pull, 0) } // add first push codes comment @@ -124,7 +123,7 @@ func NewPullRequest(ctx context.Context, repo *repo_model.Repository, pull *issu Content: string(dataJSON), } - _, _ = issues_model.CreateComment(ops) + _, _ = issue_service.CreateComment(ops) } return nil @@ -172,7 +171,7 @@ func ChangeTargetBranch(ctx context.Context, pr *issues_model.PullRequest, doer } // Check if pull request for the new target branch already exists - existingPr, err := issues_model.GetUnmergedPullRequest(pr.HeadRepoID, pr.BaseRepoID, pr.HeadBranch, targetBranch, issues_model.PullRequestFlowGithub) + existingPr, err := issues_model.GetUnmergedPullRequest(ctx, pr.HeadRepoID, pr.BaseRepoID, pr.HeadBranch, targetBranch, issues_model.PullRequestFlowGithub) if existingPr != nil { return issues_model.ErrPullRequestAlreadyExists{ ID: existingPr.ID, @@ -210,7 +209,7 @@ func ChangeTargetBranch(ctx context.Context, pr *issues_model.PullRequest, doer pr.CommitsAhead = divergence.Ahead pr.CommitsBehind = divergence.Behind - if err := pr.UpdateColsIfNotMerged("merge_base", "status", "conflicted_files", "changed_protected_files", "base_branch", "commits_ahead", "commits_behind"); err != nil { + if err := pr.UpdateColsIfNotMerged(ctx, "merge_base", "status", "conflicted_files", "changed_protected_files", "base_branch", "commits_ahead", "commits_behind"); err != nil { return err } @@ -223,7 +222,7 @@ func ChangeTargetBranch(ctx context.Context, pr *issues_model.PullRequest, doer OldRef: oldBranch, NewRef: targetBranch, } - if _, err = issues_model.CreateComment(options); err != nil { + if _, err = issue_service.CreateComment(options); err != nil { return fmt.Errorf("CreateChangeTargetBranchComment: %w", err) } @@ -231,9 +230,9 @@ func ChangeTargetBranch(ctx context.Context, pr *issues_model.PullRequest, doer } func checkForInvalidation(ctx context.Context, requests issues_model.PullRequestList, repoID int64, doer *user_model.User, branch string) error { - repo, err := repo_model.GetRepositoryByID(repoID) + repo, err := repo_model.GetRepositoryByID(ctx, repoID) if err != nil { - return fmt.Errorf("GetRepositoryByID: %w", err) + return fmt.Errorf("GetRepositoryByIDCtx: %w", err) } gitRepo, err := git.OpenRepository(ctx, repo.RepoPath()) if err != nil { @@ -301,7 +300,7 @@ func AddTestPullRequestTask(doer *user_model.User, repoID int64, branch string, } pr.Issue.PullRequest = pr - notification.NotifyPullRequestSynchronized(doer, pr) + notification.NotifyPullRequestSynchronized(ctx, doer, pr) } } } @@ -318,9 +317,9 @@ func AddTestPullRequestTask(doer *user_model.User, repoID int64, branch string, } AddToTaskQueue(pr) - comment, err := issues_model.CreatePushPullComment(ctx, doer, pr, oldCommitID, newCommitID) + comment, err := CreatePushPullComment(ctx, doer, pr, oldCommitID, newCommitID) if err == nil && comment != nil { - notification.NotifyPullRequestPushCommits(doer, pr, comment) + notification.NotifyPullRequestPushCommits(ctx, doer, pr, comment) } } @@ -352,14 +351,14 @@ func AddTestPullRequestTask(doer *user_model.User, repoID int64, branch string, // checkIfPRContentChanged checks if diff to target branch has changed by push // A commit can be considered to leave the PR untouched if the patch/diff with its merge base is unchanged func checkIfPRContentChanged(ctx context.Context, pr *issues_model.PullRequest, oldCommitID, newCommitID string) (hasChanged bool, err error) { - if err = pr.LoadHeadRepoCtx(ctx); err != nil { + if err = pr.LoadHeadRepo(ctx); err != nil { return false, fmt.Errorf("LoadHeadRepo: %w", err) } else if pr.HeadRepo == nil { // corrupt data assumed changed return true, nil } - if err = pr.LoadBaseRepoCtx(ctx); err != nil { + if err = pr.LoadBaseRepo(ctx); err != nil { return false, fmt.Errorf("LoadBaseRepo: %w", err) } @@ -430,22 +429,22 @@ func PushToBaseRepo(ctx context.Context, pr *issues_model.PullRequest) (err erro func pushToBaseRepoHelper(ctx context.Context, pr *issues_model.PullRequest, prefixHeadBranch string) (err error) { log.Trace("PushToBaseRepo[%d]: pushing commits to base repo '%s'", pr.BaseRepoID, pr.GetGitRefName()) - if err := pr.LoadHeadRepoCtx(ctx); err != nil { + if err := pr.LoadHeadRepo(ctx); err != nil { log.Error("Unable to load head repository for PR[%d] Error: %v", pr.ID, err) return err } headRepoPath := pr.HeadRepo.RepoPath() - if err := pr.LoadBaseRepoCtx(ctx); err != nil { + if err := pr.LoadBaseRepo(ctx); err != nil { log.Error("Unable to load base repository for PR[%d] Error: %v", pr.ID, err) return err } baseRepoPath := pr.BaseRepo.RepoPath() - if err = pr.LoadIssue(); err != nil { + if err = pr.LoadIssue(ctx); err != nil { return fmt.Errorf("unable to load issue %d for pr %d: %w", pr.IssueID, pr.ID, err) } - if err = pr.Issue.LoadPoster(); err != nil { + if err = pr.Issue.LoadPoster(ctx); err != nil { return fmt.Errorf("unable to load poster %d for pr %d: %w", pr.Issue.PosterID, pr.ID, err) } @@ -485,7 +484,7 @@ func pushToBaseRepoHelper(ctx context.Context, pr *issues_model.PullRequest, pre // UpdateRef update refs/pull/id/head directly for agit flow pull request func UpdateRef(ctx context.Context, pr *issues_model.PullRequest) (err error) { log.Trace("UpdateRef[%d]: upgate pull request ref in base repo '%s'", pr.ID, pr.GetGitRefName()) - if err := pr.LoadBaseRepoCtx(ctx); err != nil { + if err := pr.LoadBaseRepo(ctx); err != nil { log.Error("Unable to load base repository for PR[%d] Error: %v", pr.ID, err) return err } @@ -583,21 +582,21 @@ var commitMessageTrailersPattern = regexp.MustCompile(`(?:^|\n\n)(?:[\w-]+[ \t]* // GetSquashMergeCommitMessages returns the commit messages between head and merge base (if there is one) func GetSquashMergeCommitMessages(ctx context.Context, pr *issues_model.PullRequest) string { - if err := pr.LoadIssue(); err != nil { + if err := pr.LoadIssue(ctx); err != nil { log.Error("Cannot load issue %d for PR id %d: Error: %v", pr.IssueID, pr.ID, err) return "" } - if err := pr.Issue.LoadPoster(); err != nil { + if err := pr.Issue.LoadPoster(ctx); err != nil { log.Error("Cannot load poster %d for pr id %d, index %d Error: %v", pr.Issue.PosterID, pr.ID, pr.Index, err) return "" } if pr.HeadRepo == nil { var err error - pr.HeadRepo, err = repo_model.GetRepositoryByID(pr.HeadRepoID) + pr.HeadRepo, err = repo_model.GetRepositoryByID(ctx, pr.HeadRepoID) if err != nil { - log.Error("GetRepositoryById[%d]: %v", pr.HeadRepoID, err) + log.Error("GetRepositoryByIdCtx[%d]: %v", pr.HeadRepoID, err) return "" } } @@ -743,10 +742,10 @@ func GetIssuesLastCommitStatus(ctx context.Context, issues issues_model.IssueLis // GetIssuesAllCommitStatus returns a map of issue ID to a list of all statuses for the most recent commit as well as a map of issue ID to only the commit's latest status func GetIssuesAllCommitStatus(ctx context.Context, issues issues_model.IssueList) (map[int64][]*git_model.CommitStatus, map[int64]*git_model.CommitStatus, error) { - if err := issues.LoadPullRequests(); err != nil { + if err := issues.LoadPullRequests(ctx); err != nil { return nil, nil, err } - if _, err := issues.LoadRepositories(); err != nil { + if _, err := issues.LoadRepositories(ctx); err != nil { return nil, nil, err } @@ -802,7 +801,7 @@ func getAllCommitStatus(gitRepo *git.Repository, pr *issues_model.PullRequest) ( // IsHeadEqualWithBranch returns if the commits of branchName are available in pull request head func IsHeadEqualWithBranch(ctx context.Context, pr *issues_model.PullRequest, branchName string) (bool, error) { var err error - if err = pr.LoadBaseRepoCtx(ctx); err != nil { + if err = pr.LoadBaseRepo(ctx); err != nil { return false, err } baseGitRepo, closer, err := git.RepositoryFromContextOrOpen(ctx, pr.BaseRepo.RepoPath()) @@ -816,7 +815,7 @@ func IsHeadEqualWithBranch(ctx context.Context, pr *issues_model.PullRequest, br return false, err } - if err = pr.LoadHeadRepoCtx(ctx); err != nil { + if err = pr.LoadHeadRepo(ctx); err != nil { return false, err } var headGitRepo *git.Repository diff --git a/services/pull/pull_test.go b/services/pull/pull_test.go index 769e3c72e9..cbbdccce9c 100644 --- a/services/pull/pull_test.go +++ b/services/pull/pull_test.go @@ -1,13 +1,13 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package pull import ( "testing" + "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" @@ -40,18 +40,18 @@ func TestPullRequest_GetDefaultMergeMessage_InternalTracker(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) - assert.NoError(t, pr.LoadBaseRepo()) + assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) gitRepo, err := git.OpenRepository(git.DefaultContext, pr.BaseRepo.RepoPath()) assert.NoError(t, err) defer gitRepo.Close() - mergeMessage, err := GetDefaultMergeMessage(gitRepo, pr, "") + mergeMessage, err := GetDefaultMergeMessage(db.DefaultContext, gitRepo, pr, "") assert.NoError(t, err) assert.Equal(t, "Merge pull request 'issue3' (#3) from branch2 into master", mergeMessage) pr.BaseRepoID = 1 pr.HeadRepoID = 2 - mergeMessage, err = GetDefaultMergeMessage(gitRepo, pr, "") + mergeMessage, err = GetDefaultMergeMessage(db.DefaultContext, gitRepo, pr, "") assert.NoError(t, err) assert.Equal(t, "Merge pull request 'issue3' (#3) from user2/repo1:branch2 into master", mergeMessage) } @@ -70,12 +70,12 @@ func TestPullRequest_GetDefaultMergeMessage_ExternalTracker(t *testing.T) { pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2, BaseRepo: baseRepo}) - assert.NoError(t, pr.LoadBaseRepo()) + assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) gitRepo, err := git.OpenRepository(git.DefaultContext, pr.BaseRepo.RepoPath()) assert.NoError(t, err) defer gitRepo.Close() - mergeMessage, err := GetDefaultMergeMessage(gitRepo, pr, "") + mergeMessage, err := GetDefaultMergeMessage(db.DefaultContext, gitRepo, pr, "") assert.NoError(t, err) assert.Equal(t, "Merge pull request 'issue3' (!3) from branch2 into master", mergeMessage) @@ -84,7 +84,7 @@ func TestPullRequest_GetDefaultMergeMessage_ExternalTracker(t *testing.T) { pr.HeadRepoID = 2 pr.BaseRepo = nil pr.HeadRepo = nil - mergeMessage, err = GetDefaultMergeMessage(gitRepo, pr, "") + mergeMessage, err = GetDefaultMergeMessage(db.DefaultContext, gitRepo, pr, "") assert.NoError(t, err) assert.Equal(t, "Merge pull request 'issue3' (#3) from user2/repo2:branch2 into master", mergeMessage) diff --git a/services/pull/review.go b/services/pull/review.go index 16c9e108ee..67a10d7aad 100644 --- a/services/pull/review.go +++ b/services/pull/review.go @@ -1,7 +1,6 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package pull @@ -21,6 +20,7 @@ import ( "code.gitea.io/gitea/modules/notification" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/util" + issue_service "code.gitea.io/gitea/services/issue" ) // CreateCodeComment creates a comment on the code line @@ -67,7 +67,7 @@ func CreateCodeComment(ctx context.Context, doer *user_model.User, gitRepo *git. return nil, err } - notification.NotifyCreateIssueComment(doer, issue.Repo, issue, comment, mentions) + notification.NotifyCreateIssueComment(ctx, doer, issue.Repo, issue, comment, mentions) return comment, nil } @@ -119,12 +119,12 @@ var notEnoughLines = regexp.MustCompile(`exit status 128 - fatal: file .* has on // createCodeComment creates a plain code comment at the specified line / path func createCodeComment(ctx context.Context, doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, content, treePath string, line, reviewID int64) (*issues_model.Comment, error) { var commitID, patch string - if err := issue.LoadPullRequest(); err != nil { - return nil, fmt.Errorf("GetPullRequestByIssueID: %w", err) + if err := issue.LoadPullRequest(ctx); err != nil { + return nil, fmt.Errorf("LoadPullRequest: %w", err) } pr := issue.PullRequest - if err := pr.LoadBaseRepoCtx(ctx); err != nil { - return nil, fmt.Errorf("LoadHeadRepo: %w", err) + if err := pr.LoadBaseRepo(ctx); err != nil { + return nil, fmt.Errorf("LoadBaseRepo: %w", err) } gitRepo, closer, err := git.RepositoryFromContextOrOpen(ctx, pr.BaseRepo.RepoPath()) if err != nil { @@ -203,7 +203,7 @@ func createCodeComment(ctx context.Context, doer *user_model.User, repo *repo_mo return nil, err } } - return issues_model.CreateComment(&issues_model.CreateCommentOptions{ + return issue_service.CreateComment(&issues_model.CreateCommentOptions{ Type: issues_model.CommentTypeCode, Doer: doer, Repo: repo, @@ -254,7 +254,7 @@ func SubmitReview(ctx context.Context, doer *user_model.User, gitRepo *git.Repos return nil, nil, err } - notification.NotifyPullRequestReview(pr, review, comm, mentions) + notification.NotifyPullRequestReview(ctx, pr, review, comm, mentions) for _, lines := range review.CodeComments { for _, comments := range lines { @@ -263,7 +263,7 @@ func SubmitReview(ctx context.Context, doer *user_model.User, gitRepo *git.Repos if err != nil { return nil, nil, err } - notification.NotifyPullRequestCodeComment(pr, codeComment, mentions) + notification.NotifyPullRequestCodeComment(ctx, pr, codeComment, mentions) } } } @@ -316,14 +316,14 @@ func DismissReview(ctx context.Context, reviewID, repoID int64, message string, return nil, nil } - if err = review.Issue.LoadPullRequest(); err != nil { + if err = review.Issue.LoadPullRequest(ctx); err != nil { return } if err = review.Issue.LoadAttributes(ctx); err != nil { return } - comment, err = issues_model.CreateComment(&issues_model.CreateCommentOptions{ + comment, err = issue_service.CreateComment(&issues_model.CreateCommentOptions{ Doer: doer, Content: message, Type: issues_model.CommentTypeDismissReview, @@ -339,7 +339,7 @@ func DismissReview(ctx context.Context, reviewID, repoID int64, message string, comment.Poster = doer comment.Issue = review.Issue - notification.NotifyPullRevieweDismiss(doer, review, comment) + notification.NotifyPullReviewDismiss(ctx, doer, review, comment) return comment, err } diff --git a/services/pull/temp_repo.go b/services/pull/temp_repo.go index 15e776c4b9..842719467f 100644 --- a/services/pull/temp_repo.go +++ b/services/pull/temp_repo.go @@ -1,7 +1,6 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package pull @@ -23,7 +22,7 @@ import ( // createTemporaryRepo creates a temporary repo with "base" for pr.BaseBranch and "tracking" for pr.HeadBranch // it also create a second base branch called "original_base" func createTemporaryRepo(ctx context.Context, pr *issues_model.PullRequest) (string, error) { - if err := pr.LoadHeadRepoCtx(ctx); err != nil { + if err := pr.LoadHeadRepo(ctx); err != nil { log.Error("LoadHeadRepo: %v", err) return "", fmt.Errorf("LoadHeadRepo: %w", err) } else if pr.HeadRepo == nil { @@ -31,7 +30,7 @@ func createTemporaryRepo(ctx context.Context, pr *issues_model.PullRequest) (str return "", &repo_model.ErrRepoNotExist{ ID: pr.HeadRepoID, } - } else if err := pr.LoadBaseRepoCtx(ctx); err != nil { + } else if err := pr.LoadBaseRepo(ctx); err != nil { log.Error("LoadBaseRepo: %v", err) return "", fmt.Errorf("LoadBaseRepo: %w", err) } else if pr.BaseRepo == nil { diff --git a/services/pull/update.go b/services/pull/update.go index bd4880a2fc..e09dbf6244 100644 --- a/services/pull/update.go +++ b/services/pull/update.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package pull @@ -48,10 +47,10 @@ func Update(ctx context.Context, pull *issues_model.PullRequest, doer *user_mode return fmt.Errorf("Not support update agit flow pull request's head branch") } - if err := pr.LoadHeadRepoCtx(ctx); err != nil { + if err := pr.LoadHeadRepo(ctx); err != nil { log.Error("LoadHeadRepo: %v", err) return fmt.Errorf("LoadHeadRepo: %w", err) - } else if err = pr.LoadBaseRepoCtx(ctx); err != nil { + } else if err = pr.LoadBaseRepo(ctx); err != nil { log.Error("LoadBaseRepo: %v", err) return fmt.Errorf("LoadBaseRepo: %w", err) } @@ -100,14 +99,14 @@ func IsUserAllowedToUpdate(ctx context.Context, pull *issues_model.PullRequest, BaseBranch: pull.HeadBranch, } - err = pr.LoadProtectedBranch() + err = pr.LoadProtectedBranch(ctx) if err != nil { return false, false, err } // can't do rebase on protected branch because need force push if pr.ProtectedBranch == nil { - prUnit, err := pr.BaseRepo.GetUnit(unit.TypePullRequests) + prUnit, err := pr.BaseRepo.GetUnit(ctx, unit.TypePullRequests) if err != nil { log.Error("pr.BaseRepo.GetUnit(unit.TypePullRequests): %v", err) return false, false, err @@ -145,10 +144,10 @@ func IsUserAllowedToUpdate(ctx context.Context, pull *issues_model.PullRequest, // GetDiverging determines how many commits a PR is ahead or behind the PR base branch func GetDiverging(ctx context.Context, pr *issues_model.PullRequest) (*git.DivergeObject, error) { log.Trace("GetDiverging[%d]: compare commits", pr.ID) - if err := pr.LoadBaseRepoCtx(ctx); err != nil { + if err := pr.LoadBaseRepo(ctx); err != nil { return nil, err } - if err := pr.LoadHeadRepoCtx(ctx); err != nil { + if err := pr.LoadHeadRepo(ctx); err != nil { return nil, err } diff --git a/services/release/release.go b/services/release/release.go index 8ccc222fb2..13042cd3ac 100644 --- a/services/release/release.go +++ b/services/release/release.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package release @@ -22,26 +21,27 @@ import ( "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/storage" "code.gitea.io/gitea/modules/timeutil" + "code.gitea.io/gitea/modules/util" ) -func createTag(gitRepo *git.Repository, rel *repo_model.Release, msg string) (bool, error) { +func createTag(ctx context.Context, gitRepo *git.Repository, rel *repo_model.Release, msg string) (bool, error) { var created bool // Only actual create when publish. if !rel.IsDraft { if !gitRepo.IsTagExist(rel.TagName) { - if err := rel.LoadAttributes(); err != nil { + if err := rel.LoadAttributes(ctx); err != nil { log.Error("LoadAttributes: %v", err) return false, err } - protectedTags, err := git_model.GetProtectedTags(rel.Repo.ID) + protectedTags, err := git_model.GetProtectedTags(ctx, rel.Repo.ID) if err != nil { return false, fmt.Errorf("GetProtectedTags: %w", err) } // Trim '--' prefix to prevent command line argument vulnerability. rel.TagName = strings.TrimPrefix(rel.TagName, "--") - isAllowed, err := git_model.IsUserAllowedToControlTag(protectedTags, rel.TagName, rel.PublisherID) + isAllowed, err := git_model.IsUserAllowedToControlTag(ctx, protectedTags, rel.TagName, rel.PublisherID) if err != nil { return false, err } @@ -81,13 +81,13 @@ func createTag(gitRepo *git.Repository, rel *repo_model.Release, msg string) (bo commits.CompareURL = rel.Repo.ComposeCompareURL(git.EmptySHA, commit.ID.String()) notification.NotifyPushCommits( - rel.Publisher, rel.Repo, + ctx, rel.Publisher, rel.Repo, &repository.PushUpdateOptions{ RefFullName: git.TagPrefix + rel.TagName, OldCommitID: git.EmptySHA, NewCommitID: commit.ID.String(), }, commits) - notification.NotifyCreateRef(rel.Publisher, rel.Repo, "tag", git.TagPrefix+rel.TagName, commit.ID.String()) + notification.NotifyCreateRef(ctx, rel.Publisher, rel.Repo, "tag", git.TagPrefix+rel.TagName, commit.ID.String()) rel.CreatedUnix = timeutil.TimeStampNow() } commit, err := gitRepo.GetTagCommit(rel.TagName) @@ -102,7 +102,7 @@ func createTag(gitRepo *git.Repository, rel *repo_model.Release, msg string) (bo } if rel.PublisherID <= 0 { - u, err := user_model.GetUserByEmail(commit.Author.Email) + u, err := user_model.GetUserByEmailContext(ctx, commit.Author.Email) if err == nil { rel.PublisherID = u.ID } @@ -124,7 +124,7 @@ func CreateRelease(gitRepo *git.Repository, rel *repo_model.Release, attachmentU } } - if _, err = createTag(gitRepo, rel, msg); err != nil { + if _, err = createTag(gitRepo.Ctx, gitRepo, rel, msg); err != nil { return err } @@ -138,7 +138,7 @@ func CreateRelease(gitRepo *git.Repository, rel *repo_model.Release, attachmentU } if !rel.IsDraft { - notification.NotifyNewRelease(rel) + notification.NotifyNewRelease(gitRepo.Ctx, rel) } return nil @@ -173,7 +173,7 @@ func CreateNewTag(ctx context.Context, doer *user_model.User, repo *repo_model.R IsTag: true, } - if _, err = createTag(gitRepo, rel, msg); err != nil { + if _, err = createTag(ctx, gitRepo, rel, msg); err != nil { return err } @@ -190,13 +190,13 @@ func UpdateRelease(doer *user_model.User, gitRepo *git.Repository, rel *repo_mod if rel.ID == 0 { return errors.New("UpdateRelease only accepts an exist release") } - isCreated, err := createTag(gitRepo, rel, "") + isCreated, err := createTag(gitRepo.Ctx, gitRepo, rel, "") if err != nil { return err } rel.LowerTagName = strings.ToLower(rel.TagName) - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -219,7 +219,10 @@ func UpdateRelease(doer *user_model.User, gitRepo *git.Repository, rel *repo_mod } for _, attach := range attachments { if attach.ReleaseID != rel.ID { - return errors.New("delete attachement of release permission denied") + return util.SilentWrap{ + Message: "delete attachment of release permission denied", + Err: util.ErrPermissionDenied, + } } deletedUUIDs.Add(attach.UUID) } @@ -241,7 +244,10 @@ func UpdateRelease(doer *user_model.User, gitRepo *git.Repository, rel *repo_mod } for _, attach := range attachments { if attach.ReleaseID != rel.ID { - return errors.New("update attachement of release permission denied") + return util.SilentWrap{ + Message: "update attachment of release permission denied", + Err: util.ErrPermissionDenied, + } } } @@ -272,12 +278,12 @@ func UpdateRelease(doer *user_model.User, gitRepo *git.Repository, rel *repo_mod } if !isCreated { - notification.NotifyUpdateRelease(doer, rel) + notification.NotifyUpdateRelease(gitRepo.Ctx, doer, rel) return } if !rel.IsDraft { - notification.NotifyNewRelease(rel) + notification.NotifyNewRelease(gitRepo.Ctx, rel) } return err @@ -290,17 +296,17 @@ func DeleteReleaseByID(ctx context.Context, id int64, doer *user_model.User, del return fmt.Errorf("GetReleaseByID: %w", err) } - repo, err := repo_model.GetRepositoryByIDCtx(ctx, rel.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, rel.RepoID) if err != nil { return fmt.Errorf("GetRepositoryByID: %w", err) } if delTag { - protectedTags, err := git_model.GetProtectedTags(rel.RepoID) + protectedTags, err := git_model.GetProtectedTags(ctx, rel.RepoID) if err != nil { return fmt.Errorf("GetProtectedTags: %w", err) } - isAllowed, err := git_model.IsUserAllowedToControlTag(protectedTags, rel.TagName, rel.PublisherID) + isAllowed, err := git_model.IsUserAllowedToControlTag(ctx, protectedTags, rel.TagName, rel.PublisherID) if err != nil { return err } @@ -318,15 +324,15 @@ func DeleteReleaseByID(ctx context.Context, id int64, doer *user_model.User, del } notification.NotifyPushCommits( - doer, repo, + ctx, doer, repo, &repository.PushUpdateOptions{ RefFullName: git.TagPrefix + rel.TagName, OldCommitID: rel.Sha1, NewCommitID: git.EmptySHA, }, repository.NewPushCommits()) - notification.NotifyDeleteRef(doer, repo, "tag", git.TagPrefix+rel.TagName) + notification.NotifyDeleteRef(ctx, doer, repo, "tag", git.TagPrefix+rel.TagName) - if err := repo_model.DeleteReleaseByID(id); err != nil { + if err := repo_model.DeleteReleaseByID(ctx, id); err != nil { return fmt.Errorf("DeleteReleaseByID: %w", err) } } else { @@ -338,11 +344,11 @@ func DeleteReleaseByID(ctx context.Context, id int64, doer *user_model.User, del } rel.Repo = repo - if err = rel.LoadAttributes(); err != nil { + if err = rel.LoadAttributes(ctx); err != nil { return fmt.Errorf("LoadAttributes: %w", err) } - if err := repo_model.DeleteAttachmentsByRelease(rel.ID); err != nil { + if err := repo_model.DeleteAttachmentsByRelease(ctx, rel.ID); err != nil { return fmt.Errorf("DeleteAttachments: %w", err) } @@ -353,7 +359,7 @@ func DeleteReleaseByID(ctx context.Context, id int64, doer *user_model.User, del } } - notification.NotifyDeleteRelease(doer, rel) + notification.NotifyDeleteRelease(ctx, doer, rel) return nil } diff --git a/services/release/release_test.go b/services/release/release_test.go index c0cafb5fcc..9b8aaa3649 100644 --- a/services/release/release_test.go +++ b/services/release/release_test.go @@ -1,6 +1,5 @@ // Copyright 2018 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. +// SPDX-License-Identifier: MIT package release @@ -297,13 +296,13 @@ func TestRelease_createTag(t *testing.T) { IsPrerelease: false, IsTag: false, } - _, err = createTag(gitRepo, release, "") + _, err = createTag(db.DefaultContext, gitRepo, release, "") assert.NoError(t, err) assert.NotEmpty(t, release.CreatedUnix) releaseCreatedUnix := release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Note = "Changed note" - _, err = createTag(gitRepo, release, "") + _, err = createTag(db.DefaultContext, gitRepo, release, "") assert.NoError(t, err) assert.Equal(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) @@ -321,12 +320,12 @@ func TestRelease_createTag(t *testing.T) { IsPrerelease: false, IsTag: false, } - _, err = createTag(gitRepo, release, "") + _, err = createTag(db.DefaultContext, gitRepo, release, "") assert.NoError(t, err) releaseCreatedUnix = release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Title = "Changed title" - _, err = createTag(gitRepo, release, "") + _, err = createTag(db.DefaultContext, gitRepo, release, "") assert.NoError(t, err) assert.Less(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) @@ -344,13 +343,13 @@ func TestRelease_createTag(t *testing.T) { IsPrerelease: true, IsTag: false, } - _, err = createTag(gitRepo, release, "") + _, err = createTag(db.DefaultContext, gitRepo, release, "") assert.NoError(t, err) releaseCreatedUnix = release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Title = "Changed title" release.Note = "Changed note" - _, err = createTag(gitRepo, release, "") + _, err = createTag(db.DefaultContext, gitRepo, release, "") assert.NoError(t, err) assert.Equal(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) } diff --git a/services/repository/adopt.go b/services/repository/adopt.go index a9a0639548..93eeb56456 100644 --- a/services/repository/adopt.go +++ b/services/repository/adopt.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repository @@ -54,7 +53,7 @@ func AdoptRepository(doer, u *user_model.User, opts repo_module.CreateRepoOption IsEmpty: !opts.AutoInit, } - if err := db.WithTx(func(ctx context.Context) error { + if err := db.WithTx(db.DefaultContext, func(ctx context.Context) error { repoPath := repo_model.RepoPath(u.Name, repo.Name) isExist, err := util.IsExist(repoPath) if err != nil { @@ -96,7 +95,7 @@ func AdoptRepository(doer, u *user_model.User, opts repo_module.CreateRepoOption return nil, err } - notification.NotifyCreateRepository(doer, u, repo) + notification.NotifyCreateRepository(db.DefaultContext, doer, u, repo) return repo, nil } @@ -117,7 +116,7 @@ func adoptRepository(ctx context.Context, repoPath string, u *user_model.User, r // Re-fetch the repository from database before updating it (else it would // override changes that were done earlier with sql) - if repo, err = repo_model.GetRepositoryByIDCtx(ctx, repo.ID); err != nil { + if repo, err = repo_model.GetRepositoryByID(ctx, repo.ID); err != nil { return fmt.Errorf("getRepositoryByID: %w", err) } @@ -338,7 +337,7 @@ func ListUnadoptedRepositories(query string, opts *db.ListOptions) ([]string, in } repoNamesToCheck = append(repoNamesToCheck, name) - if len(repoNamesToCheck) > setting.Database.IterateBufferSize { + if len(repoNamesToCheck) >= setting.Database.IterateBufferSize { if err = checkUnadoptedRepositories(userName, repoNamesToCheck, unadopted); err != nil { return err } diff --git a/services/repository/adopt_test.go b/services/repository/adopt_test.go index b450005f34..be8897693e 100644 --- a/services/repository/adopt_test.go +++ b/services/repository/adopt_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repository diff --git a/services/repository/archiver/archiver.go b/services/repository/archiver/archiver.go index 79537ea051..1da4425cfc 100644 --- a/services/repository/archiver/archiver.go +++ b/services/repository/archiver/archiver.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package archiver @@ -174,7 +173,7 @@ func (aReq *ArchiveRequest) Await(ctx context.Context) (*repo_model.RepoArchiver } func doArchive(r *ArchiveRequest) (*repo_model.RepoArchiver, error) { - txCtx, committer, err := db.TxContext() + txCtx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return nil, err } @@ -227,7 +226,7 @@ func doArchive(r *ArchiveRequest) (*repo_model.RepoArchiver, error) { rd.Close() }() done := make(chan error, 1) // Ensure that there is some capacity which will ensure that the goroutine below can always finish - repo, err := repo_model.GetRepositoryByID(archiver.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, archiver.RepoID) if err != nil { return nil, fmt.Errorf("archiver.LoadRepo failed: %w", err) } diff --git a/services/repository/archiver/archiver_test.go b/services/repository/archiver/archiver_test.go index 24437ce76c..3cd6e81351 100644 --- a/services/repository/archiver/archiver_test.go +++ b/services/repository/archiver/archiver_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package archiver diff --git a/services/repository/avatar.go b/services/repository/avatar.go index 1cf9e869c0..a829a1000a 100644 --- a/services/repository/avatar.go +++ b/services/repository/avatar.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repository @@ -33,7 +32,7 @@ func UploadAvatar(repo *repo_model.Repository, data []byte) error { return nil } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -76,7 +75,7 @@ func DeleteAvatar(repo *repo_model.Repository) error { avatarPath := repo.CustomAvatarRelativePath() log.Trace("DeleteAvatar[%d]: %s", repo.ID, avatarPath) - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } diff --git a/services/repository/avatar_test.go b/services/repository/avatar_test.go index e5d9ac9d53..3875302696 100644 --- a/services/repository/avatar_test.go +++ b/services/repository/avatar_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repository diff --git a/services/repository/branch.go b/services/repository/branch.go index 1328422582..e5ffbbeb74 100644 --- a/services/repository/branch.go +++ b/services/repository/branch.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repository @@ -11,6 +10,7 @@ import ( "strings" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" @@ -141,8 +141,8 @@ func RenameBranch(repo *repo_model.Repository, doer *user_model.User, gitRepo *g return "", err } - notification.NotifyDeleteRef(doer, repo, "branch", git.BranchPrefix+from) - notification.NotifyCreateRef(doer, repo, "branch", git.BranchPrefix+to, refID) + notification.NotifyDeleteRef(db.DefaultContext, doer, repo, "branch", git.BranchPrefix+from) + notification.NotifyCreateRef(db.DefaultContext, doer, repo, "branch", git.BranchPrefix+to, refID) return "", nil } diff --git a/services/repository/cache.go b/services/repository/cache.go index 855fe7f4a0..6fd4fa7250 100644 --- a/services/repository/cache.go +++ b/services/repository/cache.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repository diff --git a/services/repository/check.go b/services/repository/check.go index 5725f540b0..293cb04d38 100644 --- a/services/repository/check.go +++ b/services/repository/check.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repository @@ -23,8 +22,8 @@ import ( "xorm.io/builder" ) -// GitFsck calls 'git fsck' to check repository health. -func GitFsck(ctx context.Context, timeout time.Duration, args []git.CmdArg) error { +// GitFsckRepos calls 'git fsck' to check repository health. +func GitFsckRepos(ctx context.Context, timeout time.Duration, args []git.CmdArg) error { log.Trace("Doing: GitFsck") if err := db.Iterate( @@ -36,15 +35,7 @@ func GitFsck(ctx context.Context, timeout time.Duration, args []git.CmdArg) erro return db.ErrCancelledf("before fsck of %s", repo.FullName()) default: } - log.Trace("Running health check on repository %v", repo) - repoPath := repo.RepoPath() - if err := git.Fsck(ctx, repoPath, timeout, args...); err != nil { - log.Warn("Failed to health check repository (%v): %v", repo, err) - if err = system_model.CreateRepositoryNotice("Failed to health check repository (%s): %v", repo.FullName(), err); err != nil { - log.Error("CreateRepositoryNotice: %v", err) - } - } - return nil + return GitFsckRepo(ctx, repo, timeout, args) }, ); err != nil { log.Trace("Error: GitFsck: %v", err) @@ -55,6 +46,19 @@ func GitFsck(ctx context.Context, timeout time.Duration, args []git.CmdArg) erro return nil } +// GitFsckRepo calls 'git fsck' to check an individual repository's health. +func GitFsckRepo(ctx context.Context, repo *repo_model.Repository, timeout time.Duration, args []git.CmdArg) error { + log.Trace("Running health check on repository %-v", repo) + repoPath := repo.RepoPath() + if err := git.Fsck(ctx, repoPath, timeout, args...); err != nil { + log.Warn("Failed to health check repository (%-v): %v", repo, err) + if err = system_model.CreateRepositoryNotice("Failed to health check repository (%s): %v", repo.FullName(), err); err != nil { + log.Error("CreateRepositoryNotice: %v", err) + } + } + return nil +} + // GitGcRepos calls 'git gc' to remove unnecessary files and optimize the local repository func GitGcRepos(ctx context.Context, timeout time.Duration, args ...git.CmdArg) error { log.Trace("Doing: GitGcRepos") @@ -69,33 +73,7 @@ func GitGcRepos(ctx context.Context, timeout time.Duration, args ...git.CmdArg) return db.ErrCancelledf("before GC of %s", repo.FullName()) default: } - log.Trace("Running git gc on %v", repo) - command := git.NewCommand(ctx, args...). - SetDescription(fmt.Sprintf("Repository Garbage Collection: %s", repo.FullName())) - var stdout string - var err error - stdout, _, err = command.RunStdString(&git.RunOpts{Timeout: timeout, Dir: repo.RepoPath()}) - - if err != nil { - log.Error("Repository garbage collection failed for %v. Stdout: %s\nError: %v", repo, stdout, err) - desc := fmt.Sprintf("Repository garbage collection failed for %s. Stdout: %s\nError: %v", repo.RepoPath(), stdout, err) - if err = system_model.CreateRepositoryNotice(desc); err != nil { - log.Error("CreateRepositoryNotice: %v", err) - } - return fmt.Errorf("Repository garbage collection failed in repo: %s: Error: %w", repo.FullName(), err) - } - - // Now update the size of the repository - if err := repo_module.UpdateRepoSize(ctx, repo); err != nil { - log.Error("Updating size as part of garbage collection failed for %v. Stdout: %s\nError: %v", repo, stdout, err) - desc := fmt.Sprintf("Updating size as part of garbage collection failed for %s. Stdout: %s\nError: %v", repo.RepoPath(), stdout, err) - if err = system_model.CreateRepositoryNotice(desc); err != nil { - log.Error("CreateRepositoryNotice: %v", err) - } - return fmt.Errorf("Updating size as part of garbage collection failed in repo: %s: Error: %w", repo.FullName(), err) - } - - return nil + return GitGcRepo(ctx, repo, timeout, args) }, ); err != nil { return err @@ -105,6 +83,37 @@ func GitGcRepos(ctx context.Context, timeout time.Duration, args ...git.CmdArg) return nil } +// GitGcRepo calls 'git gc' to remove unnecessary files and optimize the local repository +func GitGcRepo(ctx context.Context, repo *repo_model.Repository, timeout time.Duration, args []git.CmdArg) error { + log.Trace("Running git gc on %-v", repo) + command := git.NewCommand(ctx, args...). + SetDescription(fmt.Sprintf("Repository Garbage Collection: %s", repo.FullName())) + var stdout string + var err error + stdout, _, err = command.RunStdString(&git.RunOpts{Timeout: timeout, Dir: repo.RepoPath()}) + + if err != nil { + log.Error("Repository garbage collection failed for %v. Stdout: %s\nError: %v", repo, stdout, err) + desc := fmt.Sprintf("Repository garbage collection failed for %s. Stdout: %s\nError: %v", repo.RepoPath(), stdout, err) + if err = system_model.CreateRepositoryNotice(desc); err != nil { + log.Error("CreateRepositoryNotice: %v", err) + } + return fmt.Errorf("Repository garbage collection failed in repo: %s: Error: %w", repo.FullName(), err) + } + + // Now update the size of the repository + if err := repo_module.UpdateRepoSize(ctx, repo); err != nil { + log.Error("Updating size as part of garbage collection failed for %-v. Stdout: %s\nError: %v", repo, stdout, err) + desc := fmt.Sprintf("Updating size as part of garbage collection failed for %s. Stdout: %s\nError: %v", repo.RepoPath(), stdout, err) + if err = system_model.CreateRepositoryNotice(desc); err != nil { + log.Error("CreateRepositoryNotice: %v", err) + } + return fmt.Errorf("Updating size as part of garbage collection failed in repo: %s: Error: %w", repo.FullName(), err) + } + + return nil +} + func gatherMissingRepoRecords(ctx context.Context) ([]*repo_model.Repository, error) { repos := make([]*repo_model.Repository, 0, 10) if err := db.Iterate( diff --git a/services/repository/files/cherry_pick.go b/services/repository/files/cherry_pick.go index a30d4f6025..6bc67e2636 100644 --- a/services/repository/files/cherry_pick.go +++ b/services/repository/files/cherry_pick.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package files diff --git a/services/repository/files/commit.go b/services/repository/files/commit.go index bc5a4c8ed3..c49b03d608 100644 --- a/services/repository/files/commit.go +++ b/services/repository/files/commit.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package files diff --git a/services/repository/files/content.go b/services/repository/files/content.go index 34c8aeec25..a311625f31 100644 --- a/services/repository/files/content.go +++ b/services/repository/files/content.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package files diff --git a/services/repository/files/content_test.go b/services/repository/files/content_test.go index 24fcd6c4c5..a43b71cf31 100644 --- a/services/repository/files/content_test.go +++ b/services/repository/files/content_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package files diff --git a/services/repository/files/delete.go b/services/repository/files/delete.go index f098052ad8..faa60bb3ba 100644 --- a/services/repository/files/delete.go +++ b/services/repository/files/delete.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package files diff --git a/services/repository/files/diff.go b/services/repository/files/diff.go index dbe1bef52b..373249b114 100644 --- a/services/repository/files/diff.go +++ b/services/repository/files/diff.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package files diff --git a/services/repository/files/diff_test.go b/services/repository/files/diff_test.go index 310308ca88..621816e97d 100644 --- a/services/repository/files/diff_test.go +++ b/services/repository/files/diff_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package files diff --git a/services/repository/files/file.go b/services/repository/files/file.go index c6c626c9ce..ddd64a5399 100644 --- a/services/repository/files/file.go +++ b/services/repository/files/file.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package files diff --git a/services/repository/files/file_test.go b/services/repository/files/file_test.go index e158c63de2..e1c7d5d7fb 100644 --- a/services/repository/files/file_test.go +++ b/services/repository/files/file_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package files diff --git a/services/repository/files/patch.go b/services/repository/files/patch.go index 2be01f25be..b5eef8c091 100644 --- a/services/repository/files/patch.go +++ b/services/repository/files/patch.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package files diff --git a/services/repository/files/temp_repo.go b/services/repository/files/temp_repo.go index b96d9e7b3d..1f3375cdcc 100644 --- a/services/repository/files/temp_repo.go +++ b/services/repository/files/temp_repo.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package files diff --git a/services/repository/files/tree.go b/services/repository/files/tree.go index 59e5690977..1aa6d0df36 100644 --- a/services/repository/files/tree.go +++ b/services/repository/files/tree.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package files diff --git a/services/repository/files/tree_test.go b/services/repository/files/tree_test.go index e900480d35..a500dbdb22 100644 --- a/services/repository/files/tree_test.go +++ b/services/repository/files/tree_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package files diff --git a/services/repository/files/update.go b/services/repository/files/update.go index 1721b00b01..f7a41ef24c 100644 --- a/services/repository/files/update.go +++ b/services/repository/files/update.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package files diff --git a/services/repository/files/upload.go b/services/repository/files/upload.go index 3728780991..240564d401 100644 --- a/services/repository/files/upload.go +++ b/services/repository/files/upload.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package files @@ -70,7 +69,7 @@ func UploadRepoFiles(ctx context.Context, repo *repo_model.Repository, doer *use return err } if lfsLock != nil && lfsLock.OwnerID != doer.ID { - u, err := user_model.GetUserByID(lfsLock.OwnerID) + u, err := user_model.GetUserByID(ctx, lfsLock.OwnerID) if err != nil { return err } diff --git a/services/repository/fork.go b/services/repository/fork.go index 136d7ccab6..3ed0f4ffa5 100644 --- a/services/repository/fork.go +++ b/services/repository/fork.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository @@ -112,7 +111,7 @@ func ForkRepository(ctx context.Context, doer, owner *user_model.User, opts Fork panic(panicErr) }() - err = db.WithTx(func(txCtx context.Context) error { + err = db.WithTx(ctx, func(txCtx context.Context) error { if err = repo_module.CreateRepositoryByExample(txCtx, doer, owner, repo, false); err != nil { return err } @@ -177,15 +176,15 @@ func ForkRepository(ctx context.Context, doer, owner *user_model.User, opts Fork } } - notification.NotifyForkRepository(doer, opts.BaseRepo, repo) + notification.NotifyForkRepository(ctx, doer, opts.BaseRepo, repo) return repo, nil } // ConvertForkToNormalRepository convert the provided repo from a forked repo to normal repo func ConvertForkToNormalRepository(repo *repo_model.Repository) error { - err := db.WithTx(func(ctx context.Context) error { - repo, err := repo_model.GetRepositoryByIDCtx(ctx, repo.ID) + err := db.WithTx(db.DefaultContext, func(ctx context.Context) error { + repo, err := repo_model.GetRepositoryByID(ctx, repo.ID) if err != nil { return err } diff --git a/services/repository/fork_test.go b/services/repository/fork_test.go index d4ba507351..c809ed4529 100644 --- a/services/repository/fork_test.go +++ b/services/repository/fork_test.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package repository diff --git a/services/repository/hooks.go b/services/repository/hooks.go index d29384e012..a8b6f7a622 100644 --- a/services/repository/hooks.go +++ b/services/repository/hooks.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package repository diff --git a/services/repository/lfs.go b/services/repository/lfs.go new file mode 100644 index 0000000000..0e88d359a8 --- /dev/null +++ b/services/repository/lfs.go @@ -0,0 +1,105 @@ +// Copyright 2022 The Gitea Authors. All rights reserved. +// SPDX-License-Identifier: MIT + +package repository + +import ( + "context" + "fmt" + "time" + + "code.gitea.io/gitea/models/db" + git_model "code.gitea.io/gitea/models/git" + repo_model "code.gitea.io/gitea/models/repo" + "code.gitea.io/gitea/modules/git" + "code.gitea.io/gitea/modules/lfs" + "code.gitea.io/gitea/modules/log" + + "xorm.io/builder" +) + +func GarbageCollectLFSMetaObjects(ctx context.Context, logger log.Logger, autofix bool) error { + log.Trace("Doing: GarbageCollectLFSMetaObjects") + + if err := db.Iterate( + ctx, + builder.And(builder.Gt{"id": 0}), + func(ctx context.Context, repo *repo_model.Repository) error { + return GarbageCollectLFSMetaObjectsForRepo(ctx, repo, logger, autofix) + }, + ); err != nil { + return err + } + + log.Trace("Finished: GarbageCollectLFSMetaObjects") + return nil +} + +func GarbageCollectLFSMetaObjectsForRepo(ctx context.Context, repo *repo_model.Repository, logger log.Logger, autofix bool) error { + if logger != nil { + logger.Info("Checking %-v", repo) + } + total, orphaned, collected, deleted := 0, 0, 0, 0 + if logger != nil { + defer func() { + if orphaned == 0 { + logger.Info("Found %d total LFSMetaObjects in %-v", total, repo) + } else if !autofix { + logger.Info("Found %d/%d orphaned LFSMetaObjects in %-v", orphaned, total, repo) + } else { + logger.Info("Collected %d/%d orphaned/%d total LFSMetaObjects in %-v. %d removed from storage.", collected, orphaned, total, repo, deleted) + } + }() + } + + gitRepo, err := git.OpenRepository(ctx, repo.RepoPath()) + if err != nil { + log.Error("Unable to open git repository %-v: %v", repo, err) + return err + } + defer gitRepo.Close() + + store := lfs.NewContentStore() + + return git_model.IterateLFSMetaObjectsForRepo(ctx, repo.ID, func(ctx context.Context, metaObject *git_model.LFSMetaObject, count int64) error { + total++ + pointerSha := git.ComputeBlobHash([]byte(metaObject.Pointer.StringContent())) + + if gitRepo.IsObjectExist(pointerSha.String()) { + return nil + } + orphaned++ + + if !autofix { + return nil + } + // Non-existent pointer file + _, err = git_model.RemoveLFSMetaObjectByOidFn(repo.ID, metaObject.Oid, func(count int64) error { + if count > 0 { + return nil + } + + if err := store.Delete(metaObject.RelativePath()); err != nil { + log.Error("Unable to remove lfs metaobject %s from store: %v", metaObject.Oid, err) + } + deleted++ + return nil + }) + if err != nil { + return fmt.Errorf("unable to remove meta-object %s in %s: %w", metaObject.Oid, repo.FullName(), err) + } + collected++ + + return nil + }, &git_model.IterateLFSMetaObjectsForRepoOptions{ + // Only attempt to garbage collect lfs meta objects older than a week as the order of git lfs upload + // and git object upload is not necessarily guaranteed. It's possible to imagine a situation whereby + // an LFS object is uploaded but the git branch is not uploaded immediately, or there are some rapid + // changes in new branches that might lead to lfs objects becoming temporarily unassociated with git + // objects. + // + // It is likely that a week is potentially excessive but it should definitely be enough that any + // unassociated LFS object is genuinely unassociated. + OlderThan: time.Now().Add(-24 * 7 * time.Hour), + }) +} diff --git a/services/repository/main_test.go b/services/repository/main_test.go index 42134fa7ad..007790f2a9 100644 --- a/services/repository/main_test.go +++ b/services/repository/main_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository diff --git a/services/repository/push.go b/services/repository/push.go index 3a7205d18b..f1eedb8e08 100644 --- a/services/repository/push.go +++ b/services/repository/push.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package repository @@ -82,7 +81,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { ctx, _, finished := process.GetManager().AddContext(graceful.GetManager().HammerContext(), fmt.Sprintf("PushUpdates: %s/%s", optsList[0].RepoUserName, optsList[0].RepoName)) defer finished() - repo, err := repo_model.GetRepositoryByOwnerAndName(optsList[0].RepoUserName, optsList[0].RepoName) + repo, err := repo_model.GetRepositoryByOwnerAndName(ctx, optsList[0].RepoUserName, optsList[0].RepoName) if err != nil { return fmt.Errorf("GetRepositoryByOwnerAndName failed: %w", err) } @@ -110,14 +109,14 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { if opts.IsTag() { // If is tag reference if pusher == nil || pusher.ID != opts.PusherID { var err error - if pusher, err = user_model.GetUserByID(opts.PusherID); err != nil { + if pusher, err = user_model.GetUserByID(ctx, opts.PusherID); err != nil { return err } } tagName := opts.TagName() if opts.IsDelRef() { notification.NotifyPushCommits( - pusher, repo, + db.DefaultContext, pusher, repo, &repo_module.PushUpdateOptions{ RefFullName: git.TagPrefix + tagName, OldCommitID: opts.OldCommitID, @@ -125,7 +124,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { }, repo_module.NewPushCommits()) delTags = append(delTags, tagName) - notification.NotifyDeleteRef(pusher, repo, "tag", opts.RefFullName) + notification.NotifyDeleteRef(db.DefaultContext, pusher, repo, "tag", opts.RefFullName) } else { // is new tag newCommit, err := gitRepo.GetCommit(opts.NewCommitID) if err != nil { @@ -137,7 +136,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { commits.CompareURL = repo.ComposeCompareURL(git.EmptySHA, opts.NewCommitID) notification.NotifyPushCommits( - pusher, repo, + db.DefaultContext, pusher, repo, &repo_module.PushUpdateOptions{ RefFullName: git.TagPrefix + tagName, OldCommitID: git.EmptySHA, @@ -145,12 +144,12 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { }, commits) addTags = append(addTags, tagName) - notification.NotifyCreateRef(pusher, repo, "tag", opts.RefFullName, opts.NewCommitID) + notification.NotifyCreateRef(db.DefaultContext, pusher, repo, "tag", opts.RefFullName, opts.NewCommitID) } } else if opts.IsBranch() { // If is branch reference if pusher == nil || pusher.ID != opts.PusherID { var err error - if pusher, err = user_model.GetUserByID(opts.PusherID); err != nil { + if pusher, err = user_model.GetUserByID(ctx, opts.PusherID); err != nil { return err } } @@ -190,7 +189,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { if err != nil { return fmt.Errorf("newCommit.CommitsBeforeLimit: %w", err) } - notification.NotifyCreateRef(pusher, repo, "branch", opts.RefFullName, opts.NewCommitID) + notification.NotifyCreateRef(db.DefaultContext, pusher, repo, "branch", opts.RefFullName, opts.NewCommitID) } else { l, err = newCommit.CommitsBeforeUntil(opts.OldCommitID) if err != nil { @@ -250,7 +249,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { commits.Commits = commits.Commits[:setting.UI.FeedMaxCommitNum] } - notification.NotifyPushCommits(pusher, repo, opts, commits) + notification.NotifyPushCommits(db.DefaultContext, pusher, repo, opts, commits) if err = git_model.RemoveDeletedBranchByName(repo.ID, branch); err != nil { log.Error("models.RemoveDeletedBranch %s/%s failed: %v", repo.ID, branch, err) @@ -261,7 +260,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { log.Error("repo_module.CacheRef %s/%s failed: %v", repo.ID, branch, err) } } else { - notification.NotifyDeleteRef(pusher, repo, "branch", opts.RefFullName) + notification.NotifyDeleteRef(db.DefaultContext, pusher, repo, "branch", opts.RefFullName) if err = pull_service.CloseBranchPulls(pusher, repo.ID, branch); err != nil { // close all related pulls log.Error("close related pull request failed: %v", err) @@ -290,7 +289,7 @@ func pushUpdates(optsList []*repo_module.PushUpdateOptions) error { // PushUpdateAddDeleteTags updates a number of added and delete tags func PushUpdateAddDeleteTags(repo *repo_model.Repository, gitRepo *git.Repository, addTags, delTags []string) error { - return db.WithTx(func(ctx context.Context) error { + return db.WithTx(db.DefaultContext, func(ctx context.Context) error { if err := repo_model.PushUpdateDeleteTagsContext(ctx, repo, delTags); err != nil { return err } diff --git a/services/repository/repository.go b/services/repository/repository.go index 763ef74927..3c3e7e82c3 100644 --- a/services/repository/repository.go +++ b/services/repository/repository.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository @@ -32,7 +31,7 @@ func CreateRepository(doer, owner *user_model.User, opts repo_module.CreateRepoO return nil, err } - notification.NotifyCreateRepository(doer, owner, repo) + notification.NotifyCreateRepository(db.DefaultContext, doer, owner, repo) return repo, nil } @@ -45,7 +44,7 @@ func DeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_mod if notify { // If the repo itself has webhooks, we need to trigger them before deleting it... - notification.NotifyDeleteRepository(doer, repo) + notification.NotifyDeleteRepository(ctx, doer, repo) } if err := models.DeleteRepository(doer, repo.OwnerID, repo.ID); err != nil { @@ -59,7 +58,7 @@ func DeleteRepository(ctx context.Context, doer *user_model.User, repo *repo_mod func PushCreateRepo(authUser, owner *user_model.User, repoName string) (*repo_model.Repository, error) { if !authUser.IsAdmin { if owner.IsOrganization() { - if ok, err := organization.CanCreateOrgRepo(owner.ID, authUser.ID); err != nil { + if ok, err := organization.CanCreateOrgRepo(db.DefaultContext, owner.ID, authUser.ID); err != nil { return nil, err } else if !ok { return nil, fmt.Errorf("cannot push-create repository for org") @@ -90,7 +89,7 @@ func Init() error { // UpdateRepository updates a repository func UpdateRepository(repo *repo_model.Repository, visibilityChanged bool) (err error) { - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -104,24 +103,24 @@ func UpdateRepository(repo *repo_model.Repository, visibilityChanged bool) (err } // LinkedRepository returns the linked repo if any -func LinkedRepository(a *repo_model.Attachment) (*repo_model.Repository, unit.Type, error) { +func LinkedRepository(ctx context.Context, a *repo_model.Attachment) (*repo_model.Repository, unit.Type, error) { if a.IssueID != 0 { - iss, err := issues_model.GetIssueByID(db.DefaultContext, a.IssueID) + iss, err := issues_model.GetIssueByID(ctx, a.IssueID) if err != nil { return nil, unit.TypeIssues, err } - repo, err := repo_model.GetRepositoryByID(iss.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, iss.RepoID) unitType := unit.TypeIssues if iss.IsPull { unitType = unit.TypePullRequests } return repo, unitType, err } else if a.ReleaseID != 0 { - rel, err := repo_model.GetReleaseByID(db.DefaultContext, a.ReleaseID) + rel, err := repo_model.GetReleaseByID(ctx, a.ReleaseID) if err != nil { return nil, unit.TypeReleases, err } - repo, err := repo_model.GetRepositoryByID(rel.RepoID) + repo, err := repo_model.GetRepositoryByID(ctx, rel.RepoID) return repo, unit.TypeReleases, err } return nil, -1, nil diff --git a/services/repository/repository_test.go b/services/repository/repository_test.go index e0ffcac3cc..892a11a23e 100644 --- a/services/repository/repository_test.go +++ b/services/repository/repository_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package repository @@ -32,7 +31,7 @@ func TestLinkedRepository(t *testing.T) { t.Run(tc.name, func(t *testing.T) { attach, err := repo_model.GetAttachmentByID(db.DefaultContext, tc.attachID) assert.NoError(t, err) - repo, unitType, err := LinkedRepository(attach) + repo, unitType, err := LinkedRepository(db.DefaultContext, attach) assert.NoError(t, err) if tc.expectedRepo != nil { assert.Equal(t, tc.expectedRepo.ID, repo.ID) diff --git a/services/repository/review.go b/services/repository/review.go index 9e8012978e..d30d61ee06 100644 --- a/services/repository/review.go +++ b/services/repository/review.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package repository diff --git a/services/repository/review_test.go b/services/repository/review_test.go index badacf39a6..2bf4cdbf5c 100644 --- a/services/repository/review_test.go +++ b/services/repository/review_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package repository diff --git a/services/repository/template.go b/services/repository/template.go index b73abdce58..13e0749869 100644 --- a/services/repository/template.go +++ b/services/repository/template.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository @@ -48,7 +47,7 @@ func GenerateRepository(doer, owner *user_model.User, templateRepo *repo_model.R } var generateRepo *repo_model.Repository - if err = db.WithTx(func(ctx context.Context) error { + if err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { generateRepo, err = repo_module.GenerateRepository(ctx, doer, owner, templateRepo, opts) if err != nil { return err @@ -101,7 +100,7 @@ func GenerateRepository(doer, owner *user_model.User, templateRepo *repo_model.R return nil, err } - notification.NotifyCreateRepository(doer, owner, generateRepo) + notification.NotifyCreateRepository(db.DefaultContext, doer, owner, generateRepo) return generateRepo, nil } diff --git a/services/repository/transfer.go b/services/repository/transfer.go index a0f4a7685c..f4afb7e2de 100644 --- a/services/repository/transfer.go +++ b/services/repository/transfer.go @@ -1,10 +1,10 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository import ( + "context" "fmt" "code.gitea.io/gitea/models" @@ -25,8 +25,8 @@ import ( var repoWorkingPool = sync.NewExclusivePool() // TransferOwnership transfers all corresponding setting from old user to new one. -func TransferOwnership(doer, newOwner *user_model.User, repo *repo_model.Repository, teams []*organization.Team) error { - if err := repo.GetOwner(db.DefaultContext); err != nil { +func TransferOwnership(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository, teams []*organization.Team) error { + if err := repo.GetOwner(ctx); err != nil { return err } for _, team := range teams { @@ -44,18 +44,18 @@ func TransferOwnership(doer, newOwner *user_model.User, repo *repo_model.Reposit } repoWorkingPool.CheckOut(fmt.Sprint(repo.ID)) - newRepo, err := repo_model.GetRepositoryByID(repo.ID) + newRepo, err := repo_model.GetRepositoryByID(ctx, repo.ID) if err != nil { return err } for _, team := range teams { - if err := models.AddRepository(db.DefaultContext, team, newRepo); err != nil { + if err := models.AddRepository(ctx, team, newRepo); err != nil { return err } } - notification.NotifyTransferRepository(doer, repo, oldOwner.Name) + notification.NotifyTransferRepository(ctx, doer, repo, oldOwner.Name) return nil } @@ -78,56 +78,56 @@ func ChangeRepositoryName(doer *user_model.User, repo *repo_model.Repository, ne repoWorkingPool.CheckOut(fmt.Sprint(repo.ID)) repo.Name = newRepoName - notification.NotifyRenameRepository(doer, repo, oldRepoName) + notification.NotifyRenameRepository(db.DefaultContext, doer, repo, oldRepoName) return nil } // StartRepositoryTransfer transfer a repo from one owner to a new one. // it make repository into pending transfer state, if doer can not create repo for new owner. -func StartRepositoryTransfer(doer, newOwner *user_model.User, repo *repo_model.Repository, teams []*organization.Team) error { +func StartRepositoryTransfer(ctx context.Context, doer, newOwner *user_model.User, repo *repo_model.Repository, teams []*organization.Team) error { if err := models.TestRepositoryReadyForTransfer(repo.Status); err != nil { return err } // Admin is always allowed to transfer || user transfer repo back to his account if doer.IsAdmin || doer.ID == newOwner.ID { - return TransferOwnership(doer, newOwner, repo, teams) + return TransferOwnership(ctx, doer, newOwner, repo, teams) } // If new owner is an org and user can create repos he can transfer directly too if newOwner.IsOrganization() { - allowed, err := organization.CanCreateOrgRepo(newOwner.ID, doer.ID) + allowed, err := organization.CanCreateOrgRepo(ctx, newOwner.ID, doer.ID) if err != nil { return err } if allowed { - return TransferOwnership(doer, newOwner, repo, teams) + return TransferOwnership(ctx, doer, newOwner, repo, teams) } } // In case the new owner would not have sufficient access to the repo, give access rights for read - hasAccess, err := access_model.HasAccess(db.DefaultContext, newOwner.ID, repo) + hasAccess, err := access_model.HasAccess(ctx, newOwner.ID, repo) if err != nil { return err } if !hasAccess { - if err := repo_module.AddCollaborator(repo, newOwner); err != nil { + if err := repo_module.AddCollaborator(ctx, repo, newOwner); err != nil { return err } - if err := repo_model.ChangeCollaborationAccessMode(repo, newOwner.ID, perm.AccessModeRead); err != nil { + if err := repo_model.ChangeCollaborationAccessMode(ctx, repo, newOwner.ID, perm.AccessModeRead); err != nil { return err } } // Make repo as pending for transfer repo.Status = repo_model.RepositoryPendingTransfer - if err := models.CreatePendingRepositoryTransfer(doer, newOwner, repo.ID, teams); err != nil { + if err := models.CreatePendingRepositoryTransfer(ctx, doer, newOwner, repo.ID, teams); err != nil { return err } // notify users who are able to accept / reject transfer - notification.NotifyRepoPendingTransfer(doer, newOwner, repo) + notification.NotifyRepoPendingTransfer(ctx, doer, newOwner, repo) return nil } diff --git a/services/repository/transfer_test.go b/services/repository/transfer_test.go index bf2a0ce0a2..1299e66be2 100644 --- a/services/repository/transfer_test.go +++ b/services/repository/transfer_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package repository @@ -38,7 +37,7 @@ func TestTransferOwnership(t *testing.T) { doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) repo.Owner = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) - assert.NoError(t, TransferOwnership(doer, doer, repo, nil)) + assert.NoError(t, TransferOwnership(db.DefaultContext, doer, doer, repo, nil)) transferredRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) assert.EqualValues(t, 2, transferredRepo.OwnerID) @@ -71,7 +70,7 @@ func TestStartRepositoryTransferSetPermission(t *testing.T) { assert.NoError(t, err) assert.False(t, hasAccess) - assert.NoError(t, StartRepositoryTransfer(doer, recipient, repo, nil)) + assert.NoError(t, StartRepositoryTransfer(db.DefaultContext, doer, recipient, repo, nil)) hasAccess, err = access_model.HasAccess(db.DefaultContext, recipient.ID, repo) assert.NoError(t, err) diff --git a/services/task/migrate.go b/services/task/migrate.go index faca6908a2..03d083e596 100644 --- a/services/task/migrate.go +++ b/services/task/migrate.go @@ -1,6 +1,5 @@ // Copyright 2019 Gitea. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package task @@ -51,7 +50,7 @@ func runMigrateTask(t *admin_model.Task) (err error) { if err == nil { err = admin_model.FinishMigrateTask(t) if err == nil { - notification.NotifyMigrateRepository(t.Doer, t.Owner, t.Repo) + notification.NotifyMigrateRepository(db.DefaultContext, t.Doer, t.Owner, t.Repo) return } diff --git a/services/task/task.go b/services/task/task.go index 138dc88a04..41bc07f2f6 100644 --- a/services/task/task.go +++ b/services/task/task.go @@ -1,6 +1,5 @@ // Copyright 2019 Gitea. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package task diff --git a/services/user/user.go b/services/user/user.go index 8dae88378a..d901eeee3b 100644 --- a/services/user/user.go +++ b/services/user/user.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package user @@ -80,7 +79,7 @@ func DeleteUser(ctx context.Context, u *user_model.User, purge bool) error { Actor: u, }) if err != nil { - return fmt.Errorf("SearchRepositoryByName: %w", err) + return fmt.Errorf("GetUserRepositories: %w", err) } if len(repos) == 0 { break @@ -134,7 +133,7 @@ func DeleteUser(ctx context.Context, u *user_model.User, purge bool) error { } } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -237,7 +236,7 @@ func UploadAvatar(u *user_model.User, data []byte) error { return err } - ctx, committer, err := db.TxContext() + ctx, committer, err := db.TxContext(db.DefaultContext) if err != nil { return err } @@ -284,18 +283,18 @@ func DeleteAvatar(u *user_model.User) error { } // FollowUser marks someone be another's follower. -func FollowUser(userID, followID int64) (err error) { +func FollowUser(ctx context.Context, userID, followID int64) (err error) { if userID == followID || user_model.IsFollowing(userID, followID) { return nil } - followUser, err := user_model.GetUserByID(followID) + followUser, err := user_model.GetUserByID(ctx, followID) if err != nil { return } if followUser.LoginType == auth.Federated { // Following remote user - actorUser, err := user_model.GetUserByID(userID) + actorUser, err := user_model.GetUserByID(ctx, userID) if err != nil { return err } @@ -309,18 +308,18 @@ func FollowUser(userID, followID int64) (err error) { } // UnfollowUser unmarks someone as another's follower. -func UnfollowUser(userID, followID int64) (err error) { +func UnfollowUser(ctx context.Context, userID, followID int64) (err error) { if userID == followID || !user_model.IsFollowing(userID, followID) { return nil } - followUser, err := user_model.GetUserByID(followID) + followUser, err := user_model.GetUserByID(ctx, followID) if err != nil { return } if followUser.LoginType == auth.Federated { // Unfollowing remote user - actorUser, err := user_model.GetUserByID(userID) + actorUser, err := user_model.GetUserByID(ctx, userID) if err != nil { return err } diff --git a/services/user/user_test.go b/services/user/user_test.go index c07244e7e1..5e052a9df2 100644 --- a/services/user/user_test.go +++ b/services/user/user_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package user diff --git a/services/webhook/deliver.go b/services/webhook/deliver.go index 85717e0978..eed711c580 100644 --- a/services/webhook/deliver.go +++ b/services/webhook/deliver.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package webhook @@ -23,6 +22,7 @@ import ( "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/hostmatcher" "code.gitea.io/gitea/modules/log" + "code.gitea.io/gitea/modules/process" "code.gitea.io/gitea/modules/proxy" "code.gitea.io/gitea/modules/queue" "code.gitea.io/gitea/modules/setting" @@ -43,7 +43,7 @@ func Deliver(ctx context.Context, t *webhook_model.HookTask) error { return } // There was a panic whilst delivering a hook... - log.Error("PANIC whilst trying to deliver webhook[%d] to %s Panic: %v\nStacktrace: %s", t.ID, w.URL, err, log.Stack(2)) + log.Error("PANIC whilst trying to deliver webhook task[%d] to webhook %s Panic: %v\nStacktrace: %s", t.ID, w.URL, err, log.Stack(2)) }() t.IsDelivered = true @@ -52,7 +52,7 @@ func Deliver(ctx context.Context, t *webhook_model.HookTask) error { switch w.HTTPMethod { case "": - log.Info("HTTP Method for webhook %d empty, setting to POST as default", t.ID) + log.Info("HTTP Method for webhook %s empty, setting to POST as default", w.URL) fallthrough case http.MethodPost: switch w.ContentType { @@ -78,14 +78,14 @@ func Deliver(ctx context.Context, t *webhook_model.HookTask) error { case http.MethodGet: u, err := url.Parse(w.URL) if err != nil { - return err + return fmt.Errorf("unable to deliver webhook task[%d] as cannot parse webhook url %s: %w", t.ID, w.URL, err) } vals := u.Query() vals["payload"] = []string{t.PayloadContent} u.RawQuery = vals.Encode() req, err = http.NewRequest("GET", u.String(), nil) if err != nil { - return err + return fmt.Errorf("unable to deliver webhook task[%d] as unable to create HTTP request for webhook url %s: %w", t.ID, w.URL, err) } case http.MethodPut: switch w.Type { @@ -97,13 +97,13 @@ func Deliver(ctx context.Context, t *webhook_model.HookTask) error { url := fmt.Sprintf("%s/%s", w.URL, url.PathEscape(txnID)) req, err = http.NewRequest("PUT", url, strings.NewReader(t.PayloadContent)) if err != nil { - return err + return fmt.Errorf("unable to deliver webhook task[%d] as cannot create matrix request for webhook url %s: %w", t.ID, w.URL, err) } default: - return fmt.Errorf("invalid http method for webhook: [%d] %v", t.ID, w.HTTPMethod) + return fmt.Errorf("invalid http method for webhook task[%d] in webhook %s: %v", t.ID, w.URL, w.HTTPMethod) } default: - return fmt.Errorf("invalid http method for webhook: [%d] %v", t.ID, w.HTTPMethod) + return fmt.Errorf("invalid http method for webhook task[%d] in webhook %s: %v", t.ID, w.URL, w.HTTPMethod) } var signatureSHA1 string @@ -159,6 +159,20 @@ func Deliver(ctx context.Context, t *webhook_model.HookTask) error { Headers: map[string]string{}, } + // OK We're now ready to attempt to deliver the task - we must double check that it + // has not been delivered in the meantime + updated, err := webhook_model.MarkTaskDelivered(ctx, t) + if err != nil { + log.Error("MarkTaskDelivered[%d]: %v", t.ID, err) + return fmt.Errorf("unable to mark task[%d] delivered in the db: %w", t.ID, err) + } + if !updated { + // This webhook task has already been attempted to be delivered or is in the process of being delivered + log.Trace("Webhook Task[%d] already delivered", t.ID) + return nil + } + + // All code from this point will update the hook task defer func() { t.Delivered = time.Now().UnixNano() if t.IsSucceed { @@ -190,13 +204,14 @@ func Deliver(ctx context.Context, t *webhook_model.HookTask) error { } if !w.IsActive { + log.Trace("Webhook %s in Webhook Task[%d] is not active", w.URL, t.ID) return nil } resp, err := webhookHTTPClient.Do(req.WithContext(ctx)) if err != nil { t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err) - return err + return fmt.Errorf("unable to deliver webhook task[%d] in %s due to error in http client: %w", t.ID, w.URL, err) } defer resp.Body.Close() @@ -210,7 +225,7 @@ func Deliver(ctx context.Context, t *webhook_model.HookTask) error { p, err := io.ReadAll(resp.Body) if err != nil { t.ResponseInfo.Body = fmt.Sprintf("read body: %s", err) - return err + return fmt.Errorf("unable to deliver webhook task[%d] in %s as unable to read response body: %w", t.ID, w.URL, err) } t.ResponseInfo.Body = string(p) return nil @@ -272,17 +287,37 @@ func Init() error { } go graceful.GetManager().RunWithShutdownFns(hookQueue.Run) - tasks, err := webhook_model.FindUndeliveredHookTasks(graceful.GetManager().HammerContext()) - if err != nil { - log.Error("FindUndeliveredHookTasks failed: %v", err) - return err - } - - for _, task := range tasks { - if err := enqueueHookTask(task); err != nil { - log.Error("enqueueHookTask failed: %v", err) - } - } + go graceful.GetManager().RunWithShutdownContext(populateWebhookSendingQueue) return nil } + +func populateWebhookSendingQueue(ctx context.Context) { + ctx, _, finished := process.GetManager().AddContext(ctx, "Webhook: Populate sending queue") + defer finished() + + lowerID := int64(0) + for { + taskIDs, err := webhook_model.FindUndeliveredHookTaskIDs(ctx, lowerID) + if err != nil { + log.Error("Unable to populate webhook queue as FindUndeliveredHookTaskIDs failed: %v", err) + return + } + if len(taskIDs) == 0 { + return + } + lowerID = taskIDs[len(taskIDs)-1] + + for _, taskID := range taskIDs { + select { + case <-ctx.Done(): + log.Warn("Shutdown before Webhook Sending queue finishing being populated") + return + default: + } + if err := enqueueHookTask(taskID); err != nil { + log.Error("Unable to push HookTask[%d] to the Webhook Sending queue: %v", taskID, err) + } + } + } +} diff --git a/services/webhook/deliver_test.go b/services/webhook/deliver_test.go index 83ca7d6178..e7a042f4d2 100644 --- a/services/webhook/deliver_test.go +++ b/services/webhook/deliver_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package webhook @@ -16,6 +15,7 @@ import ( "code.gitea.io/gitea/models/unittest" webhook_model "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/setting" + api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" ) @@ -67,8 +67,15 @@ func TestWebhookDeliverAuthorizationHeader(t *testing.T) { err := hook.SetHeaderAuthorization("Bearer s3cr3t-t0ken") assert.NoError(t, err) assert.NoError(t, webhook_model.CreateWebhook(db.DefaultContext, hook)) + db.GetEngine(db.DefaultContext).NoAutoTime().DB().Logger.ShowSQL(true) - hookTask := &webhook_model.HookTask{HookID: hook.ID, EventType: webhook_model.HookEventPush} + hookTask := &webhook_model.HookTask{HookID: hook.ID, EventType: webhook_model.HookEventPush, Payloader: &api.PushPayload{}} + + hookTask, err = webhook_model.CreateHookTask(db.DefaultContext, hookTask) + assert.NoError(t, err) + if !assert.NotNil(t, hookTask) { + return + } assert.NoError(t, Deliver(context.Background(), hookTask)) select { diff --git a/services/webhook/dingtalk.go b/services/webhook/dingtalk.go index e047e994c2..7cb1fb75fc 100644 --- a/services/webhook/dingtalk.go +++ b/services/webhook/dingtalk.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/dingtalk_test.go b/services/webhook/dingtalk_test.go index fc15380f4d..89b5f9d219 100644 --- a/services/webhook/dingtalk_test.go +++ b/services/webhook/dingtalk_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/discord.go b/services/webhook/discord.go index 22d75db893..c9fdc95320 100644 --- a/services/webhook/discord.go +++ b/services/webhook/discord.go @@ -1,6 +1,5 @@ // Copyright 2017 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/discord_test.go b/services/webhook/discord_test.go index 8e4e60a7ff..df3cdc15bd 100644 --- a/services/webhook/discord_test.go +++ b/services/webhook/discord_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/feishu.go b/services/webhook/feishu.go index 782684d0ff..58b6fff331 100644 --- a/services/webhook/feishu.go +++ b/services/webhook/feishu.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/feishu_test.go b/services/webhook/feishu_test.go index 85cfb759fe..df44fd1f72 100644 --- a/services/webhook/feishu_test.go +++ b/services/webhook/feishu_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/general.go b/services/webhook/general.go index 5be177d339..bec752cffe 100644 --- a/services/webhook/general.go +++ b/services/webhook/general.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package webhook @@ -84,11 +83,13 @@ func getPullRequestPayloadInfo(p *api.PullRequestPayload, linkFormatter linkForm issueTitle := fmt.Sprintf("#%d %s", p.Index, p.PullRequest.Title) titleLink := linkFormatter(p.PullRequest.URL, issueTitle) var text string + var attachmentText string color := yellowColor switch p.Action { case api.HookIssueOpened: text = fmt.Sprintf("[%s] Pull request opened: %s", repoLink, titleLink) + attachmentText = p.PullRequest.Body color = greenColor case api.HookIssueClosed: if p.PullRequest.HasMerged { @@ -102,6 +103,7 @@ func getPullRequestPayloadInfo(p *api.PullRequestPayload, linkFormatter linkForm text = fmt.Sprintf("[%s] Pull request re-opened: %s", repoLink, titleLink) case api.HookIssueEdited: text = fmt.Sprintf("[%s] Pull request edited: %s", repoLink, titleLink) + attachmentText = p.PullRequest.Body case api.HookIssueAssigned: list := make([]string, len(p.PullRequest.Assignees)) for i, user := range p.PullRequest.Assignees { @@ -126,16 +128,12 @@ func getPullRequestPayloadInfo(p *api.PullRequestPayload, linkFormatter linkForm text = fmt.Sprintf("[%s] Pull request milestone cleared: %s", repoLink, titleLink) case api.HookIssueReviewed: text = fmt.Sprintf("[%s] Pull request reviewed: %s", repoLink, titleLink) + attachmentText = p.Review.Content } if withSender { text += fmt.Sprintf(" by %s", linkFormatter(setting.AppURL+p.Sender.UserName, p.Sender.UserName)) } - var attachmentText string - if p.Action == api.HookIssueOpened || p.Action == api.HookIssueEdited { - attachmentText = p.PullRequest.Body - } - return text, issueTitle, attachmentText, color } diff --git a/services/webhook/general_test.go b/services/webhook/general_test.go index da3123d3ab..ba58ca4f90 100644 --- a/services/webhook/general_test.go +++ b/services/webhook/general_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/main_test.go b/services/webhook/main_test.go index 5ddb6cf1f3..6cf9410735 100644 --- a/services/webhook/main_test.go +++ b/services/webhook/main_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/matrix.go b/services/webhook/matrix.go index 7ff8b1e638..bd3efd46b2 100644 --- a/services/webhook/matrix.go +++ b/services/webhook/matrix.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/matrix_test.go b/services/webhook/matrix_test.go index bbcdef3567..754234eccf 100644 --- a/services/webhook/matrix_test.go +++ b/services/webhook/matrix_test.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/msteams.go b/services/webhook/msteams.go index bf9e95edc5..ef8366f8d5 100644 --- a/services/webhook/msteams.go +++ b/services/webhook/msteams.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/msteams_test.go b/services/webhook/msteams_test.go index 8292beed7f..8daf99f867 100644 --- a/services/webhook/msteams_test.go +++ b/services/webhook/msteams_test.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/packagist.go b/services/webhook/packagist.go index 5badc7462a..815e1a93e9 100644 --- a/services/webhook/packagist.go +++ b/services/webhook/packagist.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/packagist_test.go b/services/webhook/packagist_test.go index 4a24b76523..4941ae3f01 100644 --- a/services/webhook/packagist_test.go +++ b/services/webhook/packagist_test.go @@ -1,6 +1,5 @@ // Copyright 2022 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/payloader.go b/services/webhook/payloader.go index a9d01c9891..7b04f1dd36 100644 --- a/services/webhook/payloader.go +++ b/services/webhook/payloader.go @@ -1,6 +1,5 @@ // Copyright 2020 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/slack.go b/services/webhook/slack.go index f5c69d74b6..1814361a1c 100644 --- a/services/webhook/slack.go +++ b/services/webhook/slack.go @@ -1,6 +1,5 @@ // Copyright 2014 The Gogs Authors. All rights reserved. -// Use of this source code is governed by a MIT-style -// license that can be found in the LICENSE file. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/slack_test.go b/services/webhook/slack_test.go index 3af38b5158..db97b351c5 100644 --- a/services/webhook/slack_test.go +++ b/services/webhook/slack_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/telegram.go b/services/webhook/telegram.go index 7ca5f61062..8bc68490e5 100644 --- a/services/webhook/telegram.go +++ b/services/webhook/telegram.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/telegram_test.go b/services/webhook/telegram_test.go index 5ca78d0508..b092f7e732 100644 --- a/services/webhook/telegram_test.go +++ b/services/webhook/telegram_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/webhook.go b/services/webhook/webhook.go index 342e764f4d..21173e7cd8 100644 --- a/services/webhook/webhook.go +++ b/services/webhook/webhook.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package webhook @@ -116,19 +115,26 @@ func handle(data ...queue.Data) []queue.Data { for _, taskID := range data { task, err := webhook_model.GetHookTaskByID(ctx, taskID.(int64)) if err != nil { - log.Error("GetHookTaskByID failed: %v", err) - } else { - if err := Deliver(ctx, task); err != nil { - log.Error("webhook.Deliver failed: %v", err) - } + log.Error("GetHookTaskByID[%d] failed: %v", taskID.(int64), err) + continue + } + + if task.IsDelivered { + // Already delivered in the meantime + log.Trace("Task[%d] has already been delivered", task.ID) + continue + } + + if err := Deliver(ctx, task); err != nil { + log.Error("Unable to deliver webhook task[%d]: %v", task.ID, err) } } return nil } -func enqueueHookTask(task *webhook_model.HookTask) error { - err := hookQueue.PushFunc(task.ID, nil) +func enqueueHookTask(taskID int64) error { + err := hookQueue.Push(taskID) if err != nil && err != queue.ErrAlreadyInQueue { return err } @@ -205,7 +211,7 @@ func PrepareWebhook(ctx context.Context, w *webhook_model.Webhook, event webhook return fmt.Errorf("CreateHookTask: %w", err) } - return enqueueHookTask(task) + return enqueueHookTask(task.ID) } // PrepareWebhooks adds new webhooks to task queue for given payload. @@ -224,7 +230,7 @@ func PrepareWebhooks(ctx context.Context, source EventSource, event webhook_mode } ws = append(ws, repoHooks...) - owner = source.Repository.MustOwner() + owner = source.Repository.MustOwner(ctx) } // check if owner is an org and append additional webhooks @@ -265,5 +271,5 @@ func ReplayHookTask(ctx context.Context, w *webhook_model.Webhook, uuid string) return err } - return enqueueHookTask(task) + return enqueueHookTask(task.ID) } diff --git a/services/webhook/webhook_test.go b/services/webhook/webhook_test.go index 8d44aa504a..a1f197d809 100644 --- a/services/webhook/webhook_test.go +++ b/services/webhook/webhook_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package webhook diff --git a/services/webhook/wechatwork.go b/services/webhook/wechatwork.go index 5344ccaa22..a77d871dd7 100644 --- a/services/webhook/wechatwork.go +++ b/services/webhook/wechatwork.go @@ -1,6 +1,5 @@ // 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. +// SPDX-License-Identifier: MIT package webhook @@ -139,7 +138,7 @@ func (f *WechatworkPayload) PullRequest(p *api.PullRequestPayload) (api.Payloade func (f *WechatworkPayload) Review(p *api.PullRequestPayload, event webhook_model.HookEventType) (api.Payloader, error) { var text, title string switch p.Action { - case api.HookIssueSynchronized: + case api.HookIssueReviewed: action, err := parseHookPullRequestEventType(event) if err != nil { return nil, err diff --git a/services/wiki/wiki.go b/services/wiki/wiki.go index f6986cff86..e483416fda 100644 --- a/services/wiki/wiki.go +++ b/services/wiki/wiki.go @@ -1,7 +1,6 @@ // Copyright 2015 The Gogs Authors. All rights reserved. // Copyright 2019 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. +// SPDX-License-Identifier: MIT package wiki diff --git a/services/wiki/wiki_test.go b/services/wiki/wiki_test.go index 774ef6c283..268d8848c5 100644 --- a/services/wiki/wiki_test.go +++ b/services/wiki/wiki_test.go @@ -1,6 +1,5 @@ // Copyright 2019 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. +// SPDX-License-Identifier: MIT package wiki diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml index 437bda87aa..25494bde23 100644 --- a/snap/snapcraft.yaml +++ b/snap/snapcraft.yaml @@ -1,5 +1,5 @@ name: gitea -summary: Gitea - A painless self-hosted Git service +summary: Gitea - A painless self-hosted Git service description: | The goal of this project is to make the easiest, fastest, and most painless way of setting up a self-hosted Git service. With Go, this can be done with @@ -39,7 +39,6 @@ apps: command: usr/bin/sqlite3 parts: - gitea: plugin: make source: . diff --git a/templates/admin/base/search.tmpl b/templates/admin/base/search.tmpl index 28bc478f6a..ae1a4d2ac5 100644 --- a/templates/admin/base/search.tmpl +++ b/templates/admin/base/search.tmpl @@ -6,12 +6,12 @@ {{svg "octicon-triangle-down" 14 "dropdown icon"}} diff --git a/templates/admin/emails/list.tmpl b/templates/admin/emails/list.tmpl index adf5b9bef7..f5f6a86dc8 100644 --- a/templates/admin/emails/list.tmpl +++ b/templates/admin/emails/list.tmpl @@ -15,10 +15,10 @@ {{svg "octicon-triangle-down" 14 "dropdown icon"}} diff --git a/templates/admin/hook_new.tmpl b/templates/admin/hook_new.tmpl index c5196fce4e..407eae9646 100644 --- a/templates/admin/hook_new.tmpl +++ b/templates/admin/hook_new.tmpl @@ -31,7 +31,7 @@ {{else if eq .HookType "feishu"}} {{else if eq .HookType "matrix"}} - + {{svg "gitea-matrix" 26}} {{else if eq .HookType "wechatwork"}} {{else if eq .HookType "packagist"}} diff --git a/templates/admin/navbar.tmpl b/templates/admin/navbar.tmpl index 1c8b12fc2f..cfd32b6484 100644 --- a/templates/admin/navbar.tmpl +++ b/templates/admin/navbar.tmpl @@ -1,45 +1,45 @@ -
+
{{if .PrimaryLanguage}} - - {{.PrimaryLanguage.Language}} + + {{.PrimaryLanguage.Language}} {{end}} {{if not $.DisableStars}} diff --git a/templates/explore/repo_search.tmpl b/templates/explore/repo_search.tmpl index b784722f50..cbce97268d 100644 --- a/templates/explore/repo_search.tmpl +++ b/templates/explore/repo_search.tmpl @@ -6,18 +6,18 @@ {{svg "octicon-triangle-down" 14 "dropdown icon"}}
diff --git a/templates/explore/search.tmpl b/templates/explore/search.tmpl index 123efa56dd..72dee41f0f 100644 --- a/templates/explore/search.tmpl +++ b/templates/explore/search.tmpl @@ -6,12 +6,12 @@ {{svg "octicon-triangle-down" 14 "dropdown icon"}} diff --git a/templates/home.tmpl b/templates/home.tmpl index 7667db27a1..87192fa55b 100644 --- a/templates/home.tmpl +++ b/templates/home.tmpl @@ -3,7 +3,7 @@
- +

diff --git a/templates/org/create.tmpl b/templates/org/create.tmpl index 999f5246a3..26c432303c 100644 --- a/templates/org/create.tmpl +++ b/templates/org/create.tmpl @@ -48,7 +48,6 @@ - {{.locale.Tr "cancel"}}

diff --git a/templates/org/home.tmpl b/templates/org/home.tmpl index 3ff86259d5..6474204493 100644 --- a/templates/org/home.tmpl +++ b/templates/org/home.tmpl @@ -5,7 +5,9 @@
{{.Org.DisplayName}} - {{svg "octicon-rss" 36}} + {{if .EnableFeed}} + {{svg "octicon-rss" 36}} + {{end}} {{if .Org.Visibility.IsLimited}}
{{.locale.Tr "org.settings.visibility.limited_shortname"}}
{{end}} {{if .Org.Visibility.IsPrivate}}
{{.locale.Tr "org.settings.visibility.private_shortname"}}
{{end}} @@ -14,7 +16,7 @@ {{if $.RenderedDescription}}

{{$.RenderedDescription|Str2html}}

{{end}}
{{if .Org.Location}}
{{svg "octicon-location"}} {{.Org.Location}}
{{end}} - {{if .Org.Website}}
{{svg "octicon-link"}} {{.Org.Website}}
{{end}} + {{if .Org.Website}}
{{svg "octicon-link"}} {{.Org.Website}}
{{end}}
@@ -68,8 +70,8 @@ {{end}} diff --git a/templates/org/settings/hook_new.tmpl b/templates/org/settings/hook_new.tmpl index 7308cafa20..081f5a2839 100644 --- a/templates/org/settings/hook_new.tmpl +++ b/templates/org/settings/hook_new.tmpl @@ -26,7 +26,7 @@ {{else if eq .HookType "feishu"}} {{else if eq .HookType "matrix"}} - + {{svg "gitea-matrix" 26}} {{else if eq .HookType "wechatwork"}} {{else if eq .HookType "packagist"}} diff --git a/templates/org/settings/navbar.tmpl b/templates/org/settings/navbar.tmpl index e7cbb87344..9ff30ae4ff 100644 --- a/templates/org/settings/navbar.tmpl +++ b/templates/org/settings/navbar.tmpl @@ -1,23 +1,28 @@
diff --git a/templates/org/settings/packages.tmpl b/templates/org/settings/packages.tmpl new file mode 100644 index 0000000000..bb5d95e107 --- /dev/null +++ b/templates/org/settings/packages.tmpl @@ -0,0 +1,14 @@ +{{template "base/head" .}} +
+ {{template "org/header" .}} +
+
+ {{template "org/settings/navbar" .}} +
+ {{template "base/alert" .}} + {{template "package/shared/cleanup_rules/list" .}} +
+
+
+
+{{template "base/footer" .}} diff --git a/templates/org/settings/packages_cleanup_rules_edit.tmpl b/templates/org/settings/packages_cleanup_rules_edit.tmpl new file mode 100644 index 0000000000..8c3725f4d7 --- /dev/null +++ b/templates/org/settings/packages_cleanup_rules_edit.tmpl @@ -0,0 +1,14 @@ +{{template "base/head" .}} +
+ {{template "org/header" .}} +
+
+ {{template "org/settings/navbar" .}} +
+ {{template "base/alert" .}} + {{template "package/shared/cleanup_rules/edit" .}} +
+
+
+
+{{template "base/footer" .}} diff --git a/templates/org/settings/packages_cleanup_rules_preview.tmpl b/templates/org/settings/packages_cleanup_rules_preview.tmpl new file mode 100644 index 0000000000..e0e4652c36 --- /dev/null +++ b/templates/org/settings/packages_cleanup_rules_preview.tmpl @@ -0,0 +1,13 @@ +{{template "base/head" .}} +
+ {{template "org/header" .}} +
+
+ {{template "org/settings/navbar" .}} +
+ {{template "package/shared/cleanup_rules/preview" .}} +
+
+
+
+{{template "base/footer" .}} diff --git a/templates/org/team/new.tmpl b/templates/org/team/new.tmpl index e5266f13c5..10b5abda31 100644 --- a/templates/org/team/new.tmpl +++ b/templates/org/team/new.tmpl @@ -99,17 +99,17 @@
- +
- +
- +
@@ -121,7 +121,7 @@ {{if lt $unit.MaxPerm 2}}
- + {{$.locale.Tr $unit.DescKey}}
@@ -134,7 +134,6 @@
{{if .PageIsOrgTeamsNew}} - {{.locale.Tr "cancel"}} {{else}} {{if not (eq .Team.LowerName "owners")}} diff --git a/templates/org/team/sidebar.tmpl b/templates/org/team/sidebar.tmpl index 5d952b501e..ab118a7e26 100644 --- a/templates/org/team/sidebar.tmpl +++ b/templates/org/team/sidebar.tmpl @@ -61,11 +61,11 @@ {{if and (lt $unit.MaxPerm 2) (not $unit.Type.UnitGlobalDisabled)}} {{$.locale.Tr $unit.NameKey}} - {{if eq ($.Team.UnitAccessMode $unit.Type) 0 -}} + {{if eq ($.Team.UnitAccessMode $.Context $unit.Type) 0 -}} {{$.locale.Tr "org.teams.none_access"}} - {{- else if or (eq $.Team.ID 0) (eq ($.Team.UnitAccessMode $unit.Type) 1) -}} + {{- else if or (eq $.Team.ID 0) (eq ($.Team.UnitAccessMode $.Context $unit.Type) 1) -}} {{$.locale.Tr "org.teams.read_access"}} - {{- else if eq ($.Team.UnitAccessMode $unit.Type) 2 -}} + {{- else if eq ($.Team.UnitAccessMode $.Context $unit.Type) 2 -}} {{$.locale.Tr "org.teams.write_access"}} {{- end}} diff --git a/templates/package/shared/cleanup_rules/edit.tmpl b/templates/package/shared/cleanup_rules/edit.tmpl new file mode 100644 index 0000000000..f8525afb70 --- /dev/null +++ b/templates/package/shared/cleanup_rules/edit.tmpl @@ -0,0 +1,73 @@ +

{{if .IsEditRule}}{{.locale.Tr "packages.owner.settings.cleanuprules.edit"}}{{else}}{{.locale.Tr "packages.owner.settings.cleanuprules.add"}}{{end}}

+
+
+ {{.CsrfTokenHtml}} + +
+
+ + +
+
+
+ + +
+
+
+ + +
+
+
+

{{.locale.Tr "packages.owner.settings.cleanuprules.keep.title"}}

+
+ + +
+
+ + +

{{.locale.Tr "packages.owner.settings.cleanuprules.keep.pattern.container" | Safe}}

+
+
+

{{.locale.Tr "packages.owner.settings.cleanuprules.remove.title"}}

+
+ + +
+
+ + +
+
+ {{if .IsEditRule}} + + + {{.locale.Tr "packages.owner.settings.cleanuprules.preview"}} + {{else}} + + {{end}} +
+
+
diff --git a/templates/package/shared/cleanup_rules/list.tmpl b/templates/package/shared/cleanup_rules/list.tmpl new file mode 100644 index 0000000000..09f95e4f4a --- /dev/null +++ b/templates/package/shared/cleanup_rules/list.tmpl @@ -0,0 +1,34 @@ +

+ {{.locale.Tr "packages.owner.settings.cleanuprules.title"}} + +

+
+
+ {{range .CleanupRules}} +
+ + {{svg .Type.SVGName 36}} +
+ {{.Type.Name}} +
{{if .Enabled}}{{$.locale.Tr "enabled"}}{{else}}{{$.locale.Tr "disabled"}}{{end}}
+ {{if .KeepCount}}
{{$.locale.Tr "packages.owner.settings.cleanuprules.keep.count"}}: {{if eq .KeepCount 1}}{{$.locale.Tr "packages.owner.settings.cleanuprules.keep.count.1"}}{{else}}{{$.locale.Tr "packages.owner.settings.cleanuprules.keep.count.n" .KeepCount}}{{end}}
{{end}} + {{if .KeepPattern}}
{{$.locale.Tr "packages.owner.settings.cleanuprules.keep.pattern"}}: {{EllipsisString .KeepPattern 100}}
{{end}} + {{if .RemoveDays}}
{{$.locale.Tr "packages.owner.settings.cleanuprules.remove.days"}}: {{$.locale.Tr "tool.days" .RemoveDays}}
{{end}} + {{if .RemovePattern}}
{{$.locale.Tr "packages.owner.settings.cleanuprules.remove.pattern"}}: {{EllipsisString .RemovePattern 100}}
{{end}} +
+
+ {{else}} +
{{.locale.Tr "packages.owner.settings.cleanuprules.none"}}
+ {{end}} +
+
diff --git a/templates/package/shared/cleanup_rules/preview.tmpl b/templates/package/shared/cleanup_rules/preview.tmpl new file mode 100644 index 0000000000..c59ad67f77 --- /dev/null +++ b/templates/package/shared/cleanup_rules/preview.tmpl @@ -0,0 +1,34 @@ +

{{.locale.Tr "packages.owner.settings.cleanuprules.preview"}}

+
+

{{.locale.Tr "packages.owner.settings.cleanuprules.preview.overview" (len .VersionsToRemove)}}

+
+
+ + + + + + + + + + + + + {{range .VersionsToRemove}} + + + + + + + + + {{else}} + + + + {{end}} + +
{{.locale.Tr "admin.packages.type"}}{{.locale.Tr "admin.packages.name"}}{{.locale.Tr "admin.packages.version"}}{{.locale.Tr "admin.packages.creator"}}{{.locale.Tr "admin.packages.size"}}{{.locale.Tr "admin.packages.published"}}
{{.Package.Type.Name}}{{.Package.Name}}{{.Version.Version}}{{.Creator.Name}}{{FileSize .CalculateBlobSize}}
{{.locale.Tr "packages.owner.settings.cleanuprules.preview.none"}}
+
diff --git a/templates/repo/blame.tmpl b/templates/repo/blame.tmpl index b697573d24..e4a10ee57d 100644 --- a/templates/repo/blame.tmpl +++ b/templates/repo/blame.tmpl @@ -1,14 +1,9 @@
-

-
-
-
- {{.NumLines}} {{.locale.TrN .NumLines "repo.line" "repo.lines"}} -
-
{{FileSize .FileSize}}
-
+

+
+ {{template "repo/file_info" .}}
-
+
{{.locale.Tr "repo.file_raw"}} {{if not .IsViewCommit}} diff --git a/templates/repo/branch/list.tmpl b/templates/repo/branch/list.tmpl index 2e1878acc8..abce6591bd 100644 --- a/templates/repo/branch/list.tmpl +++ b/templates/repo/branch/list.tmpl @@ -22,18 +22,18 @@ {{if and $.IsWriter (not $.Repository.IsArchived) (not .IsDeleted)}} -
+
+ {{end}} {{if not $.DisableDownloadSourceArchives}} - + {{end}} @@ -108,26 +108,30 @@ {{if and $.IsWriter (not $.Repository.IsArchived) (not .IsDeleted)}} -
+
+ {{end}} {{if and (not .IsDeleted) (not $.DisableDownloadSourceArchives)}} - + {{end}} {{if and $.IsWriter (not $.IsMirror) (not $.Repository.IsArchived) (not .IsProtected)}} {{if .IsDeleted}} - {{svg "octicon-reply"}} + {{else}} - + {{end}} {{end}} diff --git a/templates/repo/cite/cite_buttons.tmpl b/templates/repo/cite/cite_buttons.tmpl new file mode 100644 index 0000000000..0f4fb43484 --- /dev/null +++ b/templates/repo/cite/cite_buttons.tmpl @@ -0,0 +1,11 @@ + + + + + diff --git a/templates/repo/cite/cite_modal.tmpl b/templates/repo/cite/cite_modal.tmpl new file mode 100644 index 0000000000..185b34173d --- /dev/null +++ b/templates/repo/cite/cite_modal.tmpl @@ -0,0 +1,22 @@ + diff --git a/templates/repo/commit_page.tmpl b/templates/repo/commit_page.tmpl index 8ece768832..6a40d5fbee 100644 --- a/templates/repo/commit_page.tmpl +++ b/templates/repo/commit_page.tmpl @@ -26,10 +26,10 @@ {{.locale.Tr "repo.diff.browse_source"}} {{if and ($.Permission.CanWrite $.UnitTypeCode) (not $.Repository.IsArchived) (not .IsDeleted)}}{{- /* */ -}} -
diff --git a/templates/repo/issue/milestone_issues.tmpl b/templates/repo/issue/milestone_issues.tmpl index ba229cb5e8..f3e28208ad 100644 --- a/templates/repo/issue/milestone_issues.tmpl +++ b/templates/repo/issue/milestone_issues.tmpl @@ -108,11 +108,11 @@ {{svg "octicon-triangle-down" 14 "dropdown icon"}}
{{end}} @@ -124,12 +124,12 @@ {{svg "octicon-triangle-down" 14 "dropdown icon"}}

diff --git a/templates/repo/issue/milestones.tmpl b/templates/repo/issue/milestones.tmpl index 641dc6c918..3282e895eb 100644 --- a/templates/repo/issue/milestones.tmpl +++ b/templates/repo/issue/milestones.tmpl @@ -46,12 +46,12 @@ {{svg "octicon-triangle-down" 14 "dropdown icon"}}

diff --git a/templates/repo/issue/navbar.tmpl b/templates/repo/issue/navbar.tmpl index 9a963cd822..1e57679657 100644 --- a/templates/repo/issue/navbar.tmpl +++ b/templates/repo/issue/navbar.tmpl @@ -1,4 +1,4 @@ diff --git a/templates/repo/issue/openclose.tmpl b/templates/repo/issue/openclose.tmpl index ccfb40684c..758fc447ce 100644 --- a/templates/repo/issue/openclose.tmpl +++ b/templates/repo/issue/openclose.tmpl @@ -1,5 +1,5 @@ {{end}} - {{if .Repository.IsTimetrackerEnabled}} + {{if .Repository.IsTimetrackerEnabled $.Context}} {{if and .CanUseTimetracker (not .Repository.IsArchived)}}
@@ -389,7 +389,7 @@ {{avatar $user}}
- {{$user.DisplayName}} + {{template "shared/user/authorlink" $user}}
{{$trackedtime}}
@@ -444,7 +444,7 @@ {{end}}
- {{if .Repository.IsDependenciesEnabled}} + {{if .Repository.IsDependenciesEnabled $.Context}}
diff --git a/templates/repo/migrate/codebase.tmpl b/templates/repo/migrate/codebase.tmpl index 20341e5768..0f9b377f21 100644 --- a/templates/repo/migrate/codebase.tmpl +++ b/templates/repo/migrate/codebase.tmpl @@ -107,7 +107,6 @@ - {{.locale.Tr "cancel"}}
diff --git a/templates/repo/migrate/git.tmpl b/templates/repo/migrate/git.tmpl index 612116f402..1ef031ee1f 100644 --- a/templates/repo/migrate/git.tmpl +++ b/templates/repo/migrate/git.tmpl @@ -81,7 +81,6 @@ - {{.locale.Tr "cancel"}}
diff --git a/templates/repo/migrate/gitbucket.tmpl b/templates/repo/migrate/gitbucket.tmpl index 06912b27f5..5e6b3b4528 100644 --- a/templates/repo/migrate/gitbucket.tmpl +++ b/templates/repo/migrate/gitbucket.tmpl @@ -123,7 +123,6 @@ - {{.locale.Tr "cancel"}}
diff --git a/templates/repo/migrate/gitea.tmpl b/templates/repo/migrate/gitea.tmpl index 3bc6156316..f56f9df5ec 100644 --- a/templates/repo/migrate/gitea.tmpl +++ b/templates/repo/migrate/gitea.tmpl @@ -119,7 +119,6 @@ - {{.locale.Tr "cancel"}} diff --git a/templates/repo/migrate/github.tmpl b/templates/repo/migrate/github.tmpl index a5b1f19506..c4249f8904 100644 --- a/templates/repo/migrate/github.tmpl +++ b/templates/repo/migrate/github.tmpl @@ -121,7 +121,6 @@ - {{.locale.Tr "cancel"}} diff --git a/templates/repo/migrate/gitlab.tmpl b/templates/repo/migrate/gitlab.tmpl index fa68cee891..a959833e96 100644 --- a/templates/repo/migrate/gitlab.tmpl +++ b/templates/repo/migrate/gitlab.tmpl @@ -118,7 +118,6 @@ - {{.locale.Tr "cancel"}} diff --git a/templates/repo/migrate/gogs.tmpl b/templates/repo/migrate/gogs.tmpl index 01936e028b..6d331b9e8f 100644 --- a/templates/repo/migrate/gogs.tmpl +++ b/templates/repo/migrate/gogs.tmpl @@ -121,7 +121,6 @@ - {{.locale.Tr "cancel"}} diff --git a/templates/repo/migrate/onedev.tmpl b/templates/repo/migrate/onedev.tmpl index e411d47760..18256aca5d 100644 --- a/templates/repo/migrate/onedev.tmpl +++ b/templates/repo/migrate/onedev.tmpl @@ -107,7 +107,6 @@ - {{.locale.Tr "cancel"}} diff --git a/templates/repo/projects/list.tmpl b/templates/repo/projects/list.tmpl index 9e265f9a91..274734f515 100644 --- a/templates/repo/projects/list.tmpl +++ b/templates/repo/projects/list.tmpl @@ -31,9 +31,9 @@ {{svg "octicon-triangle-down" 14 "dropdown icon"}} diff --git a/templates/repo/pulls/fork.tmpl b/templates/repo/pulls/fork.tmpl index 0172e1b708..28ba8e2e25 100644 --- a/templates/repo/pulls/fork.tmpl +++ b/templates/repo/pulls/fork.tmpl @@ -61,7 +61,6 @@ - {{.locale.Tr "cancel"}} diff --git a/templates/repo/release/list.tmpl b/templates/repo/release/list.tmpl index 6abb240cc3..f8c54bf7f6 100644 --- a/templates/repo/release/list.tmpl +++ b/templates/repo/release/list.tmpl @@ -5,10 +5,10 @@ {{template "base/alert" .}} {{if (and .CanCreateRelease (not .PageIsTagList))}} @@ -36,21 +36,21 @@ @@ -69,19 +69,10 @@ {{if .IsTag}} {{if .CreatedUnix}}{{TimeSinceUnix .CreatedUnix $.locale}}{{end}} {{else}} - {{if .IsDraft}} - {{$.locale.Tr "repo.release.draft"}} - {{else if .IsPrerelease}} - {{$.locale.Tr "repo.release.prerelease"}} - {{else}} - {{$.locale.Tr "repo.release.stable"}} - {{end}} - - {{svg "octicon-tag" 16 "mr-2"}}{{.TagName}} - + {{svg "octicon-tag" 16 "mr-2"}}{{.TagName}} {{if .Sha1}} - {{svg "octicon-git-commit" 16 "mr-2"}}{{ShortSha .Sha1}} + {{svg "octicon-git-commit" 16 "mr-2"}}{{ShortSha .Sha1}} {{template "repo/branch_dropdown" dict "root" $ "release" .}} {{end}} @@ -89,36 +80,56 @@
{{if .IsTag}} -

- {{svg "octicon-tag" 16 "mr-2"}}{{.TagName}} -

+

{{if gt .Publisher.ID 0}} {{avatar .Publisher 20}} {{.Publisher.Name}} + + {{$.locale.Tr "repo.released_this"}} + + {{if .CreatedUnix}} + {{TimeSinceUnix .CreatedUnix $.locale}} + {{end}} + | {{end}} {{$.locale.Tr "repo.release.ahead.commits" .NumCommitsBehind | Str2html}} {{$.locale.Tr "repo.release.ahead.target" $.DefaultBranch}}

{{else}} -

- {{.Title}} - {{if $.CanCreateRelease}} - - ({{$.locale.Tr "repo.release.edit"}}) - - {{end}} -

+
+

+ {{.Title}} + {{if .IsDraft}} + {{$.locale.Tr "repo.release.draft"}} + {{else if .IsPrerelease}} + {{$.locale.Tr "repo.release.prerelease"}} + {{else if not .IsTag}} + {{$.locale.Tr "repo.release.stable"}} + {{end}} +

+
+ {{if $.CanCreateRelease}} + + {{svg "octicon-pencil"}} + + {{end}} +
+

{{if .OriginalAuthor}} diff --git a/templates/repo/settings/collaboration.tmpl b/templates/repo/settings/collaboration.tmpl index 342b260db6..2f932b4c39 100644 --- a/templates/repo/settings/collaboration.tmpl +++ b/templates/repo/settings/collaboration.tmpl @@ -74,7 +74,7 @@ {{if or (eq .AccessMode 1) (eq .AccessMode 2)}} {{$first := true}}

- Sections: {{range $u, $unit := $.Units}}{{if and ($.Repo.UnitEnabled $unit.Type) ($team.UnitEnabled $unit.Type)}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{$.locale.Tr $unit.NameKey}}{{end}}{{end}} {{if $first}}None{{end}} + Sections: {{range $u, $unit := $.Units}}{{if and ($.Repo.UnitEnabled $.Context $unit.Type) ($team.UnitEnabled $.Context $unit.Type)}}{{if $first}}{{$first = false}}{{else}}, {{end}}{{$.locale.Tr $unit.NameKey}}{{end}}{{end}} {{if $first}}None{{end}}
{{end}}
diff --git a/templates/repo/settings/githooks.tmpl b/templates/repo/settings/githooks.tmpl index 893f52f188..9fa396c8d5 100644 --- a/templates/repo/settings/githooks.tmpl +++ b/templates/repo/settings/githooks.tmpl @@ -13,10 +13,10 @@ {{.locale.Tr "repo.settings.githooks_desc" | Str2html}} {{range .Hooks}} -
- {{svg "octicon-dot-fill"}} - {{.Name}} - + diff --git a/templates/repo/settings/navbar.tmpl b/templates/repo/settings/navbar.tmpl index 2a9202cf40..e2b741b8d0 100644 --- a/templates/repo/settings/navbar.tmpl +++ b/templates/repo/settings/navbar.tmpl @@ -1,34 +1,34 @@