Merge remote-tracking branch 'upstream/main'

This commit is contained in:
Anthony Wang 2022-06-25 21:40:28 -05:00
commit 786ee03f57
Signed by: a
GPG key ID: BC96B00AEC5F2D76
231 changed files with 1168 additions and 558 deletions

2
.gitattributes vendored
View file

@ -1,7 +1,5 @@
* text=auto eol=lf
*.tmpl linguist-language=Handlebars
/.eslintrc linguist-language=YAML
/.stylelintrc linguist-language=YAML
/public/vendor/** -text -eol linguist-vendored
/vendor/** -text -eol linguist-vendored
/web_src/fomantic/build/** linguist-generated

View file

@ -19,6 +19,11 @@ linters:
- revive
- gofumpt
- depguard
- nakedret
- unconvert
- wastedassign
- nolintlint
- stylecheck
enable-all: false
disable-all: true
fast: false
@ -32,6 +37,10 @@ run:
- web_src
linters-settings:
stylecheck:
checks: ["all", "-ST1005", "-ST1003"]
nakedret:
max-func-lines: 0
gocritic:
disabled-checks:
- ifElseChain

View file

@ -4,6 +4,25 @@ This changelog goes through all the changes that have been made in each release
without substantial changes to our git log; to see the highlights of what has
been added to each release, please refer to the [blog](https://blog.gitea.io).
## [1.16.9](https://github.com/go-gitea/gitea/releases/tag/v1.16.9) - 2022-06-21
* BUGFIXES
* Release page show all tags in compare dropdown (#20070) (#20071)
* Fix permission check for delete tag (#19985) (#20001)
* Only log non ErrNotExist errors in git.GetNote (#19884) (#19905)
* Use exact search instead of fuzzy search for branch filter dropdown (#19885) (#19893)
* Set Setpgid on child git processes (#19865) (#19881)
* Import git from alpine 3.16 repository as 2.30.4 is needed for `safe.directory = '*'` to work but alpine 3.13 has 2.30.3 (#19876)
* Ensure responses are context.ResponseWriters (#19843) (#19859)
* Fix incorrect usage of `Count` function (#19850)
* Fix raw endpoint PDF file headers (#19825) (#19826)
* Make WIP prefixes case insensitive, e.g. allow `Draft` as a WIP prefix (#19780) (#19811)
* Don't return 500 on NotificationUnreadCount (#19802)
* Prevent NPE when cache service is disabled (#19703) (#19783)
* Detect truncated utf-8 characters at the end of content as still representing utf-8 (#19773) (#19774)
* Fix doctor pq: syntax error at or near "." quote user table name (#19765) (#19770)
* Fix bug with assigneees (#19757)
## [1.16.8](https://github.com/go-gitea/gitea/releases/tag/v1.16.8) - 2022-05-16
* ENHANCEMENTS

View file

@ -3,8 +3,76 @@
The Gitea maintainers take security seriously.
If you discover a security issue, please bring it to their attention right away!
### Reporting a Vulnerability
## Reporting a Vulnerability
Please **DO NOT** file a public issue, instead send your report privately to `security@gitea.io`.
## Protecting Security Information
Due to the sensitive nature of security information, you can use below GPG public key encrypt your mail body.
The PGP key is valid until June 24, 2024.
Key ID: 6FCD2D5B
Key Type: RSA
Expires: 6/24/2024
Key Size: 4096/4096
Fingerprint: 3DE0 3D1E 144A 7F06 9359 99DC AAFD 2381 6FCD 2D5B
UserID: Gitea Security <security@gitea.io>
```
-----BEGIN PGP PUBLIC KEY BLOCK-----
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
zgS/ZdziCvdAutqnGA==
=gZWO
-----END PGP PUBLIC KEY BLOCK-----
```
Security reports are greatly appreciated and we will publicly thank you for it, although we keep your name confidential if you request it.

View file

@ -792,7 +792,7 @@ func writeDataPktLine(out io.Writer, data []byte) error {
if err != nil {
return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
}
if 4 != lr {
if lr != 4 {
return fail("Internal Server Error", "Pkt-Line response failed: %v", err)
}

View file

@ -174,6 +174,18 @@ var (
Action: runAddSMTPLogger,
},
},
}, {
Name: "log-sql",
Usage: "Set LogSQL",
Flags: []cli.Flag{
cli.BoolFlag{
Name: "debug",
}, cli.BoolFlag{
Name: "off",
Usage: "Switch off SQL logging",
},
},
Action: runSetLogSQL,
},
},
}
@ -381,3 +393,18 @@ func runReleaseReopenLogging(c *cli.Context) error {
fmt.Fprintln(os.Stdout, msg)
return nil
}
func runSetLogSQL(c *cli.Context) error {
ctx, cancel := installSignals()
defer cancel()
setup("manager", c.Bool("debug"))
statusCode, msg := private.SetLogSQL(ctx, !c.Bool("off"))
switch statusCode {
case http.StatusInternalServerError:
return fail("InternalServerError", msg)
}
fmt.Fprintln(os.Stdout, msg)
return nil
}

View file

@ -1097,6 +1097,9 @@ PATH =
;; Number of items that are displayed in home feed
;FEED_PAGING_NUM = 20
;;
;; Number of items that are displayed in a single subsitemap
;SITEMAP_PAGING_NUM = 20
;;
;; Number of maximum commits displayed in commit graph.
;GRAPH_MAX_COMMIT_NUM = 100
;;
@ -2249,27 +2252,27 @@ PATH =
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;
;; Enable/Disable federation capabilities
; ENABLED = true
;ENABLED = false
;;
;; Enable/Disable user statistics for nodeinfo if federation is enabled
; SHARE_USER_STATISTICS = true
;SHARE_USER_STATISTICS = true
;;
;; Maximum federation request and response size (MB)
; MAX_SIZE = 4
;MAX_SIZE = 4
;;
;; WARNING: Changing the settings below can break federation.
;;
;; HTTP signature algorithms
; ALGORITHMS = rsa-sha256, rsa-sha512, ed25519
;ALGORITHMS = rsa-sha256, rsa-sha512, ed25519
;;
;; HTTP signature digest algorithm
; DIGEST_ALGORITHM = SHA-256
;DIGEST_ALGORITHM = SHA-256
;;
;; GET headers for federation requests
; GET_HEADERS = (request-target), Date
;GET_HEADERS = (request-target), Date
;;
;; POST headers for federation requests
; POST_HEADERS = (request-target), Date, Digest
;POST_HEADERS = (request-target), Date, Digest
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

View file

@ -18,7 +18,7 @@ params:
description: Git with a cup of tea
author: The Gitea Authors
website: https://docs.gitea.io
version: 1.16.8
version: 1.16.9
minGoVersion: 1.18
goVersion: 1.18
minNodeVersion: 14

View file

@ -174,6 +174,7 @@ The following configuration set `Content-Type: application/vnd.android.package-a
- `MEMBERS_PAGING_NUM`: **20**: Number of members that are shown in organization members.
- `FEED_MAX_COMMIT_NUM`: **5**: Number of maximum commits shown in one activity feed.
- `FEED_PAGING_NUM`: **20**: Number of items that are displayed in home feed.
- `SITEMAP_PAGING_NUM`: **20**: Number of items that are displayed in a single subsitemap.
- `GRAPH_MAX_COMMIT_NUM`: **100**: Number of maximum commits shown in the commit graph.
- `CODE_COMMENT_LINES`: **4**: Number of line of codes shown for a code comment.
- `DEFAULT_THEME`: **auto**: \[auto, gitea, arc-green\]: Set the default theme for the Gitea install.
@ -1088,7 +1089,7 @@ Task queue configuration has been moved to `queue.task`. However, the below conf
## Federation (`federation`)
- `ENABLED`: **true**: Enable/Disable federation capabilities
- `ENABLED`: **false**: Enable/Disable federation capabilities
- `SHARE_USER_STATISTICS`: **true**: Enable/Disable user statistics for nodeinfo if federation is enabled
- `MAX_SIZE`: **4**: Maximum federation request and response size (MB)

View file

@ -41,13 +41,13 @@ To use the Authorization Code Grant as a third party application it is required
## Scopes
Currently Gitea does not support scopes (see [#4300](https://github.com/go-gitea/gitea/issues/4300)) and all third party applications will be granted access to all resources of the user and his/her organizations.
Currently Gitea does not support scopes (see [#4300](https://github.com/go-gitea/gitea/issues/4300)) and all third party applications will be granted access to all resources of the user and their organizations.
## Example
**Note:** This example does not use PKCE.
1. Redirect to user to the authorization endpoint in order to get his/her consent for accessing the resources:
1. Redirect to user to the authorization endpoint in order to get their consent for accessing the resources:
```curl
https://[YOUR-GITEA-URL]/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI& response_type=code&state=STATE

View file

@ -46,7 +46,7 @@ Gitea 支援作為 OAuth2 提供者,能讓第三方程式能在使用者同意
**備註:** 此範例未使用 PKCE。
1. 重新導向使用者到 authorization endpoint 以獲得他同意授權存取資源:
<!-- 1. Redirect to user to the authorization endpoint in order to get his/her consent for accessing the resources: -->
<!-- 1. Redirect to user to the authorization endpoint in order to get their consent for accessing the resources: -->
```curl
https://[YOUR-GITEA-URL]/login/oauth/authorize?client_id=CLIENT_ID&redirect_uri=REDIRECT_URI& response_type=code&state=STATE

View file

@ -20,10 +20,26 @@ menu:
**NOTE:** When asking for support, it may be a good idea to have the following available so that the person helping has all the info they need:
1. Your `app.ini` (with any sensitive data scrubbed as necessary)
2. The `gitea.log` (and any other appropriate log files for the situation)
* e.g. If the error is related to the database, the `xorm.log` might be helpful
3. Any error messages you are seeing
1. Your `app.ini` (with any sensitive data scrubbed as necessary).
2. The Gitea logs, and any other appropriate log files for the situation.
* The logs are likely to be outputted to console. If you need to collect logs from files,
you could copy the following config into your `app.ini` (remove all other `[log]` sections),
then you can find the `*.log` files in Gitea's log directory (default: `%(GITEA_WORK_DIR)/log`).
```ini
; To show all SQL logs, you can also set LOG_SQL=true in the [database] section
[log]
LEVEL=debug
MODE=console,file
ROUTER=console,file
XORM=console,file
ENABLE_XORM_LOG=true
FILE_NAME=gitea.log
[log.file.router]
FILE_NAME=router.log
[log.file.xorm]
FILE_NAME=xorm.log
```
3. Any error messages you are seeing.
4. When possible, try to replicate the issue on [try.gitea.io](https://try.gitea.io) and include steps so that others can reproduce the issue.
* This will greatly improve the chance that the root of the issue can be quickly discovered and resolved.
5. If you meet slow/hanging/deadlock problems, please report the stack trace when the problem occurs:

View file

@ -85,7 +85,7 @@ Possible directory names for issue templates:
- `.gitlab/ISSUE_TEMPLATE`
- `.gitlab/issue_template`
Inside the directory can be multiple issue templates with the form
Inside the directory can be multiple markdown (`.md`) issue templates of the form
```md
---

View file

@ -67,7 +67,7 @@ Different from individual repositories, the owner of organization repositories a
A team in an organization has unit permissions settings. It can have members and repositories scope. A team could access all the repositories in this organization or special repositories changed by the owner team. A team could also be allowed to create new
repositories.
The owner team will be created when the organization created and the creator will become the first member of the owner team.
Notice Gitea will not allow a people is a member of organization but not in any team. The owner team could not be deleted and only
members of owner team could create a new team. Admin team could be created to manage some of repositories, members of admin team
could do anything with these repositories. Generate team could be created by the owner team to do the permissions allowed operations.
The owner team will be created when the organization is created, and the creator will become the first member of the owner team.
Every member of an organization must be in at least one team. The owner team cannot be deleted and only
members of the owner team can create a new team. An admin team can be created to manage some of the repositories, whose members can do anything with these repositories.
The Generate team can be created by the owner team to do the operations allowed by their permissions.

View file

@ -88,8 +88,8 @@ server {
listen 80;
server_name git.example.com;
location /_/static/assets {
alias /path/to/gitea/public;
location /_/static/assets/ {
alias /path/to/gitea/public/;
}
location / {
@ -120,8 +120,8 @@ server {
listen 80;
server_name cdn.example.com;
location /gitea {
alias /path/to/gitea/public;
location /gitea/ {
alias /path/to/gitea/public/;
}
location / {
@ -362,4 +362,4 @@ gitea:
- "traefik.http.services.gitea-websecure.loadbalancer.server.port=3000"
```
This config assumes that you are handling HTTPS on the traefik side and using HTTP between Gitea and traefik.
This config assumes that you are handling HTTPS on the traefik side and using HTTP between Gitea and traefik.

View file

@ -15,18 +15,21 @@ import (
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/activitypub"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/routers"
ap "github.com/go-ap/activitypub"
"github.com/stretchr/testify/assert"
)
func TestActivityPubPerson(t *testing.T) {
onGiteaRun(t, func(*testing.T, *url.URL) {
setting.Federation.Enabled = true
defer func() {
setting.Federation.Enabled = false
}()
setting.Federation.Enabled = true
c = routers.NormalRoutes()
defer func() {
setting.Federation.Enabled = false
c = routers.NormalRoutes()
}()
onGiteaRun(t, func(*testing.T, *url.URL) {
username := "user2"
req := NewRequestf(t, "GET", fmt.Sprintf("/api/v1/activitypub/user/%s", username))
resp := MakeRequest(t, req, http.StatusOK)
@ -56,12 +59,14 @@ func TestActivityPubPerson(t *testing.T) {
}
func TestActivityPubMissingPerson(t *testing.T) {
onGiteaRun(t, func(*testing.T, *url.URL) {
setting.Federation.Enabled = true
defer func() {
setting.Federation.Enabled = false
}()
setting.Federation.Enabled = true
c = routers.NormalRoutes()
defer func() {
setting.Federation.Enabled = false
c = routers.NormalRoutes()
}()
onGiteaRun(t, func(*testing.T, *url.URL) {
req := NewRequestf(t, "GET", "/api/v1/activitypub/user/nonexistentuser")
resp := MakeRequest(t, req, http.StatusNotFound)
assert.Contains(t, resp.Body.String(), "user redirect does not exist")
@ -69,15 +74,20 @@ func TestActivityPubMissingPerson(t *testing.T) {
}
func TestActivityPubPersonInbox(t *testing.T) {
setting.Federation.Enabled = true
c = routers.NormalRoutes()
defer func() {
setting.Federation.Enabled = false
c = routers.NormalRoutes()
}()
srv := httptest.NewServer(c)
defer srv.Close()
onGiteaRun(t, func(*testing.T, *url.URL) {
appURL := setting.AppURL
setting.Federation.Enabled = true
setting.AppURL = srv.URL
defer func() {
setting.Federation.Enabled = false
setting.Database.LogSQL = false
setting.AppURL = appURL
}()

View file

@ -38,7 +38,7 @@ func TestAPIListStopWatches(t *testing.T) {
assert.EqualValues(t, issue.Title, apiWatches[0].IssueTitle)
assert.EqualValues(t, repo.Name, apiWatches[0].RepoName)
assert.EqualValues(t, repo.OwnerName, apiWatches[0].RepoOwnerName)
assert.Greater(t, int64(apiWatches[0].Seconds), int64(0))
assert.Greater(t, apiWatches[0].Seconds, int64(0))
}
}

View file

@ -11,17 +11,20 @@ import (
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/routers"
"github.com/stretchr/testify/assert"
)
func TestNodeinfo(t *testing.T) {
onGiteaRun(t, func(*testing.T, *url.URL) {
setting.Federation.Enabled = true
defer func() {
setting.Federation.Enabled = false
}()
setting.Federation.Enabled = true
c = routers.NormalRoutes()
defer func() {
setting.Federation.Enabled = false
c = routers.NormalRoutes()
}()
onGiteaRun(t, func(*testing.T, *url.URL) {
req := NewRequestf(t, "GET", "/api/v1/nodeinfo")
resp := MakeRequest(t, req, http.StatusOK)
var nodeinfo api.NodeInfo

View file

@ -88,7 +88,7 @@ func TestPackageContainer(t *testing.T) {
req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL))
addTokenAuthHeader(req, anonymousToken)
resp = MakeRequest(t, req, http.StatusOK)
MakeRequest(t, req, http.StatusOK)
})
t.Run("User", func(t *testing.T) {
@ -112,7 +112,7 @@ func TestPackageContainer(t *testing.T) {
req = NewRequest(t, "GET", fmt.Sprintf("%sv2", setting.AppURL))
addTokenAuthHeader(req, userToken)
resp = MakeRequest(t, req, http.StatusOK)
MakeRequest(t, req, http.StatusOK)
})
})

View file

@ -82,7 +82,7 @@ func TestCreateFileOnProtectedBranch(t *testing.T) {
"_csrf": csrf,
"protected": "off",
})
resp = session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusSeeOther)
// Check if master branch has been locked successfully
flashCookie = session.GetCookie("macaron_flash")
assert.NotNil(t, flashCookie)
@ -109,7 +109,7 @@ func testEditFile(t *testing.T, session *TestSession, user, repo, branch, filePa
"commit_choice": "direct",
},
)
resp = session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusSeeOther)
// Verify the change
req = NewRequest(t, "GET", path.Join(user, repo, "raw/branch", branch, filePath))
@ -139,7 +139,7 @@ func testEditFileToNewBranch(t *testing.T, session *TestSession, user, repo, bra
"new_branch_name": targetBranch,
},
)
resp = session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusSeeOther)
// Verify the change
req = NewRequest(t, "GET", path.Join(user, repo, "raw/branch", targetBranch, filePath))

View file

@ -150,7 +150,7 @@ func standardCommitAndPushTest(t *testing.T, dstPath string) (little, big string
defer PrintCurrentTest(t)()
little, big = commitAndPushTest(t, dstPath, "data-file-")
})
return
return little, big
}
func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS string) {
@ -191,7 +191,7 @@ func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS strin
lockTest(t, dstPath)
})
})
return
return littleLFS, bigLFS
}
func commitAndPushTest(t *testing.T, dstPath, prefix string) (little, big string) {
@ -210,7 +210,7 @@ func commitAndPushTest(t *testing.T, dstPath, prefix string) (little, big string
big = doCommitAndPush(t, bigSize, dstPath, prefix)
})
})
return
return little, big
}
func rawTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS string) {

View file

@ -438,7 +438,7 @@ func getTokenForLoggedInUser(t testing.TB, session *TestSession) string {
"_csrf": doc.GetCSRF(),
"name": fmt.Sprintf("api-testing-token-%d", tokenCounter),
})
resp = session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", "/user/settings/applications")
resp = session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)

View file

@ -10,11 +10,13 @@ PASSWD = {{TEST_MSSQL_PASSWORD}}
SSL_MODE = disable
[indexer]
ISSUE_INDEXER_PATH = integrations/gitea-integration-mssql/indexers/issues.bleve
ISSUE_INDEXER_QUEUE_DIR = integrations/gitea-integration-mssql/indexers/issues.queue
REPO_INDEXER_ENABLED = true
REPO_INDEXER_PATH = integrations/gitea-integration-mssql/indexers/repos.bleve
[queue.issue_indexer]
PATH = integrations/gitea-integration-mssql/indexers/issues.bleve
DATADIR = integrations/gitea-integration-mssql/indexers/issues.queue
[queue]
TYPE = immediate

View file

@ -10,12 +10,14 @@ PASSWD = {{TEST_MYSQL_PASSWORD}}
SSL_MODE = disable
[indexer]
ISSUE_INDEXER_TYPE = elasticsearch
ISSUE_INDEXER_CONN_STR = http://elastic:changeme@elasticsearch:9200
ISSUE_INDEXER_QUEUE_DIR = integrations/gitea-integration-mysql/indexers/issues.queue
REPO_INDEXER_ENABLED = true
REPO_INDEXER_PATH = integrations/gitea-integration-mysql/indexers/repos.bleve
[queue.issue_indexer]
TYPE = elasticsearch
CONN_STR = http://elastic:changeme@elasticsearch:9200
DATADIR = integrations/gitea-integration-mysql/indexers/issues.queue
[queue]
TYPE = immediate

View file

@ -10,11 +10,13 @@ PASSWD = {{TEST_MYSQL8_PASSWORD}}
SSL_MODE = disable
[indexer]
ISSUE_INDEXER_PATH = integrations/gitea-integration-mysql8/indexers/issues.bleve
ISSUE_INDEXER_QUEUE_DIR = integrations/gitea-integration-mysql8/indexers/issues.queue
REPO_INDEXER_ENABLED = true
REPO_INDEXER_PATH = integrations/gitea-integration-mysql8/indexers/repos.bleve
[queue.issue_indexer]
PATH = integrations/gitea-integration-mysql8/indexers/issues.bleve
DATADIR = integrations/gitea-integration-mysql8/indexers/issues.queue
[queue]
TYPE = immediate

View file

@ -26,7 +26,7 @@ func testSrcRouteRedirect(t *testing.T, session *TestSession, user, repo, route,
// Perform redirect
req = NewRequest(t, "GET", location)
resp = session.MakeRequest(t, req, expectedStatus)
session.MakeRequest(t, req, expectedStatus)
}
func setDefaultBranch(t *testing.T, session *TestSession, user, repo, branch string) {

View file

@ -197,7 +197,7 @@ func TestAccessTokenExchangeWithBasicAuth(t *testing.T) {
"code_verifier": "N1Zo9-8Rfwhkt68r1r29ty8YwIraXR8eh_1Qwxg7yQXsonBt", // test PKCE additionally
})
req.Header.Add("Authorization", "Basic ZGE3ZGEzYmEtOWExMy00MTY3LTg1NmYtMzg5OWRlMGIwMTM4OmJsYWJsYQ==")
resp = MakeRequest(t, req, http.StatusBadRequest)
MakeRequest(t, req, http.StatusBadRequest)
// missing header
req = NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{
@ -206,7 +206,7 @@ func TestAccessTokenExchangeWithBasicAuth(t *testing.T) {
"code": "authcode",
"code_verifier": "N1Zo9-8Rfwhkt68r1r29ty8YwIraXR8eh_1Qwxg7yQXsonBt", // test PKCE additionally
})
resp = MakeRequest(t, req, http.StatusBadRequest)
MakeRequest(t, req, http.StatusBadRequest)
}
func TestRefreshTokenInvalidation(t *testing.T) {

View file

@ -11,11 +11,13 @@ SCHEMA = {{TEST_PGSQL_SCHEMA}}
SSL_MODE = disable
[indexer]
ISSUE_INDEXER_PATH = integrations/gitea-integration-pgsql/indexers/issues.bleve
ISSUE_INDEXER_QUEUE_DIR = integrations/gitea-integration-pgsql/indexers/issues.queue
REPO_INDEXER_ENABLED = true
REPO_INDEXER_PATH = integrations/gitea-integration-pgsql/indexers/repos.bleve
[queue.issue_indexer]
PATH = integrations/gitea-integration-pgsql/indexers/issues.bleve
DATADIR = integrations/gitea-integration-pgsql/indexers/issues.queue
[queue]
TYPE = immediate

View file

@ -45,7 +45,7 @@ func testRepoFork(t *testing.T, session *TestSession, ownerName, repoName, forkO
"uid": fmt.Sprintf("%d", forkOwner.ID),
"repo_name": forkRepoName,
})
resp = session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusSeeOther)
// Step4: check the existence of the forked repo
req = NewRequestf(t, "GET", "/%s/%s", forkOwnerName, forkRepoName)

View file

@ -46,7 +46,7 @@ func testRepoGenerate(t *testing.T, session *TestSession, templateOwnerName, tem
"repo_name": generateRepoName,
"git_content": "true",
})
resp = session.MakeRequest(t, req, http.StatusSeeOther)
session.MakeRequest(t, req, http.StatusSeeOther)
// Step4: check the existence of the generated repo
req = NewRequestf(t, "GET", "/%s/%s", generateOwnerName, generateRepoName)

View file

@ -6,11 +6,13 @@ DB_TYPE = sqlite3
PATH = integrations/gitea-integration-sqlite/gitea.db
[indexer]
ISSUE_INDEXER_PATH = integrations/gitea-integration-sqlite/indexers/issues.bleve
ISSUE_INDEXER_QUEUE_DIR = integrations/gitea-integration-sqlite/indexers/issues.queue
REPO_INDEXER_ENABLED = true
REPO_INDEXER_PATH = integrations/gitea-integration-sqlite/indexers/repos.bleve
[queue.issue_indexer]
PATH = integrations/gitea-integration-sqlite/indexers/issues.bleve
DATADIR = integrations/gitea-integration-sqlite/indexers/issues.queue
[queue]
TYPE = immediate

View file

@ -245,6 +245,6 @@ func TestListStopWatches(t *testing.T) {
assert.EqualValues(t, issue.Title, apiWatches[0].IssueTitle)
assert.EqualValues(t, repo.Name, apiWatches[0].RepoName)
assert.EqualValues(t, repo.OwnerName, apiWatches[0].RepoOwnerName)
assert.Greater(t, int64(apiWatches[0].Seconds), int64(0))
assert.Greater(t, apiWatches[0].Seconds, int64(0))
}
}

View file

@ -459,7 +459,7 @@ func DeleteOldActions(olderThan time.Duration) (err error) {
}
_, err = db.GetEngine(db.DefaultContext).Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Action{})
return
return err
}
func notifyWatchers(ctx context.Context, actions ...*Action) error {

View file

@ -142,5 +142,5 @@ func DeleteOldSystemNotices(olderThan time.Duration) (err error) {
}
_, err = db.GetEngine(db.DefaultContext).Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Notice{})
return
return err
}

View file

@ -520,5 +520,5 @@ func CalculateTrustStatus(verification *CommitVerification, repoTrustModel repo_
}
}
return
return err
}

View file

@ -317,7 +317,7 @@ func TestFromOpenSSH(t *testing.T) {
td := t.TempDir()
data := []byte("hello, ssh world")
dataPath := write(t, []byte(data), td, "data")
dataPath := write(t, data, td, "data")
privPath := write(t, []byte(tt.priv), td, "id")
write(t, []byte(tt.pub), td, "id.pub")
@ -372,14 +372,14 @@ func TestToOpenSSH(t *testing.T) {
td := t.TempDir()
data := []byte("hello, ssh world")
write(t, []byte(data), td, "data")
write(t, data, td, "data")
armored, err := sshsig.Sign([]byte(tt.priv), bytes.NewReader(data), "file")
if err != nil {
t.Fatal(err)
}
sigPath := write(t, []byte(armored), td, "oursig")
sigPath := write(t, armored, td, "oursig")
// Create an allowed_signers file with two keys to check against.
allowedSigner := "test@rekor.dev " + tt.pub + "\n"

View file

@ -123,7 +123,7 @@ func GetOAuth2ApplicationByClientID(ctx context.Context, clientID string) (app *
if !has {
return nil, ErrOAuthClientIDInvalid{ClientID: clientID}
}
return
return app, err
}
// GetOAuth2ApplicationByID returns the oauth2 application with the given id. Returns an error if not found.
@ -143,7 +143,7 @@ func GetOAuth2ApplicationByID(ctx context.Context, id int64) (app *OAuth2Applica
func GetOAuth2ApplicationsByUserID(ctx context.Context, userID int64) (apps []*OAuth2Application, err error) {
apps = make([]*OAuth2Application, 0)
err = db.GetEngine(ctx).Where("uid = ?", userID).Find(&apps)
return
return apps, err
}
// CreateOAuth2ApplicationOptions holds options to create an oauth2 application
@ -300,7 +300,7 @@ func (code *OAuth2AuthorizationCode) GenerateRedirectURI(state string) (redirect
}
q.Set("code", code.Code)
redirect.RawQuery = q.Encode()
return
return redirect, err
}
// Invalidate deletes the auth code from the database to invalidate this code
@ -430,7 +430,7 @@ func GetOAuth2GrantByID(ctx context.Context, id int64) (grant *OAuth2Grant, err
} else if !has {
return nil, nil
}
return
return grant, err
}
// GetOAuth2GrantsByUserID lists all grants of a certain user

View file

@ -23,23 +23,30 @@ type contextKey struct {
name string
}
// EnginedContextKey is a context key. It is used with context.Value() to get the current Engined for the context
var EnginedContextKey = &contextKey{"engined"}
// 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{}
// Context represents a db context
type Context struct {
context.Context
e Engine
e Engine
transaction bool
}
// WithEngine returns a Context from a context.Context and Engine
func WithEngine(ctx context.Context, e Engine) *Context {
func newContext(ctx context.Context, e Engine, transaction bool) *Context {
return &Context{
Context: ctx,
e: e.Context(ctx),
Context: ctx,
e: e,
transaction: transaction,
}
}
// InTransaction if context is in a transaction
func (ctx *Context) InTransaction() bool {
return ctx.transaction
}
// Engine returns db engine
func (ctx *Context) Engine() Engine {
return ctx.e
@ -47,7 +54,7 @@ func (ctx *Context) Engine() Engine {
// Value shadows Value for context.Context but allows us to get ourselves and an Engined object
func (ctx *Context) Value(key interface{}) interface{} {
if key == EnginedContextKey {
if key == enginedContextKey {
return ctx
}
return ctx.Context.Value(key)
@ -55,7 +62,7 @@ func (ctx *Context) Value(key interface{}) interface{} {
// WithContext returns this engine tied to this context
func (ctx *Context) WithContext(other context.Context) *Context {
return WithEngine(other, ctx.e)
return newContext(ctx, ctx.e.Context(other), ctx.transaction)
}
// Engined structs provide an Engine
@ -68,7 +75,7 @@ func GetEngine(ctx context.Context) Engine {
if engined, ok := ctx.(Engined); ok {
return engined.Engine()
}
enginedInterface := ctx.Value(EnginedContextKey)
enginedInterface := ctx.Value(enginedContextKey)
if enginedInterface != nil {
return enginedInterface.(Engined).Engine()
}
@ -89,18 +96,7 @@ func TxContext() (*Context, Committer, error) {
return nil, nil, err
}
return &Context{
Context: DefaultContext,
e: sess,
}, sess, nil
}
// WithContext represents executing database operations
func WithContext(f func(ctx *Context) error) error {
return f(&Context{
Context: DefaultContext,
e: x,
})
return newContext(DefaultContext, sess, true), sess, nil
}
// WithTx represents executing database operations on a transaction
@ -118,10 +114,7 @@ func WithTx(f func(ctx context.Context) error, stdCtx ...context.Context) error
return err
}
if err := f(&Context{
Context: parentCtx,
e: sess,
}); err != nil {
if err := f(newContext(parentCtx, sess, true)); err != nil {
return err
}

View file

@ -285,5 +285,14 @@ func DeleteAllRecords(tableName string) error {
// GetMaxID will return max id of the table
func GetMaxID(beanOrTableName interface{}) (maxID int64, err error) {
_, err = x.Select("MAX(id)").Table(beanOrTableName).Get(&maxID)
return
return maxID, err
}
func SetLogSQL(ctx context.Context, on bool) {
e := GetEngine(ctx)
if x, ok := e.(*xorm.Engine); ok {
x.ShowSQL(on)
} else if sess, ok := e.(*xorm.Session); ok {
sess.Engine().ShowSQL(on)
}
}

View file

@ -44,7 +44,7 @@ func UpsertResourceIndex(ctx context.Context, tableName string, groupID int64) (
default:
return fmt.Errorf("database type not supported")
}
return
return err
}
var (

View file

@ -58,7 +58,7 @@ func (opts *ListOptions) GetSkipTake() (skip, take int) {
func (opts *ListOptions) GetStartEnd() (start, end int) {
start, take := opts.GetSkipTake()
end = start + take
return
return start, end
}
// SetDefaultValues sets default values

View file

@ -6,6 +6,7 @@ package db
import (
"fmt"
"sync/atomic"
"code.gitea.io/gitea/modules/log"
@ -14,15 +15,19 @@ import (
// XORMLogBridge a logger bridge from Logger to xorm
type XORMLogBridge struct {
showSQL bool
logger log.Logger
showSQLint *int32
logger log.Logger
}
// NewXORMLogger inits a log bridge for xorm
func NewXORMLogger(showSQL bool) xormlog.Logger {
showSQLint := int32(0)
if showSQL {
showSQLint = 1
}
return &XORMLogBridge{
showSQL: showSQL,
logger: log.GetLogger("xorm"),
showSQLint: &showSQLint,
logger: log.GetLogger("xorm"),
}
}
@ -94,14 +99,16 @@ func (l *XORMLogBridge) SetLevel(lvl xormlog.LogLevel) {
// ShowSQL set if record SQL
func (l *XORMLogBridge) ShowSQL(show ...bool) {
if len(show) > 0 {
l.showSQL = show[0]
} else {
l.showSQL = true
showSQL := int32(1)
if len(show) > 0 && !show[0] {
showSQL = 0
}
atomic.StoreInt32(l.showSQLint, showSQL)
}
// IsShowSQL if record SQL
func (l *XORMLogBridge) IsShowSQL() bool {
return l.showSQL
showSQL := atomic.LoadInt32(l.showSQLint)
return showSQL == 1
}

View file

@ -44,7 +44,7 @@ func (d *postgresSchemaDriver) Open(name string) (driver.Conn, error) {
_, err := execer.Exec(`SELECT set_config(
'search_path',
$1 || ',' || current_setting('search_path'),
false)`, []driver.Value{schemaValue}) //nolint
false)`, []driver.Value{schemaValue})
if err != nil {
_ = conn.Close()
return nil, err

View file

@ -363,7 +363,7 @@ func updateApprovalWhitelist(ctx context.Context, repo *repo_model.Repository, c
whitelist = append(whitelist, userID)
}
return
return whitelist, err
}
// updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
@ -392,7 +392,7 @@ func updateUserWhitelist(ctx context.Context, repo *repo_model.Repository, curre
whitelist = append(whitelist, userID)
}
return
return whitelist, err
}
// updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
@ -415,7 +415,7 @@ func updateTeamWhitelist(ctx context.Context, repo *repo_model.Repository, curre
}
}
return
return whitelist, err
}
// DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
@ -539,7 +539,7 @@ func FindRenamedBranch(repoID int64, from string) (branch *RenamedBranch, exist
}
exist, err = db.GetEngine(db.DefaultContext).Get(branch)
return
return branch, exist, err
}
// RenameBranch rename a branch

View file

@ -74,7 +74,7 @@ func upsertCommitStatusIndex(ctx context.Context, repoID int64, sha string) (err
default:
return fmt.Errorf("database type not supported")
}
return
return err
}
// GetNextCommitStatusIndex retried 3 times to generate a resource index

View file

@ -42,7 +42,7 @@ func (issue *Issue) LoadAssignees(ctx context.Context) (err error) {
if len(issue.Assignees) > 0 {
issue.Assignee = issue.Assignees[0]
}
return
return err
}
// GetAssigneeIDsByIssue returns the IDs of users assigned to an issue
@ -167,5 +167,5 @@ func MakeIDsFromAPIAssigneesToAdd(oneAssignee string, multipleAssignees []string
// Get the IDs of all assignees
assigneeIDs, err = user_model.GetUserIDsByNames(requestAssignees, false)
return
return assigneeIDs, err
}

View file

@ -315,7 +315,7 @@ func (c *Comment) LoadIssueCtx(ctx context.Context) (err error) {
return nil
}
c.Issue, err = GetIssueByID(ctx, c.IssueID)
return
return err
}
// BeforeInsert will be invoked by XORM before inserting a record
@ -627,7 +627,7 @@ func (c *Comment) LoadResolveDoer() (err error) {
err = nil
}
}
return
return err
}
// IsResolved check if an code comment is resolved
@ -955,7 +955,7 @@ func createIssueDependencyComment(ctx context.Context, doer *user_model.User, is
DependentIssueID: issue.ID,
}
_, err = CreateCommentCtx(ctx, opts)
return
return err
}
// CreateCommentOptions defines options for creating comment
@ -1350,7 +1350,7 @@ func CreatePushPullComment(ctx context.Context, pusher *user_model.User, pr *Pul
comment, err = CreateComment(ops)
return
return comment, err
}
// CreateAutoMergeComment is a internal function, only use it for CommentTypePRScheduledToAutoMerge and CommentTypePRUnScheduledToAutoMerge CommentTypes
@ -1372,7 +1372,7 @@ func CreateAutoMergeComment(ctx context.Context, typ CommentType, pr *PullReques
Repo: pr.BaseRepo,
Issue: pr.Issue,
})
return
return comment, err
}
// getCommitsFromRepo get commit IDs from repo in between oldCommitID and newCommitID
@ -1434,7 +1434,7 @@ func getCommitIDsFromRepo(ctx context.Context, repo *repo_model.Repository, oldC
}
}
return
return commitIDs, isForcePush, err
}
type commitBranchCheckItem struct {

View file

@ -223,7 +223,7 @@ func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
return nil, err
}
pr.Issue = issue
return
return pr, err
}
// LoadLabels loads labels
@ -255,7 +255,7 @@ func (issue *Issue) loadPoster(ctx context.Context) (err error) {
return
}
}
return
return err
}
func (issue *Issue) loadPullRequest(ctx context.Context) (err error) {
@ -311,7 +311,7 @@ func (issue *Issue) loadReactions(ctx context.Context) (err error) {
return err
}
// Load reaction user data
if _, err := ReactionList(reactions).LoadUsers(ctx, issue.Repo); err != nil {
if _, err := reactions.LoadUsers(ctx, issue.Repo); err != nil {
return err
}
@ -2110,7 +2110,7 @@ func updateIssueClosedNum(ctx context.Context, issue *Issue) (err error) {
} else {
err = repo_model.StatsCorrectNumClosed(ctx, issue.RepoID, false, "num_closed_issues")
}
return
return err
}
// FindAndUpdateIssueMentions finds users mentioned in the given content string, and saves them in the database.
@ -2123,7 +2123,7 @@ func FindAndUpdateIssueMentions(ctx context.Context, issue *Issue, doer *user_mo
if err = UpdateIssueMentions(ctx, issue.ID, mentions); err != nil {
return nil, fmt.Errorf("UpdateIssueMentions [%d]: %v", issue.ID, err)
}
return
return mentions, err
}
// ResolveIssueMentionsByVisibility returns the users mentioned in an issue, removing those that
@ -2257,7 +2257,7 @@ func ResolveIssueMentionsByVisibility(ctx context.Context, issue *Issue, doer *u
users = append(users, user)
}
return
return users, err
}
// UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID
@ -2380,7 +2380,7 @@ func DeleteIssuesByRepoID(ctx context.Context, repoID int64) (attachmentPaths []
return
}
return
return attachmentPaths, err
}
// RemapExternalUser ExternalUserRemappable interface

View file

@ -14,32 +14,32 @@ import (
)
// LoadProject load the project the issue was assigned to
func (i *Issue) LoadProject() (err error) {
return i.loadProject(db.DefaultContext)
func (issue *Issue) LoadProject() (err error) {
return issue.loadProject(db.DefaultContext)
}
func (i *Issue) loadProject(ctx context.Context) (err error) {
if i.Project == nil {
func (issue *Issue) loadProject(ctx context.Context) (err error) {
if issue.Project == nil {
var p project_model.Project
if _, err = db.GetEngine(ctx).Table("project").
Join("INNER", "project_issue", "project.id=project_issue.project_id").
Where("project_issue.issue_id = ?", i.ID).
Where("project_issue.issue_id = ?", issue.ID).
Get(&p); err != nil {
return err
}
i.Project = &p
issue.Project = &p
}
return
return err
}
// ProjectID return project id if issue was assigned to one
func (i *Issue) ProjectID() int64 {
return i.projectID(db.DefaultContext)
func (issue *Issue) ProjectID() int64 {
return issue.projectID(db.DefaultContext)
}
func (i *Issue) projectID(ctx context.Context) int64 {
func (issue *Issue) projectID(ctx context.Context) int64 {
var ip project_model.ProjectIssue
has, err := db.GetEngine(ctx).Where("issue_id=?", i.ID).Get(&ip)
has, err := db.GetEngine(ctx).Where("issue_id=?", issue.ID).Get(&ip)
if err != nil || !has {
return 0
}
@ -47,13 +47,13 @@ func (i *Issue) projectID(ctx context.Context) int64 {
}
// ProjectBoardID return project board id if issue was assigned to one
func (i *Issue) ProjectBoardID() int64 {
return i.projectBoardID(db.DefaultContext)
func (issue *Issue) ProjectBoardID() int64 {
return issue.projectBoardID(db.DefaultContext)
}
func (i *Issue) projectBoardID(ctx context.Context) int64 {
func (issue *Issue) projectBoardID(ctx context.Context) int64 {
var ip project_model.ProjectIssue
has, err := db.GetEngine(ctx).Where("issue_id=?", i.ID).Get(&ip)
has, err := db.GetEngine(ctx).Where("issue_id=?", issue.ID).Get(&ip)
if err != nil || !has {
return 0
}

View file

@ -65,7 +65,7 @@ func GetIssueWatch(ctx context.Context, userID, issueID int64) (iw *IssueWatch,
Where("user_id = ?", userID).
And("issue_id = ?", issueID).
Get(iw)
return
return iw, exists, err
}
// CheckIssueWatch check if an user is watching an issue

View file

@ -231,46 +231,46 @@ func (issue *Issue) verifyReferencedIssue(stdCtx context.Context, ctx *crossRefe
}
// AddCrossReferences add cross references
func (comment *Comment) AddCrossReferences(stdCtx context.Context, doer *user_model.User, removeOld bool) error {
if comment.Type != CommentTypeCode && comment.Type != CommentTypeComment {
func (c *Comment) AddCrossReferences(stdCtx context.Context, doer *user_model.User, removeOld bool) error {
if c.Type != CommentTypeCode && c.Type != CommentTypeComment {
return nil
}
if err := comment.LoadIssueCtx(stdCtx); err != nil {
if err := c.LoadIssueCtx(stdCtx); err != nil {
return err
}
ctx := &crossReferencesContext{
Type: CommentTypeCommentRef,
Doer: doer,
OrigIssue: comment.Issue,
OrigComment: comment,
OrigIssue: c.Issue,
OrigComment: c,
RemoveOld: removeOld,
}
return comment.Issue.createCrossReferences(stdCtx, ctx, "", comment.Content)
return c.Issue.createCrossReferences(stdCtx, ctx, "", c.Content)
}
func (comment *Comment) neuterCrossReferences(ctx context.Context) error {
return neuterCrossReferences(ctx, comment.IssueID, comment.ID)
func (c *Comment) neuterCrossReferences(ctx context.Context) error {
return neuterCrossReferences(ctx, c.IssueID, c.ID)
}
// LoadRefComment loads comment that created this reference from database
func (comment *Comment) LoadRefComment() (err error) {
if comment.RefComment != nil {
func (c *Comment) LoadRefComment() (err error) {
if c.RefComment != nil {
return nil
}
comment.RefComment, err = GetCommentByID(db.DefaultContext, comment.RefCommentID)
return
c.RefComment, err = GetCommentByID(db.DefaultContext, c.RefCommentID)
return err
}
// LoadRefIssue loads comment that created this reference from database
func (comment *Comment) LoadRefIssue() (err error) {
if comment.RefIssue != nil {
func (c *Comment) LoadRefIssue() (err error) {
if c.RefIssue != nil {
return nil
}
comment.RefIssue, err = GetIssueByID(db.DefaultContext, comment.RefIssueID)
c.RefIssue, err = GetIssueByID(db.DefaultContext, c.RefIssueID)
if err == nil {
err = comment.RefIssue.LoadRepo(db.DefaultContext)
err = c.RefIssue.LoadRepo(db.DefaultContext)
}
return
return err
}
// CommentTypeIsRef returns true if CommentType is a reference from another issue
@ -279,44 +279,44 @@ func CommentTypeIsRef(t CommentType) bool {
}
// RefCommentHTMLURL returns the HTML URL for the comment that created this reference
func (comment *Comment) RefCommentHTMLURL() string {
func (c *Comment) RefCommentHTMLURL() string {
// Edge case for when the reference is inside the title or the description of the referring issue
if comment.RefCommentID == 0 {
return comment.RefIssueHTMLURL()
if c.RefCommentID == 0 {
return c.RefIssueHTMLURL()
}
if err := comment.LoadRefComment(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefComment(%d): %v", comment.RefCommentID, err)
if err := c.LoadRefComment(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefComment(%d): %v", c.RefCommentID, err)
return ""
}
return comment.RefComment.HTMLURL()
return c.RefComment.HTMLURL()
}
// RefIssueHTMLURL returns the HTML URL of the issue where this reference was created
func (comment *Comment) RefIssueHTMLURL() string {
if err := comment.LoadRefIssue(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefIssue(%d): %v", comment.RefCommentID, err)
func (c *Comment) RefIssueHTMLURL() string {
if err := c.LoadRefIssue(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefIssue(%d): %v", c.RefCommentID, err)
return ""
}
return comment.RefIssue.HTMLURL()
return c.RefIssue.HTMLURL()
}
// RefIssueTitle returns the title of the issue where this reference was created
func (comment *Comment) RefIssueTitle() string {
if err := comment.LoadRefIssue(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefIssue(%d): %v", comment.RefCommentID, err)
func (c *Comment) RefIssueTitle() string {
if err := c.LoadRefIssue(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefIssue(%d): %v", c.RefCommentID, err)
return ""
}
return comment.RefIssue.Title
return c.RefIssue.Title
}
// RefIssueIdent returns the user friendly identity (e.g. "#1234") of the issue where this reference was created
func (comment *Comment) RefIssueIdent() string {
if err := comment.LoadRefIssue(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefIssue(%d): %v", comment.RefCommentID, err)
func (c *Comment) RefIssueIdent() string {
if err := c.LoadRefIssue(); err != nil { // Silently dropping errors :unamused:
log.Error("LoadRefIssue(%d): %v", c.RefCommentID, err)
return ""
}
// FIXME: check this name for cross-repository references (#7901 if it gets merged)
return fmt.Sprintf("#%d", comment.RefIssue.Index)
return fmt.Sprintf("#%d", c.RefIssue.Index)
}
// __________ .__ .__ __________ __

View file

@ -323,7 +323,7 @@ func (pr *PullRequest) LoadProtectedBranchCtx(ctx context.Context) (err error) {
}
pr.ProtectedBranch, err = git_model.GetProtectedBranchBy(ctx, pr.BaseRepo.ID, pr.BaseBranch)
}
return
return err
}
// ReviewCount represents a count of Reviews

View file

@ -134,7 +134,7 @@ func (r *Review) LoadCodeComments(ctx context.Context) (err error) {
return
}
r.CodeComments, err = fetchCodeCommentsByReview(ctx, r.Issue, nil, r)
return
return err
}
func (r *Review) loadIssue(ctx context.Context) (err error) {
@ -142,7 +142,7 @@ func (r *Review) loadIssue(ctx context.Context) (err error) {
return
}
r.Issue, err = GetIssueByID(ctx, r.IssueID)
return
return err
}
func (r *Review) loadReviewer(ctx context.Context) (err error) {
@ -150,7 +150,7 @@ func (r *Review) loadReviewer(ctx context.Context) (err error) {
return
}
r.Reviewer, err = user_model.GetUserByIDCtx(ctx, r.ReviewerID)
return
return err
}
func (r *Review) loadReviewerTeam(ctx context.Context) (err error) {
@ -159,7 +159,7 @@ func (r *Review) loadReviewerTeam(ctx context.Context) (err error) {
}
r.ReviewerTeam, err = organization.GetTeamByID(ctx, r.ReviewerTeamID)
return
return err
}
// LoadReviewer loads reviewer
@ -186,7 +186,7 @@ func (r *Review) LoadAttributes(ctx context.Context) (err error) {
if err = r.loadReviewerTeam(ctx); err != nil {
return
}
return
return err
}
// GetReviewByID returns the review by the given ID
@ -537,7 +537,7 @@ func GetReviewByIssueIDAndUserID(ctx context.Context, issueID, userID int64) (*R
func GetTeamReviewerByIssueIDAndTeamID(ctx context.Context, issueID, teamID int64) (review *Review, err error) {
review = new(Review)
has := false
var has bool
if has, err = db.GetEngine(ctx).SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id = ? AND reviewer_team_id = ?)",
issueID, teamID).
Get(review); err != nil {
@ -548,21 +548,21 @@ func GetTeamReviewerByIssueIDAndTeamID(ctx context.Context, issueID, teamID int6
return nil, ErrReviewNotExist{0}
}
return
return review, err
}
// MarkReviewsAsStale marks existing reviews as stale
func MarkReviewsAsStale(issueID int64) (err error) {
_, err = db.GetEngine(db.DefaultContext).Exec("UPDATE `review` SET stale=? WHERE issue_id=?", true, issueID)
return
return err
}
// MarkReviewsAsNotStale marks existing reviews as not stale for a giving commit SHA
func MarkReviewsAsNotStale(issueID int64, commitID string) (err error) {
_, err = db.GetEngine(db.DefaultContext).Exec("UPDATE `review` SET stale=? WHERE issue_id=? AND commit_id=?", false, issueID, commitID)
return
return err
}
// DismissReview change the dismiss status of a review
@ -579,7 +579,7 @@ func DismissReview(review *Review, isDismiss bool) (err error) {
_, err = db.GetEngine(db.DefaultContext).ID(review.ID).Cols("dismissed").Update(review)
return
return err
}
// InsertReviews inserts review and review comments

View file

@ -63,7 +63,7 @@ func getStopwatch(ctx context.Context, userID, issueID int64) (sw *Stopwatch, ex
Where("user_id = ?", userID).
And("issue_id = ?", issueID).
Get(sw)
return
return sw, exists, err
}
// UserIDCount is a simple coalition of UserID and Count
@ -130,7 +130,7 @@ func HasUserStopwatch(ctx context.Context, userID int64) (exists bool, sw *Stopw
exists, err = db.GetEngine(ctx).
Where("user_id = ?", userID).
Get(sw)
return
return exists, sw, err
}
// FinishIssueStopwatchIfPossible if stopwatch exist then finish it otherwise ignore

View file

@ -63,7 +63,7 @@ func (t *TrackedTime) loadAttributes(ctx context.Context) (err error) {
return
}
}
return
return err
}
// LoadAttributes load Issue, User
@ -73,7 +73,7 @@ func (tl TrackedTimeList) LoadAttributes() (err error) {
return err
}
}
return
return err
}
// FindTrackedTimesOptions represent the filters for tracked times. If an ID is 0 it will be ignored.
@ -130,7 +130,7 @@ func (opts *FindTrackedTimesOptions) toSession(e db.Engine) db.Engine {
// GetTrackedTimes returns all tracked times that fit to the given options.
func GetTrackedTimes(ctx context.Context, options *FindTrackedTimesOptions) (trackedTimes TrackedTimeList, err error) {
err = options.toSession(db.GetEngine(ctx)).Find(&trackedTimes)
return
return trackedTimes, err
}
// CountTrackedTimes returns count of tracked times that fit to the given options.
@ -291,7 +291,7 @@ func deleteTimes(ctx context.Context, opts FindTrackedTimesOptions) (removedTime
}
_, err = opts.toSession(db.GetEngine(ctx)).Table("tracked_time").Cols("deleted").Update(&TrackedTime{Deleted: true})
return
return removedTime, err
}
func deleteTime(ctx context.Context, t *TrackedTime) error {

View file

@ -389,6 +389,8 @@ var migrations = []Migration{
NewMigration("allow to view files in PRs", addReviewViewedFiles),
// v216 -> v217
NewMigration("Improve Action table indices", improveActionTableIndices),
// v217 -> v218
NewMigration("Alter hook_task table TEXT fields to LONGTEXT", alterHookTaskTextFieldsToLongText),
}
// GetCurrentDBVersion returns the current db version

View file

@ -48,5 +48,5 @@ func recalculateStars(x *xorm.Engine) (err error) {
log.Debug("recalculate Stars number for all user finished")
return
return err
}

View file

@ -30,7 +30,7 @@ func addTimeStamps(x *xorm.Engine) error {
return err
}
// Follow represents relations of user and his/her followers.
// Follow represents relations of user and their followers.
type Follow struct {
CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
}

View file

@ -66,7 +66,7 @@ func deleteMigrationCredentials(x *xorm.Engine) (err error) {
return
}
}
return
return err
}
func removeCredentials(payload string) (string, error) {

View file

@ -81,7 +81,7 @@ func unwrapLDAPSourceCfg(x *xorm.Engine) error {
}
err := jsonUnmarshalHandleDoubleEncode([]byte(source.Cfg), &wrapped)
if err != nil {
return fmt.Errorf("failed to unmarshal %s: %w", string(source.Cfg), err)
return fmt.Errorf("failed to unmarshal %s: %w", source.Cfg, err)
}
if wrapped.Source != nil && len(wrapped.Source) > 0 {
bs, err := json.Marshal(wrapped.Source)

View file

@ -42,26 +42,5 @@ func (a *improveActionTableIndicesAction) TableIndices() []*schemas.Index {
}
func improveActionTableIndices(x *xorm.Engine) error {
{
type Action struct {
ID int64 `xorm:"pk autoincr"`
UserID int64 `xorm:"INDEX"` // Receiver user id.
OpType int
ActUserID int64 `xorm:"INDEX"` // Action user id.
RepoID int64 `xorm:"INDEX"`
CommentID int64 `xorm:"INDEX"`
IsDeleted bool `xorm:"INDEX NOT NULL DEFAULT false"`
RefName string
IsPrivate bool `xorm:"INDEX NOT NULL DEFAULT false"`
Content string `xorm:"TEXT"`
CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
}
if err := x.Sync2(&Action{}); err != nil {
return err
}
if err := x.DropIndexes(&Action{}); err != nil {
return err
}
}
return x.Sync2(&improveActionTableIndicesAction{})
}

26
models/migrations/v217.go Normal file
View file

@ -0,0 +1,26 @@
// 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.
package migrations
import (
"code.gitea.io/gitea/modules/setting"
"xorm.io/xorm"
)
func alterHookTaskTextFieldsToLongText(x *xorm.Engine) error {
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
return err
}
if setting.Database.UseMySQL {
if _, err := sess.Exec("ALTER TABLE `hook_task` CHANGE `payload_content` `payload_content` LONGTEXT, CHANGE `request_content` `request_content` LONGTEXT, change `response_content` `response_content` LONGTEXT"); err != nil {
return err
}
}
return sess.Commit()
}

View file

@ -131,7 +131,7 @@ func (opts *FindNotificationOptions) ToSession(ctx context.Context) *xorm.Sessio
// GetNotifications returns all notifications that fit to the given options.
func GetNotifications(ctx context.Context, options *FindNotificationOptions) (nl NotificationList, err error) {
err = options.ToSession(ctx).OrderBy("notification.updated_unix DESC").Find(&nl)
return
return nl, err
}
// CountNotifications count all notifications that fit to the given options and ignore pagination.
@ -291,7 +291,7 @@ func getNotificationsByIssueID(ctx context.Context, issueID int64) (notification
err = db.GetEngine(ctx).
Where("issue_id = ?", issueID).
Find(&notifications)
return
return notifications, err
}
func notificationExists(notifications []*Notification, issueID, userID int64) bool {
@ -370,7 +370,7 @@ func NotificationsForUser(ctx context.Context, user *user_model.User, statuses [
}
err = sess.Find(&notifications)
return
return notifications, err
}
// CountUnread count unread notifications for a user
@ -401,7 +401,7 @@ func (n *Notification) loadAttributes(ctx context.Context) (err error) {
if err = n.loadComment(ctx); err != nil {
return
}
return
return err
}
func (n *Notification) loadRepo(ctx context.Context) (err error) {
@ -730,7 +730,7 @@ func GetNotificationCount(ctx context.Context, user *user_model.User, status Not
Where("user_id = ?", user.ID).
And("status = ?", status).
Count(&Notification{})
return
return count, err
}
// UserIDCount is a simple coalition of UserID and Count

View file

@ -149,7 +149,7 @@ func removeOrgUser(ctx context.Context, orgID, userID int64) error {
}
}
// Delete member in his/her teams.
// Delete member in their teams.
teams, err := organization.GetUserOrgTeams(ctx, org.ID, userID)
if err != nil {
return err

View file

@ -680,7 +680,7 @@ type accessibleReposEnv struct {
user *user_model.User
team *Team
teamIDs []int64
e db.Engine
ctx context.Context
keyword string
orderBy db.SearchOrderBy
}
@ -706,7 +706,7 @@ func AccessibleReposEnv(ctx context.Context, org *Organization, userID int64) (A
org: org,
user: user,
teamIDs: teamIDs,
e: db.GetEngine(ctx),
ctx: ctx,
orderBy: db.SearchOrderByRecentUpdated,
}, nil
}
@ -717,7 +717,7 @@ func (org *Organization) AccessibleTeamReposEnv(team *Team) AccessibleReposEnvir
return &accessibleReposEnv{
org: org,
team: team,
e: db.GetEngine(db.DefaultContext),
ctx: db.DefaultContext,
orderBy: db.SearchOrderByRecentUpdated,
}
}
@ -744,7 +744,7 @@ func (env *accessibleReposEnv) cond() builder.Cond {
}
func (env *accessibleReposEnv) CountRepos() (int64, error) {
repoCount, err := env.e.
repoCount, err := db.GetEngine(env.ctx).
Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id").
Where(env.cond()).
Distinct("`repository`.id").
@ -761,7 +761,7 @@ func (env *accessibleReposEnv) RepoIDs(page, pageSize int) ([]int64, error) {
}
repoIDs := make([]int64, 0, pageSize)
return repoIDs, env.e.
return repoIDs, db.GetEngine(env.ctx).
Table("repository").
Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id").
Where(env.cond()).
@ -783,7 +783,7 @@ func (env *accessibleReposEnv) Repos(page, pageSize int) ([]*repo_model.Reposito
return repos, nil
}
return repos, env.e.
return repos, db.GetEngine(env.ctx).
In("`repository`.id", repoIDs).
OrderBy(string(env.orderBy)).
Find(&repos)
@ -791,7 +791,7 @@ func (env *accessibleReposEnv) Repos(page, pageSize int) ([]*repo_model.Reposito
func (env *accessibleReposEnv) MirrorRepoIDs() ([]int64, error) {
repoIDs := make([]int64, 0, 10)
return repoIDs, env.e.
return repoIDs, db.GetEngine(env.ctx).
Table("repository").
Join("INNER", "team_repo", "`team_repo`.repo_id=`repository`.id AND `repository`.is_mirror=?", true).
Where(env.cond()).
@ -812,7 +812,7 @@ func (env *accessibleReposEnv) MirrorRepos() ([]*repo_model.Repository, error) {
return repos, nil
}
return repos, env.e.
return repos, db.GetEngine(env.ctx).
In("`repository`.id", repoIDs).
Find(&repos)
}

View file

@ -185,7 +185,7 @@ func (t *Team) GetUnitNames() (res []string) {
for _, u := range t.Units {
res = append(res, unit.Units[u.Type].NameKey)
}
return
return res
}
// GetUnitsMap returns the team units permissions
@ -226,7 +226,7 @@ func (t *Team) GetRepositoriesCtx(ctx context.Context) (err error) {
t.Repos, err = GetTeamRepositories(ctx, &SearchTeamRepoOptions{
TeamID: t.ID,
})
return
return err
}
// GetMembersCtx returns paginated members in team of organization.

View file

@ -235,7 +235,7 @@ func (opts *PackageSearchOptions) toConds() builder.Cond {
}
if !opts.HasFiles.IsNone() {
var filesCond builder.Cond = builder.Exists(builder.Select("package_file.id").From("package_file").Where(builder.Expr("package_file.version_id = package_version.id")))
filesCond := builder.Exists(builder.Select("package_file.id").From("package_file").Where(builder.Expr("package_file.version_id = package_version.id")))
if opts.HasFiles.IsFalse() {
filesCond = builder.Not{filesCond}

View file

@ -273,7 +273,7 @@ func GetUserRepoPermission(ctx context.Context, repo *repo_model.Repository, use
}
}
return
return perm, err
}
// IsUserRealRepoAdmin check if this user is real repo admin

View file

@ -103,7 +103,7 @@ func MoveIssuesOnProjectBoard(board *Board, sortedIssueIDs map[int64]int64) erro
})
}
func (pb *Board) removeIssues(ctx context.Context) error {
_, err := db.GetEngine(ctx).Exec("UPDATE `project_issue` SET project_board_id = 0 WHERE project_board_id = ? ", pb.ID)
func (b *Board) removeIssues(ctx context.Context) error {
_, err := db.GetEngine(ctx).Exec("UPDATE `project_issue` SET project_board_id = 0 WHERE project_board_id = ? ", b.ID)
return err
}

View file

@ -132,7 +132,7 @@ func AddReleaseAttachments(ctx context.Context, releaseID int64, attachmentUUIDs
}
}
return
return err
}
// GetRelease returns release by given ID.
@ -305,7 +305,7 @@ func GetReleaseAttachments(ctx context.Context, rels ...*Release) (err error) {
sortedRels.Rel[currentIndex].Attachments = append(sortedRels.Rel[currentIndex].Attachments, attachment)
}
return
return err
}
type releaseSorter struct {

View file

@ -756,7 +756,7 @@ func DoctorUserStarNum() (err error) {
log.Debug("recalculate Stars number for all user finished")
return
return err
}
// DeleteDeployKey delete deploy keys

View file

@ -112,5 +112,5 @@ func FindRepoArchives(opts FindRepoArchiversOption) ([]*RepoArchiver, error) {
func SetArchiveRepoState(repo *Repository, isArchived bool) (err error) {
repo.IsArchived = isArchived
_, err = db.GetEngine(db.DefaultContext).Where("id = ?", repo.ID).Cols("is_archived").NoAutoTime().Update(repo)
return
return err
}

View file

@ -280,7 +280,7 @@ func (repo *Repository) CommitLink(commitID string) (result string) {
} else {
result = repo.HTMLURL() + "/commit/" + url.PathEscape(commitID)
}
return
return result
}
// APIURL returns the repository API URL
@ -319,13 +319,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) {
if err := db.WithContext(func(ctx *db.Context) error {
result = repo.UnitEnabledCtx(ctx, tp)
return nil
}); err != nil {
log.Error("repo.UnitEnabled: %v", err)
}
return
return repo.UnitEnabledCtx(db.DefaultContext, tp)
}
// UnitEnabled if this repository has the given unit enabled
@ -546,7 +540,7 @@ func (repo *Repository) DescriptionHTML(ctx context.Context) template.HTML {
log.Error("Failed to render description for %s (ID: %d): %v", repo.Name, repo.ID, err)
return template.HTML(markup.Sanitize(repo.Description))
}
return template.HTML(markup.Sanitize(string(desc)))
return template.HTML(markup.Sanitize(desc))
}
// CloneLink represents different types of clone URLs of repository.

View file

@ -111,5 +111,5 @@ func GetStatistic() (stats Statistic) {
stats.Counter.Attachment, _ = e.Count(new(repo_model.Attachment))
stats.Counter.Project, _ = e.Count(new(project_model.Project))
stats.Counter.ProjectBoard, _ = e.Count(new(project_model.Board))
return
return stats
}

View file

@ -156,14 +156,14 @@ type ErrTaskDoesNotExist struct {
Type structs.TaskType
}
// IsErrTaskDoesNotExist checks if an error is a ErrTaskIsNotExist.
// IsErrTaskDoesNotExist checks if an error is a ErrTaskDoesNotExist.
func IsErrTaskDoesNotExist(err error) bool {
_, ok := err.(ErrTaskDoesNotExist)
return ok
}
func (err ErrTaskDoesNotExist) Error() string {
return fmt.Sprintf("task is not exist [id: %d, repo_id: %d, type: %d]",
return fmt.Sprintf("task does not exist [id: %d, repo_id: %d, type: %d]",
err.ID, err.RepoID, err.Type)
}

View file

@ -318,7 +318,7 @@ func FindUnitTypes(nameKeys ...string) (res []Type) {
res = append(res, TypeInvalid)
}
}
return
return res
}
// TypeFromKey give the unit key name and return unit

View file

@ -9,7 +9,7 @@ import (
"code.gitea.io/gitea/modules/timeutil"
)
// Follow represents relations of user and his/her followers.
// Follow represents relations of user and their followers.
type Follow struct {
ID int64 `xorm:"pk autoincr"`
UserID int64 `xorm:"UNIQUE(follow)"`

View file

@ -59,7 +59,7 @@ func (opts *SearchUserOptions) toSearchQueryBase() *xorm.Session {
}
if opts.Actor != nil {
var exprCond builder.Cond = builder.Expr("org_user.org_id = `user`.id")
exprCond := builder.Expr("org_user.org_id = `user`.id")
// If Admin - they see all users!
if !opts.Actor.IsAdmin {

View file

@ -86,7 +86,7 @@ type User struct {
PasswdHashAlgo string `xorm:"NOT NULL DEFAULT 'argon2'"`
// MustChangePassword is an attribute that determines if a user
// is to change his/her password after registration.
// is to change their password after registration.
MustChangePassword bool `xorm:"NOT NULL DEFAULT false"`
LoginType auth.Type
@ -537,7 +537,7 @@ func GetUserSalt() (string, error) {
return hex.EncodeToString(rBytes), nil
}
// NewGhostUser creates and returns a fake user for someone has deleted his/her account.
// NewGhostUser creates and returns a fake user for someone has deleted their account.
func NewGhostUser() *User {
return &User{
ID: -1,

View file

@ -105,7 +105,7 @@ type HookTask struct {
HookID int64
UUID string
api.Payloader `xorm:"-"`
PayloadContent string `xorm:"TEXT"`
PayloadContent string `xorm:"LONGTEXT"`
EventType HookEventType
IsDelivered bool
Delivered int64
@ -113,9 +113,9 @@ type HookTask struct {
// History info.
IsSucceed bool
RequestContent string `xorm:"TEXT"`
RequestContent string `xorm:"LONGTEXT"`
RequestInfo *HookRequest `xorm:"-"`
ResponseContent string `xorm:"TEXT"`
ResponseContent string `xorm:"LONGTEXT"`
ResponseInfo *HookResponse `xorm:"-"`
}
@ -286,7 +286,7 @@ func deleteDeliveredHookTasksByWebhook(hookID int64, numberDeliveriesToKeep int)
Cols("hook_task.delivered").
Join("INNER", "webhook", "hook_task.hook_id = webhook.id").
OrderBy("hook_task.delivered desc").
Limit(1, int(numberDeliveriesToKeep)).
Limit(1, numberDeliveriesToKeep).
Find(&deliveryDates)
if err != nil {
return err

View file

@ -92,7 +92,7 @@ func NewClient(user *user_model.User, pubID string) (c *Client, err error) {
priv: privParsed,
pubID: pubID,
}
return
return c, err
}
// NewRequest function
@ -110,7 +110,7 @@ func (c *Client) NewRequest(b []byte, to string) (req *http.Request, err error)
return
}
err = signer.SignRequest(c.priv, c.pubID, req, b)
return
return req, err
}
// Post function
@ -120,5 +120,5 @@ func (c *Client) Post(b []byte, to string) (resp *http.Response, err error) {
return
}
resp, err = c.client.Do(req)
return
return resp, err
}

View file

@ -34,7 +34,7 @@ func Fetch(iri *url.URL) (b []byte, err error) {
return
}
b, err = io.ReadAll(io.LimitReader(resp.Body, setting.Federation.MaxSize))
return
return b, err
}
func Send(user *user_model.User, activity *ap.Activity) {

View file

@ -35,11 +35,11 @@ func GetKeyPair(user *user_model.User) (pub, priv string, err error) {
// GetPublicKey function returns a user's public key
func GetPublicKey(user *user_model.User) (pub string, err error) {
pub, _, err = GetKeyPair(user)
return
return pub, err
}
// GetPrivateKey function returns a user's private key
func GetPrivateKey(user *user_model.User) (priv string, err error) {
_, priv, err = GetKeyPair(user)
return
return priv, err
}

View file

@ -55,7 +55,7 @@ func isDecimal(r rune) bool {
}
func compareByNumbers(str1 string, pos1 int, str2 string, pos2 int) (i1, i2 int, less, equal bool) {
var d1, d2 bool = true, true
d1, d2 := true, true
var dec1, dec2 string
for d1 || d2 {
if d1 {

View file

@ -296,11 +296,11 @@ func TestDetectEncoding(t *testing.T) {
}
func stringMustStartWith(t *testing.T, expected, value string) {
assert.Equal(t, expected, string(value[:len(expected)]))
assert.Equal(t, expected, value[:len(expected)])
}
func stringMustEndWith(t *testing.T, expected, value string) {
assert.Equal(t, expected, string(value[len(value)-len(expected):]))
assert.Equal(t, expected, value[len(value)-len(expected):])
}
func bytesMustStartWith(t *testing.T, expected, value []byte) {

View file

@ -222,15 +222,15 @@ readingloop:
return
}
escaped.HasError = true
return
return escaped, err
}
func writeBroken(output io.Writer, bs []byte) (err error) {
_, err = fmt.Fprintf(output, `<span class="broken-code-point">&lt;%X&gt;</span>`, bs)
return
return err
}
func writeEscaped(output io.Writer, r rune) (err error) {
_, err = fmt.Fprintf(output, `<span class="escaped-code-point" data-escaped="[U+%04X]"><span class="char">%c</span></span>`, r, r)
return
return err
}

View file

@ -340,7 +340,7 @@ func ReferencesGitRepo(allowEmpty ...bool) func(ctx *APIContext) (cancel context
}
}
return
return cancel
}
}

View file

@ -7,6 +7,7 @@ package context
import (
"net/http"
"strings"
"code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/modules/log"
@ -41,6 +42,10 @@ func Toggle(options *ToggleOptions) func(ctx *Context) {
if ctx.Doer.MustChangePassword {
if ctx.Req.URL.Path != "/user/settings/change_password" {
if strings.HasPrefix(ctx.Req.UserAgent(), "git") {
ctx.Error(http.StatusUnauthorized, ctx.Tr("auth.must_change_password"))
return
}
ctx.Data["Title"] = ctx.Tr("auth.must_change_password")
ctx.Data["ChangePasscodeLink"] = setting.AppSubURL + "/user/change_password"
if ctx.Req.URL.Path != "/user/events" {

View file

@ -82,5 +82,5 @@ func PrivateContexter() func(http.Handler) http.Handler {
func OverrideContext(ctx *PrivateContext) (cancel context.CancelFunc) {
// We now need to override the request context as the base for our work because even if the request is cancelled we have to continue this work
ctx.Override, _, cancel = process.GetManager().AddTypedContext(graceful.GetManager().HammerContext(), fmt.Sprintf("PrivateContext: %s", ctx.Req.RequestURI), process.RequestProcessType, true)
return
return cancel
}

View file

@ -734,7 +734,7 @@ func RepoAssignment(ctx *Context) (cancel context.CancelFunc) {
ctx.Data["GoDocDirectory"] = prefix + "{/dir}"
ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}"
}
return
return cancel
}
// RepoRefType type of repo reference
@ -1001,7 +1001,7 @@ func RepoRefByType(refType RepoRefType, ignoreNotExistErr ...bool) func(*Context
return
}
ctx.Data["CommitsCount"] = ctx.Repo.CommitsCount
return
return cancel
}
}

View file

@ -52,5 +52,5 @@ func parseTime(value string) (int64, error) {
func prepareQueryArg(ctx *Context, name string) (value string, err error) {
value, err = url.PathUnescape(ctx.FormString(name))
value = strings.TrimSpace(value)
return
return value, err
}

View file

@ -257,7 +257,7 @@ func ToHook(repoLink string, w *webhook.Webhook) *api.Hook {
return &api.Hook{
ID: w.ID,
Type: string(w.Type),
Type: w.Type,
URL: fmt.Sprintf("%s/settings/hooks/%d", repoLink, w.ID),
Active: w.IsActive,
Config: config,

View file

@ -123,7 +123,7 @@ func ToTrackedTime(t *issues_model.TrackedTime) (apiT *api.TrackedTime) {
if t.User != nil {
apiT.UserName = t.User.Name
}
return
return apiT
}
// ToStopWatches convert Stopwatch list to api.StopWatches

View file

@ -216,7 +216,7 @@ func fixBrokenRepoUnit16961(repoUnit *repo_model.RepoUnit, bs []byte) (fixed boo
return false, nil
}
switch unit.Type(repoUnit.Type) {
switch repoUnit.Type {
case unit.TypeCode, unit.TypeReleases, unit.TypeWiki, unit.TypeProjects:
cfg := &repo_model.UnitConfig{}
repoUnit.Config = cfg

View file

@ -30,6 +30,9 @@ func iteratePRs(ctx context.Context, repo *repo_model.Repository, each func(*rep
}
func checkPRMergeBase(ctx context.Context, logger log.Logger, autofix bool) error {
if err := git.InitOnceWithSync(ctx); err != nil {
return err
}
numRepos := 0
numPRs := 0
numPRsUpdated := 0

View file

@ -189,6 +189,75 @@ func checkDaemonExport(ctx context.Context, logger log.Logger, autofix bool) err
return nil
}
func checkCommitGraph(ctx context.Context, logger log.Logger, autofix bool) error {
if err := git.InitOnceWithSync(ctx); err != nil {
return err
}
numRepos := 0
numNeedUpdate := 0
numWritten := 0
if err := iterateRepositories(ctx, func(repo *repo_model.Repository) error {
numRepos++
commitGraphExists := func() (bool, error) {
// Check commit-graph exists
commitGraphFile := path.Join(repo.RepoPath(), `objects/info/commit-graph`)
isExist, err := util.IsExist(commitGraphFile)
if err != nil {
logger.Error("Unable to check if %s exists. Error: %v", commitGraphFile, err)
return false, err
}
if !isExist {
commitGraphsDir := path.Join(repo.RepoPath(), `objects/info/commit-graphs`)
isExist, err = util.IsExist(commitGraphsDir)
if err != nil {
logger.Error("Unable to check if %s exists. Error: %v", commitGraphsDir, err)
return false, err
}
}
return isExist, nil
}
isExist, err := commitGraphExists()
if err != nil {
return err
}
if !isExist {
numNeedUpdate++
if autofix {
if err := git.WriteCommitGraph(ctx, repo.RepoPath()); err != nil {
logger.Error("Unable to write commit-graph in %s. Error: %v", repo.FullName(), err)
return err
}
isExist, err := commitGraphExists()
if err != nil {
return err
}
if isExist {
numWritten++
logger.Info("Commit-graph written: %s", repo.FullName())
} else {
logger.Warn("No commit-graph written: %s", repo.FullName())
}
}
}
return nil
}); err != nil {
logger.Critical("Unable to checkCommitGraph: %v", err)
return err
}
if autofix {
logger.Info("Wrote commit-graph files for %d of %d repositories.", numWritten, numRepos)
} else {
logger.Info("Checked %d repositories, %d without commit-graphs.", numRepos, numNeedUpdate)
}
return nil
}
func init() {
Register(&Check{
Title: "Check if SCRIPT_TYPE is available",
@ -225,4 +294,11 @@ func init() {
Run: checkDaemonExport,
Priority: 8,
})
Register(&Check{
Title: "Check commit-graphs",
Name: "check-commit-graphs",
IsDefault: false,
Run: checkCommitGraph,
Priority: 9,
})
}

View file

@ -18,7 +18,7 @@ func wrapNewlines(w io.Writer, prefix, value []byte) (sum int64, err error) {
if len(value) == 0 {
return
}
n := 0
var n int
last := 0
for j := bytes.IndexByte(value, '\n'); j > -1; j = bytes.IndexByte(value[last:], '\n') {
n, err = w.Write(prefix)
@ -45,7 +45,7 @@ func wrapNewlines(w io.Writer, prefix, value []byte) (sum int64, err error) {
}
n, err = w.Write([]byte("\n"))
sum += int64(n)
return
return sum, err
}
// Event is an eventsource event, not all fields need to be set
@ -64,7 +64,7 @@ type Event struct {
// The return value n is the number of bytes written. Any error encountered during the write is also returned.
func (e *Event) WriteTo(w io.Writer) (int64, error) {
sum := int64(0)
nint := 0
var nint int
n, err := wrapNewlines(w, []byte("event: "), []byte(e.Name))
sum += n
if err != nil {

View file

@ -176,12 +176,12 @@ func ReadBatchLine(rd *bufio.Reader) (sha []byte, typ string, size int64, err er
typ = typ[:idx]
size, err = strconv.ParseInt(sizeStr, 10, 64)
return
return sha, typ, size, err
}
// ReadTagObjectID reads a tag object ID hash from a cat-file --batch stream, throwing away the rest of the stream.
func ReadTagObjectID(rd *bufio.Reader, size int64) (string, error) {
id := ""
var id string
var n int64
headerLoop:
for {
@ -216,7 +216,7 @@ headerLoop:
// ReadTreeID reads a tree ID from a cat-file --batch stream, throwing away the rest of the stream.
func ReadTreeID(rd *bufio.Reader, size int64) (string, error) {
id := ""
var id string
var n int64
headerLoop:
for {
@ -328,7 +328,7 @@ func ParseTreeLine(rd *bufio.Reader, modeBuf, fnameBuf, shaBuf []byte) (mode, fn
// Deal with the 20-byte SHA
idx = 0
for idx < 20 {
read := 0
var read int
read, err = rd.Read(shaBuf[idx:20])
n += read
if err != nil {
@ -337,7 +337,7 @@ func ParseTreeLine(rd *bufio.Reader, modeBuf, fnameBuf, shaBuf []byte) (mode, fn
idx += read
}
sha = shaBuf
return
return mode, fname, sha, n, err
}
var callerPrefix string

Some files were not shown because too many files have changed in this diff Show more