3591 Commits (forgejo)

Author SHA1 Message Date
qwerty287 08609d439d
Add pages to view watched repos and subscribed issues/PRs (#17156)
Adds GitHub-like pages to view watched repos and subscribed issues/PRs
This is my second try to fix this, but it is better than the first since
it doesn't uses a filter option which could be slow when accessing
`/issues` or `/pulls` and it shows both pulls and issues (the first try
is #17053).

Closes #16111 
Replaces and closes #17053


![Screenshot](https://user-images.githubusercontent.com/80460567/134782937-3112f7da-425a-45b6-9511-5c9695aee896.png)

Co-authored-by: Lauris BH <lauris@nix.lv>
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2 years ago
Alexander Shimchik 1d3095b718
Check if email is used when updating user (#21289)
Fix #21075 
When updating user data should check if email is used by other users
2 years ago
qwerty287 1dfa28ffa5
Add API endpoint to get changed files of a PR (#21177)
This adds an api endpoint `/files` to PRs that allows to get a list of changed files.

built upon #18228, reviews there are included
closes https://github.com/go-gitea/gitea/issues/654

Co-authored-by: Anton Bracke <anton@ju60.de>
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2 years ago
M Hickford 6a45a691c1
Ignore port for loopback redirect URIs (#21293)
Following https://datatracker.ietf.org/doc/html/rfc8252#section-7.3

Fixes #21285
2 years ago
KN4CK3R f52fe82add
Use absolute links in feeds (#21229)
fixes #20864

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: techknowlogick <techknowlogick@gitea.io>
2 years ago
KN4CK3R 1b630ff7cd
Fix user visible check (#21210)
Fixes #21206

If user and viewer are equal the method should return true.
Also the common organization check was wrong as `count` can never be
less then 0.

Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
6543 c5e88fb03d
[API] teamSearch show teams with no members if user is admin (#21204)
close #21176
2 years ago
Jason Song 34f736ca04
Fix reaction of issues (#21185)
Fix #20860.

`CommentID` in `FindReactionsOptions` should be -1 to search reactions
with zero comment id.


8351172b6e/models/issues/reaction.go (L108-L121)

Co-authored-by: Lauris BH <lauris@nix.lv>
2 years ago
luzpaz cb3b3e519f
Fix various typos (#21103)
Found via `codespell -q 3 -S
./options/locale,./options/license,./public/vendor,./web_src/fomantic -L
actived,allways,attachements,ba,befores,commiter,pullrequest,pullrequests,readby,splitted,te,unknwon`

Co-authored-by: techknowlogick <techknowlogick@gitea.io>
2 years ago
Lunny Xiao bc4cce138a
Fix delete user missed some comments (#21067)
There is a mistake in the batched delete comments part of DeleteUser which causes some comments to not be deleted

The code incorrectly updates the `start` of the limit clause resulting in most comments not being deleted.

```go
			if err = e.Where("type=? AND poster_id=?", issues_model.CommentTypeComment, u.ID).Limit(batchSize, start).Find(&comments); err != nil {
```

should be:

```go
			if err = e.Where("type=? AND poster_id=?", issues_model.CommentTypeComment, u.ID).Limit(batchSize, 0).Find(&comments); err != nil {
```

Co-authored-by: zeripath <art27@cantab.net>
2 years ago
Aaron F 3963625b6e
Webhook for Wiki changes (#20219)
Add support for triggering webhook notifications on wiki changes.

This PR contains frontend and backend for webhook notifications on wiki actions (create a new page, rename a page, edit a page and delete a page). The frontend got a new checkbox under the Custom Event -> Repository Events section. There is only one checkbox for create/edit/rename/delete actions, because it makes no sense to separate it and others like releases or packages follow the same schema.

![image](https://user-images.githubusercontent.com/121972/177018803-26851196-831f-4fde-9a4c-9e639b0e0d6b.png)

The actions itself are separated, so that different notifications will be executed (with the "action" field). All the webhook receivers implement the new interface method (Wiki) and the corresponding tests.

When implementing this, I encounter a little bug on editing a wiki page. Creating and editing a wiki page is technically the same action and will be handled by the ```updateWikiPage``` function. But the function need to know if it is a new wiki page or just a change. This distinction is done by the ```action``` parameter, but this will not be sent by the frontend (on form submit). This PR will fix this by adding the ```action``` parameter with the values ```_new``` or ```_edit```, which will be used by the ```updateWikiPage``` function.

I've done integration tests with matrix and gitea (http).

![image](https://user-images.githubusercontent.com/121972/177018795-eb5cdc01-9ba3-483e-a6b7-ed0e313a71fb.png)

Fix #16457

Signed-off-by: Aaron Fischer <mail@aaron-fischer.net>
2 years ago
Eng Zer Jun 8b0aaa5f86
test: use `T.TempDir` to create temporary test directory (#21043)
A testing cleanup. 

This pull request replaces `os.MkdirTemp` with `t.TempDir`. We can use the `T.TempDir` function from the `testing` package to create temporary directory. The directory created by `T.TempDir` is automatically removed when the test and all its subtests complete. 

This saves us at least 2 lines (error check, and cleanup) on every instance, or in some cases adds cleanup that we forgot.

Reference: https://pkg.go.dev/testing#T.TempDir

```go
func TestFoo(t *testing.T) {
	// before
	tmpDir, err := os.MkdirTemp("", "")
	require.NoError(t, err)
	defer os.RemoveAll(tmpDir)

	// now
	tmpDir := t.TempDir()
}
```

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
2 years ago
zeripath e6b3be4608
Add more checks in migration code (#21011)
When migrating add several more important sanity checks:

* SHAs must be SHAs
* Refs must be valid Refs
* URLs must be reasonable

Signed-off-by: Andrew Thornton <art27@cantab.net>

Signed-off-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: techknowlogick <matti@mdranta.net>
2 years ago
zeripath 58a80ba69c
Add another index for Action table on postgres (#21033)
In #21031 we have discovered that on very big tables postgres will use a
search involving the sort term in preference to the restrictive index.

Therefore we add another index for postgres and update the original migration.

Fix #21031

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
KN4CK3R 5bc73ca666
Delete unreferenced packages when deleting a package version (#20977)
Delete a package if its last version got deleted. Otherwise removing the owner works only after the clean up job ran.

Fix #20969
2 years ago
Kyle D c8ded77680
Kd/ci playwright go test (#20123)
* Add initial playwright config

* Simplify Makefile

* Simplify Makefile

* Use correct config files

* Update playwright settings

* Fix package-lock file

* Don't use test logger for e2e tests

* fix frontend lint

* Allow passing TEST_LOGGER variable

* Init postgres database

* use standard gitea env variables

* Update playwright

* update drone

* Move empty env var to commands

* Cleanup

* Move integrations to subfolder

* tests integrations to tests integraton

* Run e2e tests with go test

* Fix linting

* install CI deps

* Add files to ESlint

* Fix drone typo

* Don't log to console in CI

* Use go test http server

* Add build step before tests

* Move shared init function to common package

* fix drone

* Clean up tests

* Fix linting

* Better mocking for page + version string

* Cleanup test generation

* Remove dependency on gitea binary

* Fix linting

* add initial support for running specific tests

* Add ACCEPT_VISUAL variable

* don't require git-lfs

* Add initial documentation

* Review feedback

* Add logged in session test

* Attempt fixing drone race

* Cleanup and bump version

* Bump deps

* Review feedback

* simplify installation

* Fix ci

* Update install docs
2 years ago
Lunny Xiao de5b8cfad8
Fix missed sort bug (#20996)
Co-authored-by: techknowlogick <techknowlogick@gitea.io>
2 years ago
Peter Gardfjäll 4562d40fce
fix hard-coded timeout and error panic in API archive download endpoint (#20925)
* fix hard-coded timeout and error panic in API archive download endpoint

This commit updates the `GET /api/v1/repos/{owner}/{repo}/archive/{archive}`
endpoint which prior to this PR had a couple of issues.

1. The endpoint had a hard-coded 20s timeout for the archiver to complete after
   which a 500 (Internal Server Error) was returned to client. For a scripted
   API client there was no clear way of telling that the operation timed out and
   that it should retry.

2. Whenever the timeout _did occur_, the code used to panic. This was caused by
   the API endpoint "delegating" to the same call path as the web, which uses a
   slightly different way of reporting errors (HTML rather than JSON for
   example).

   More specifically, `api/v1/repo/file.go#GetArchive` just called through to
   `web/repo/repo.go#Download`, which expects the `Context` to have a `Render`
   field set, but which is `nil` for API calls. Hence, a `nil` pointer error.

The code addresses (1) by dropping the hard-coded timeout. Instead, any
timeout/cancelation on the incoming `Context` is used.

The code addresses (2) by updating the API endpoint to use a separate call path
for the API-triggered archive download. This avoids producing HTML-errors on
errors (it now produces JSON errors).

Signed-off-by: Peter Gardfjäll <peter.gardfjall.work@gmail.com>
2 years ago
KN4CK3R 41c76ad714
Add support for Vagrant packages (#20930)
* Add support for Vagrant boxes.

* Add authentication.

* Add tests.

* Add integration tests.

* Add docs.

* Add icons.

* Update routers/api/packages/api.go

Co-authored-by: Lauris BH <lauris@nix.lv>
Co-authored-by: 6543 <6543@obermui.de>
2 years ago
Gusted 27ac65a124
Only show relevant repositories on explore page (#19361)
Adds a new option to only show relevant repo's on the explore page, for bigger Gitea instances like Codeberg this is a nice option to enable to make the explore page more populated with unique and "high" quality repo's. A note is shown that the results are filtered and have the possibility to see the unfiltered results.

Co-authored-by: vednoc <vednoc@protonmail.com>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: 6543 <6543@obermui.de>
2 years ago
Lunny Xiao 1d8543e7db
Move some files into models' sub packages (#20262)
* Move some files into models' sub packages

* Move functions

* merge main branch

* Fix check

* fix check

* Fix some tests

* Fix lint

* Fix lint

* Revert lint changes

* Fix error comments

* Fix lint

Co-authored-by: 6543 <6543@obermui.de>
2 years ago
zeripath 9d6a2034bc
Increase Content field size of gpg_key and public_key to MEDIUMTEXT (#20896)
Unfortunately some keys are too big to fix within the 65535 limit of TEXT on MySQL
this causes issues with these large keys.

Therefore increase these fields to MEDIUMTEXT.

Fix #20894

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
Gusted 0b4c166e8a
Fix SQL Query for `SearchTeam` (#20844)
- Currently the function takes in the `UserID` option, but isn't being
used within the SQL query. This patch fixes that by checking that only
teams are being returned that the user belongs to.

Fix #20829

Co-authored-by: delvh <dev.lh@web.de>
2 years ago
zeripath 11bae50484
Pad GPG Key ID with preceding zeroes (#20878) 2 years ago
zeripath fc4680ea71
In PushMirrorsIterate and MirrorsIterate if limit is negative do not set it (#20837) 2 years ago
zeripath 68f3aaee80
Remove calls to load Mirrors in user.Dashboard (#20855)
Whilst looking at #20840 I noticed that the Mirrors data doesn't appear
to be being used therefore we can remove this and in fact none of the
related code is used elsewhere so it can also be removed.

Related #20840
Related #20804

Signed-off-by: Andrew Thornton <art27@cantab.net>

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
Lunny Xiao 5d0f643461
Fix migration file name (#20843) 2 years ago
zeripath 03df7d0452
Check Mirror exists before linking its Repo (#20840)
In MirrorRepositoryList.loadAttributes there is some code to load the Mirror entries
from the database. This assumes that every Repository which has IsMirror set has
a Mirror associated in the DB. This association is incorrect in the case of
Mirror repository under creation when there is no Mirror entry in the DB until
completion.

Unfortunately LoadAttributes makes this incorrect assumption and presumes that a
Mirror will always be loaded. This then causes a panic.

This PR simply double checks if there a Mirror before attempting to link back to
its Repo. Unfortunately it should be expected that there may be other cases where
this incorrect assumption causes further problems.

Fix #20804

Signed-off-by: Andrew Thornton <art27@cantab.net>

Signed-off-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
techknowlogick d8e6c99125
Add badge capabilities to users (#20607)
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: John Olheiser <john.olheiser@gmail.com>
2 years ago
Balki c138e76c1c
Fix panic when an invalid oauth2 name is passed (#20820) 2 years ago
Lunny Xiao 1f146090ec
Add migrate repo archiver and packages storage support on command line (#20757)
* Add migrate repo archiver and packages storage support on command line

* Fix typo

* Use stdCtx

* Use packageblob and fix command description

* Add migrate packages unit tests

* Fix comment year

* Fix the migrate storage command line description

* Update cmd/migrate_storage.go

Co-authored-by: zeripath <art27@cantab.net>

* Update cmd/migrate_storage.go

Co-authored-by: zeripath <art27@cantab.net>

* Update cmd/migrate_storage.go

Co-authored-by: zeripath <art27@cantab.net>

* Fix test

Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: zeripath <art27@cantab.net>
2 years ago
Lunny Xiao 86c85c19b6
Refactor AssertExistsAndLoadBean to use generics (#20797)
* Refactor AssertExistsAndLoadBean to use generics

* Fix tests

Co-authored-by: zeripath <art27@cantab.net>
2 years ago
wxiaoguang 75d96f4a02
Refactor legacy git init (#20376)
* merge `CheckLFSVersion` into `InitFull` (renamed from `InitWithSyncOnce`)
* remove the `Once` during git init, no data-race now
* for doctor sub-commands, `InitFull` should only be called in initialization stage

Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
parnic 0066bc5113
Add issue filter for Author (#20578)
This adds a new filter option on the issues and pulls pages to filter by the author/poster/creator of the issue or PR
2 years ago
Lunny Xiao 5b4a84beb4
Fix v220 migration to be compatible for MSSQL 2008 r2 (#20702) 2 years ago
KN4CK3R f55af4675c
Add support for Pub packages (#20560)
* Added support for Pub packages.

* Update docs/content/doc/packages/overview.en-us.md

Co-authored-by: Gergely Nagy <algernon@users.noreply.github.com>

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: Gergely Nagy <algernon@users.noreply.github.com>
Co-authored-by: Lauris BH <lauris@nix.lv>
2 years ago
Gabriel Vasile cf06e20c0d
Check webhooks slice length before calling xorm (#20642)
xorm.db.Insert errors for empty slices. Fixes: #20641

Co-authored-by: Lauris BH <lauris@nix.lv>
Co-authored-by: John Olheiser <john.olheiser@gmail.com>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
Mohamed Sekour 0e61a74e5a
Add new API endpoints for push mirrors management (#19841)
- Add a new push mirror to specific repository
- Sync now ( send all the changes to the configured push mirrors )
- Get list of all push mirrors of a repository
- Get a push mirror by ID
- Delete push mirror by ID

Signed-off-by: Mohamed Sekour <mohamed.sekour@exfo.com>
Signed-off-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: zeripath <art27@cantab.net>
2 years ago
zeripath e819da0837
WebAuthn CredentialID field needs to be increased in size (#20530)
WebAuthn have updated their specification to set the maximum size of the
CredentialID to 1023 bytes. This is somewhat larger than our current
size and therefore we need to migrate.

The PR changes the struct to add CredentialIDBytes and migrates the CredentialID string 
to the bytes field before another migration drops the old CredentialID field. Another migration
renames this field back.

Fix #20457

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
Tyrone Yeh 8e3da0e27f
Modify milestone search keywords to be case insensitive again (#20513)
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: delvh <dev.lh@web.de>
2 years ago
Tyrone Yeh 3bd8f50af8
Added email notification option to receive all own messages (#20179)
Sometimes users want to receive email notifications of messages they create or reply to,
Added an option to personal preferences to allow users to choose

Closes #20149
2 years ago
KN4CK3R 86e5268c39
Add Docker /v2/_catalog endpoint (#20469)
* Added properties for packages.
* Fixed authenticate header format.
* Added _catalog endpoint.
* Check owner visibility.
* Extracted condition.
* Added test for _catalog.

Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: Lauris BH <lauris@nix.lv>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2 years ago
KN4CK3R a3d55ac523
Hide internal package versions (#20492)
* Hide internal versions from most searches.

* Added test.
2 years ago
aceArt-GmbH ed6cd3cbb7
Display project in issue list (#20434)
Co-authored-by: lukas <lukas.walter@aceart.de>
2 years ago
Dhruv Manilawala 3df33799c1
Fix: Actor is required to get user repositories (#20443)
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: Andrew Thornton <art27@cantab.net>
2 years ago
KN4CK3R 7690de56f7
Simplify visibility checks (#20406)
Was looking into the visibility checks because I need them for something different and noticed the checks are more complicated than they have to be.

The rule is just: user/org is visible if
- The doer is a member of the org, regardless of the org visibility
- The doer is not restricted and the user/org is public or limited
2 years ago
6543 c0f5111fea
Dismiss prior pull reviews if done via web in review dismiss (#20197) 2 years ago
silverwind 7d20c8323a
Fix commit status icon when in subdirectory (#20285)
When viewing a subdirectory and the latest commit to that directory in
the table, the commit status icon incorrectly showed the status of the
HEAD commit instead of the latest for that directory.
2 years ago
Tyrone Yeh 931c02d152
Add order by for assignee no sort issue (#20053)
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2 years ago
zeripath bffa303020
Add option to purge users (#18064)
Add the ability to purge users when deleting them.

Close #15588

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
Tyrone Yeh 715042c5bb
Fix org label open count, including close count issue (#20353)
Fixed using organization tags to see open issues in the tag list including closed issues count
2 years ago
Ing. Jaroslav Šafka 8420c1bf4c
Fix checks in PR for empty commits #19603 (#20290)
* Fixes issue #19603 (Not able to merge commit in PR when branches content is same, but different commit id)
* fill HeadCommitID in PullRequest
* compare real commits ID as check for merging
* based on @zeripath patch in #19738
2 years ago
luzpaz d29d6d1991
Fix various typos (#20338)
* Fix various typos

Found via `codespell -q 3 -S ./options/locale,./options/license,./public/vendor -L actived,allways,attachements,ba,befores,commiter,pullrequest,pullrequests,readby,splitted,te,unknwon`

Co-authored-by: zeripath <art27@cantab.net>
2 years ago
Gusted 8a7d1a3516
Store read access in access for team repo's (#20275)
- Currently when a Team has read access to a organization's non-private
repository, their access won't be stored in the database. This caused
issue for code that rely on read access being stored. So from now-on if
we see that the repository is owned by a organization don't increase the
minMode to write permission.
- Resolves #20083
2 years ago
Chongyi Zheng 49f9d43afe
Implement sync push mirror on commit (#19411)
Support synchronizing with the push mirrors whenever new commits are pushed or synced from pull mirror.

Related Issues: #18220

Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
wxiaoguang 496b8e3990
Use git.HOME_PATH for Git HOME directory (#20114)
* Add git.HOME_PATH

* add legacy file check

* Apply suggestions from code review

Co-authored-by: zeripath <art27@cantab.net>

* pass env GNUPGHOME to git command, move the existing .gitconfig to new home, make the fix for 1.17rc more clear.

* set git.HOME_PATH for docker images to default HOME

* Revert "set git.HOME_PATH for docker images to default HOME"

This reverts commit f120101ddc267cef74e4f4b92c783d5fc8e275a1.

* force Gitea to use a stable GNUPGHOME directory

* extra check to ensure only process dir or symlink for legacy files

* refactor variable name

* The legacy dir check (for 1.17-rc1) could be removed with 1.18 release, since users should have upgraded from 1.17-rc to 1.17-stable

* Update modules/git/git.go

Co-authored-by: Steven Kriegler <61625851+justusbunsi@users.noreply.github.com>

* remove initFixGitHome117rc

* Update git.go

* Update docs/content/doc/advanced/config-cheat-sheet.en-us.md

Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: Steven Kriegler <61625851+justusbunsi@users.noreply.github.com>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
Tyrone Yeh 970288f0b2
Modify milestone search keywords to be case insensitive (#20266)
Milestone search keywords are now sensitive, this modification is changed to insensitive
2 years ago
zeripath 45f17528a8
Only show Followers that current user can access (#20220)
Users who are following or being followed by a user should only be
displayed if the viewing user can see them.

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
Baekjun Kim c4368fc6bc
Display full name (#20171)
The setting `DEFAULT_SHOW_FULL_NAME` promises to use the user's full name everywhere it can be used.

Unfortunately the function `*user_model.User.ShortName()` currently uses the `.Name` instead - but this should also use the `.FullName()`.

Therefore we should make `*user_model.User.ShortName()` base its pre-shortened name on the `.FullName()` function.
2 years ago
zeripath 5c9c0b8c1e
Refix indices on actions table (#20158)
Unforunately the previous PR #20035 created indices that were not helpful
for SQLite. This PR adjusts these after testing using the try.gitea.io db.

Fix #20129

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
Lunny Xiao 184a7d4195
Check if project has the same repository id with issue when assign project to issue (#20133)
* Check if project has the same repository id with issue when assign project to issue

* Check if issue's repository id match project's repository id

* Add more permission checking

* Remove invalid argument

* Fix errors

* Add generic check

* Remove duplicated check

* Return error + add check for new issues

* Apply suggestions from code review

Co-authored-by: KN4CK3R <admin@oldschoolhack.me>

Co-authored-by: Gusted <williamzijl7@hotmail.com>
Co-authored-by: KN4CK3R <admin@oldschoolhack.me>
Co-authored-by: 6543 <6543@obermui.de>
2 years ago
Gusted 711cbcce8d
Use neutral language in comments and docs (#20135)
- Replace `his/her` to `their`, as it's more neutral language.
2 years ago
Petr Vaněk d789d3646c
Fix typos related to ErrTaskDoesNotExist error (#20118)
Fixes: f2a3abc683 ("Move migrating repository from frontend to backend (#6200)")
2 years ago
zeripath 4909493a9f
Allow manager logging to set SQL (#20064)
This PR adds a new manager command to switch on SQL logging and to turn it off.

```
gitea manager logging log-sql
gitea manager logging log-sql --off
```

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
Lunny Xiao 0649c54275
Adjust transaction handling via db.Context (#20031) 2 years ago
Wim cb50375e2b
Add more linters to improve code readability (#19989)
Add nakedret, unconvert, wastedassign, stylecheck and nolintlint linters to improve code readability

- nakedret - https://github.com/alexkohler/nakedret - nakedret is a Go static analysis tool to find naked returns in functions greater than a specified function length.
- unconvert - https://github.com/mdempsky/unconvert - Remove unnecessary type conversions
- wastedassign - https://github.com/sanposhiho/wastedassign -  wastedassign finds wasted assignment statements.
- notlintlint -  Reports ill-formed or insufficient nolint directives
- stylecheck - https://staticcheck.io/docs/checks/#ST - keep style consistent
  - excluded: [ST1003 - Poorly chosen identifier](https://staticcheck.io/docs/checks/#ST1003) and [ST1005 - Incorrectly formatted error string](https://staticcheck.io/docs/checks/#ST1005)
2 years ago
Wim 62104b4896
Alter hook_task TEXT fields to LONGTEXT (#20038)
Mysql TEXT has a limit of 64KB, change this to LONGTEXT in mysql only so we can have bigger hook payloads.

Postgresql has unlimited TEXT - https://www.postgresql.org/docs/current/datatype-character.html
Sqlite has unlimited TEXT - https://www.sqlitetutorial.net/sqlite-data-types/#:~:text=The%20maximum%20length%20of%20TEXT,SQLite%20supports%20various%20character%20encodings.

Same issue as #16656 but for hook_task

Fixes #10252, #19679, #3561
2 years ago
zeripath 62cb3c8c85
Simplify and fix migration 216 (#20035)
There appears to be a strange bug whereby the comment_id index can sometimes be missed
or missing from the action table despite the sync2 that should create it in the earlier
part of this migration. However, looking through the code for Sync2 there is no need
for this pre-code to exist and Sync2 should drop/create the indices as necessary.

I think therefore we should simplify the migration to simply be Sync2.

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
Anthony Wang e86f18a05a
User keypairs and HTTP signatures for ActivityPub federation using go-ap (#19133)
* go.mod: add go-fed/{httpsig,activity/pub,activity/streams} dependency

go get github.com/go-fed/activity/streams@master
go get github.com/go-fed/activity/pub@master
go get github.com/go-fed/httpsig@master

* activitypub: implement /api/v1/activitypub/user/{username} (#14186)

Return informations regarding a Person (as defined in ActivityStreams
https://www.w3.org/TR/activitystreams-vocabulary/#dfn-person).

Refs: https://github.com/go-gitea/gitea/issues/14186

Signed-off-by: Loïc Dachary <loic@dachary.org>

* activitypub: add the public key to Person (#14186)

Refs: https://github.com/go-gitea/gitea/issues/14186

Signed-off-by: Loïc Dachary <loic@dachary.org>

* activitypub: go-fed conformant Clock instance

Signed-off-by: Loïc Dachary <loic@dachary.org>

* activitypub: signing http client

Signed-off-by: Loïc Dachary <loic@dachary.org>

* activitypub: implement the ReqSignature middleware

Signed-off-by: Loïc Dachary <loic@dachary.org>

* activitypub: hack_16834

Signed-off-by: Loïc Dachary <loic@dachary.org>

* Fix CI checks-backend errors with go mod tidy

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Change 2021 to 2022, properly format package imports

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Run make fmt and make generate-swagger

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Use Gitea JSON library, add assert for pkp

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Run make fmt again, fix err var redeclaration

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Remove LogSQL from ActivityPub person test

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Assert if json.Unmarshal succeeds

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Cleanup, handle invalid usernames for ActivityPub person GET request

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Rename hack_16834 to user_settings

Signed-off-by: Anthony Wang <ta180m@pm.me>

* Use the httplib module instead of http for GET requests

* Clean up whitespace with make fmt

* Use time.RFC1123 and make the http.Client proxy-aware

* Check if digest algo is supported in setting module

* Clean up some variable declarations

* Remove unneeded copy

* Use system timezone instead of setting.DefaultUILocation

* Use named constant for httpsigExpirationTime

* Make pubKey IRI #main-key instead of /#main-key

* Move /#main-key to #main-key in tests

* Implemented Webfinger endpoint.

* Add visible check.

* Add user profile as alias.

* Add actor IRI and remote interaction URL to WebFinger response

* fmt

* Fix lint errors

* Use go-ap instead of go-fed

* Run go mod tidy to fix missing modules in go.mod and go.sum

* make fmt

* Convert remaining code to go-ap

* Clean up go.sum

* Fix JSON unmarshall error

* Fix CI errors by adding @context to Person() and making sure types match

* Correctly decode JSON in api_activitypub_person_test.go

* Force CI rerun

* Fix TestActivityPubPersonInbox segfault

* Fix lint error

* Use @mariusor's suggestions for idiomatic go-ap usage

* Correctly add inbox/outbox IRIs to person

* Code cleanup

* Remove another LogSQL from ActivityPub person test

* Move httpsig algos slice to an init() function

* Add actor IRI and remote interaction URL to WebFinger response

* Update TestWebFinger to check for ActivityPub IRI in aliases

* make fmt

* Force CI rerun

* WebFinger: Add CORS header and fix Href -> Template for remote interactions

The CORS header is needed due to https://datatracker.ietf.org/doc/html/rfc7033#section-5 and fixes some Peertube <-> Gitea federation issues

* make lint-backend

* Make sure Person endpoint has Content-Type application/activity+json and includes PreferredUsername, URL, and Icon

Setting the correct Content-Type is essential for federating with Mastodon

* Use UTC instead of GMT

* Rename pkey to pubKey

* Make sure HTTP request Date in GMT

* make fmt

* dont drop err

* Make sure API responses always refer to username in original case

Copied from what I wrote on #19133 discussion: Handling username case is a very tricky issue and I've already encountered a Mastodon <-> Gitea federation bug due to Gitea considering Ta180m and ta180m to be the same user while Mastodon thinks they are two different users. I think the best way forward is for Gitea to only use the original case version of the username for federation so other AP software don't get confused.

* Move httpsig algs constant slice to modules/setting/federation.go

* Add new federation settings to app.example.ini and config-cheat-sheet

* Return if marshalling error

* Make sure Person IRIs are generated correctly

This commit ensures that if the setting.AppURL is something like "http://127.0.0.1:42567" (like in the integration tests), a trailing slash will be added after that URL.

* If httpsig verification fails, fix Host header and try again

This fixes a very rare bug when Gitea and another AP server (confirmed to happen with Mastodon) are running on the same machine, Gitea fails to verify incoming HTTP signatures. This is because the other AP server creates the sig with the public Gitea domain as the Host. However, when Gitea receives the request, the Host header is instead localhost, so the signature verification fails. Manually changing the host header to the correct value and trying the veification again fixes the bug.


* Revert "If httpsig verification fails, fix Host header and try again"

This reverts commit f53e46c721a037c55facb9200106a6b491bf834c.

The bug was actually caused by nginx messing up the Host header when reverse-proxying since I didn't have the line `proxy_set_header Host $host;` in my nginx config for Gitea.

* Go back to using ap.IRI to generate inbox and outbox IRIs

* use const for key values

* Update routers/web/webfinger.go

* Use ctx.JSON in Person response to make code cleaner

* Revert "Use ctx.JSON in Person response to make code cleaner"

This doesn't work because the ctx.JSON() function already sends the response out and it's too late to edit the headers.

This reverts commit 95aad988975be3393c76094864ed6ba962157e0c.

* Use activitypub.ActivityStreamsContentType for Person response Content Type

* Limit maximum ActivityPub request and response sizes to a configurable setting

* Move setting key constants to models/user/setting_keys.go

* Fix failing ActivityPubPerson integration test by checking the correct field for username

* Add a warning about changing settings that can break federation

* Add better comments

* Don't multiply Federation.MaxSize by 1<<20 twice

* Add more better comments

* Fix failing ActivityPubMissingPerson test

We now use ctx.ContextUser so the message printed out when a user does not exist is slightly different

* make generate-swagger

For some reason I didn't realize that /templates/swagger/v1_json.tmpl was machine-generated by make generate-swagger... I've been editing it by hand for three months! 🤦

* Move getting the RFC 2616 time to a separate function

* More code cleanup

* Update go-ap to fix empty liked collection and removed unneeded HTTP headers

* go mod tidy

* Add ed25519 to httpsig algorithms

* Use go-ap/jsonld to add @context and marshal JSON

* Change Gitea user agent from the default to Gitea/Version

* Use ctx.ServerError and remove all remote interaction code from webfinger.go
2 years ago
zeripath 5d653cc10d
Improve action table indices (#19472) 2 years ago
zeripath 5d80feb5a6
Fix CountOrphanedLabels in orphan check (#20009)
gitea doctor --run check-db-consistency is currently broken due to an incorrect
and old use of Count() with a string.

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
wxiaoguang 157b405753
Remove legacy git code (ver < 2.0), fine tune markup tests (#19930)
* clean git support for ver < 2.0

* fine tune tests for markup (which requires git module)

* remove unnecessary comments

* try to fix tests

* try test again

* use const for GitVersionRequired instead of var

* try to fix integration test

* Refactor CheckAttributeReader to make a *git.Repository version

* update document for commit signing with Gitea's internal gitconfig

* update document for commit signing with Gitea's internal gitconfig

Co-authored-by: Andrew Thornton <art27@cantab.net>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
Gusted 7d1770cd71
Use correct count for `NumOpenIssues` (#19980)
- Don't specify the field in `Count` instead use `Cols` for this.
- Call `log.Error` when a error occur.

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
Hugo Hoitink 6473bd333a
In code search, get code unit accessible repos in one (main) query (#19764)
* When non-admin users use code search, get code unit accessible repos in one main query

* Modified some comments to match the changes

* Removed unnecessary check for Access Mode in Collaboration table

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: Lauris BH <lauris@nix.lv>
2 years ago
Lunny Xiao d91d4db344
Move tests as seperate sub packages to reduce duplicated file names (#19951) 2 years ago
Lunny Xiao 1a9821f57a
Move issues related files into models/issues (#19931)
* Move access and repo permission to models/perm/access

* fix test

* fix git test

* Move functions sequence

* Some improvements per @KN4CK3R and @delvh

* Move issues related code to models/issues

* Move some issues related sub package

* Merge

* Fix test

* Fix test

* Fix test

* Fix test

* Rename some files
2 years ago
yutotnh 3708ca8e28
fix: some typos (#19956) 2 years ago
Lunny Xiao 110fc57cbc
Move some code into models/git (#19879)
* Move access and repo permission to models/perm/access

* fix test

* Move some git related files into sub package models/git

* Fix build

* fix git test

* move lfs to sub package

* move more git related functions to models/git

* Move functions sequence

* Some improvements per @KN4CK3R and @delvh
2 years ago
Lunny Xiao ce3dd04c63
Fix some mirror bugs (#18649)
* Fix some mirror bugs

* Remove unnecessary code

* Fix lint

* rename stdard url

* Allow more charactors in git ssh protocol url

* improve the detection

* support ipv6 for git url parse

* Fix bug

* Fix template

* Fix bug

* fix template

* Fix tmpl

* Fix tmpl

* Fix parse ssh with interface

* Rename functions name

Co-authored-by: zeripath <art27@cantab.net>
2 years ago
wxiaoguang 88f2e457d8
Fix data-race problems in git module (quick patch) (#19934)
* Fix data-race problems in git module

* use HomeDir instead of setting.RepoRootPath

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
Sandro Santilli 52c2e82813
Custom regexp external issues (#17624)
* Implement custom regular expression for external issue tracking.

Signed-off-by: Alexander Beyn <malex@fatelectrons.org>

* Fix syntax/style

* Update repo.go

* Set metas['regexp']

* gofmt

* fix some tests

* fix more tests

* refactor frontend

* use LRU cache for regexp

* Update modules/markup/html_internal_test.go

Co-authored-by: Alexander Beyn <malex@fatelectrons.org>
Co-authored-by: techknowlogick <techknowlogick@gitea.io>
Co-authored-by: Lauris BH <lauris@nix.lv>
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2 years ago
wxiaoguang a0051634b9
Refactor git module, make Gitea use internal git config (#19732)
* Refactor git module, make Gitea use internal git config, add safe.directory config

* introduce git.InitSimple and git.InitWithConfigSync, make serv cmd use gitconfig

* use HOME instead of GIT_CONFIG_GLOBAL, because git always needs a correct HOME

* fix cmd env in cmd/serv.go

* fine tune error message

* Fix a incorrect test case

* fix configAddNonExist

* fix configAddNonExist logic, add `--fixed-value` flag, add tests

* add configSetNonExist function in case it's needed.

* use configSetNonExist for `user.name` and `user.email`

* add some comments

* Update cmd/serv.go

Co-authored-by: zeripath <art27@cantab.net>

* Update cmd/serv.go

Co-authored-by: zeripath <art27@cantab.net>

* Update modules/git/git.go

Co-authored-by: zeripath <art27@cantab.net>

* Update modules/setting/setting.go

Co-authored-by: zeripath <art27@cantab.net>

* Update modules/git/repo_attribute.go

Co-authored-by: zeripath <art27@cantab.net>

* fix spaces in messages

* use `configSet("core.protectNTFS", ...)` instead of `globalCommandArgs`

* remove GIT_CONFIG_NOSYSTEM, continue to use system's git config

* Update cmd/serv.go

Co-authored-by: zeripath <art27@cantab.net>

* fix merge

* remove code for safe.directory

* separate git.CommonEnvs to CommonGitCmdEnvs and CommonCmdServEnvs

* avoid Golang's data race error

Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
Roger Luo 2ae45cebbf
Feature: Find files in repo (#15028)
* Create finding files page ui in repo page

* Get tree entries for find repo files.

* Move find files JS to individual file.

* gen swagger.

* Add enry.IsVendor to exclude entries

Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
Lunny Xiao 26095115f4
Move some repository related code into sub package (#19711)
* Move some repository related code into sub package

* Move more repository functions out of models

* Fix lint

* Some performance optimization for webhooks and others

* some refactors

* Fix lint

* Fix

* Update modules/repository/delete.go

Co-authored-by: delvh <dev.lh@web.de>

* Fix test

* Merge

* Fix test

* Fix test

* Fix test

* Fix test

Co-authored-by: delvh <dev.lh@web.de>
2 years ago
Gusted abb7d4ae5d
Fix typo (#19889) 2 years ago
Lunny Xiao 12c742f8dc
Fix order by parameter (#19849)
Upgrade builder to v0.3.11
Upgrade xorm to v1.3.1 and fixed some hidden bugs.

Replace #19821
Replace #19834
Included #19850

Co-authored-by: zeripath <art27@cantab.net>
2 years ago
zeripath 449ea6005f
Exclude Archived repos from Dashboard Milestones (#19882)
Milestones in archived repos should not be displayed on `/milestones`. Therefore
we should exclude these repositories from milestones page.

Fix #18257

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
Lunny Xiao e09fb30d34
improvement some release related code (#19867) 2 years ago
ttys3 0c759fd4de
feat: add DEFAULT_MERGE_STYLE to `repository.pull-request` section for repo init (#19751) 2 years ago
zeripath 8aaba65eee
Only return valid stopwatches (#19863)
Looking through the logs of try.gitea.io I am seeing a number of reports
of being unable to APIformat stopwatches because the issueID is 0. These
are invalid StopWatches and they represent a db inconsistency.

This PR simply stops sending them to the eventsource.

Signed-off-by: Andrew Thornton <art27@cantab.net>

Co-authored-by: techknowlogick <techknowlogick@gitea.io>
2 years ago
Ondřej Čertík 8720f876c7
Make WIP prefixes case insensitive, e.g. allow `Draft` as a WIP prefix (#19780)
The issue was that only the actual title was converted to uppercase, but
not the prefix as specified in `WORK_IN_PROGRESS_PREFIXES`. As a result,
the following did not work:

    WORK_IN_PROGRESS_PREFIXES=Draft:,[Draft],WIP:,[WIP]

One possible workaround was:

    WORK_IN_PROGRESS_PREFIXES=DRAFT:,[DRAFT],WIP:,[WIP]

Then indeed one could use `Draft` (as well as `DRAFT`) in the title.
However, the link `Start the title with DRAFT: to prevent the pull request
from being merged accidentally.` showed the suggestion in uppercase; so
it is not possible to show it as `Draft`. This PR fixes it, and allows
to use `Draft` in `WORK_IN_PROGRESS_PREFIXES`.

Fixes #19779.

Co-authored-by: zeripath <art27@cantab.net>
2 years ago
IT-AlexKor 0692f437b6
Show source/target branches on PR's list (#19747)
Add ability to show source/target branches for Pull Request's list. It can be useful to see which branches are used in each PR right in the list.

Co-authored-by: Alexey Korobkov <akorobkov@cian.ru>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: Lauris BH <lauris@nix.lv>
2 years ago
zeripath ffb7ab31f2
Estimate Action Count in Statistics (#19775) 2 years ago
Eekle 876cad0064
Allows repo search to match against "owner/repo" pattern strings (#19754)
* Allows repo search to match against "owner/repo" pattern strings

* Gofumpt

* Adds test case for "owner/repo" style repo search

* With "owner/repo" search terms, prioritise results which match the owner field

* Fixes unquoted SQL string in repo search
2 years ago
Lunny Xiao fd7d83ace6
Move almost all functions' parameter db.Engine to context.Context (#19748)
* Move almost all functions' parameter db.Engine to context.Context
* remove some unnecessary wrap functions
2 years ago
Lunny Xiao d81e31ad78
Move org functions (#19753)
* Move org functions

* Fix comment
2 years ago
delvh ad551bffc1
Fix incorrect translation key (#19744)
Co-authored-by: techknowlogick <techknowlogick@gitea.io>
2 years ago
Eekle 260a28d8d5
Improved ref comment link when origin is body/title (#19741)
* Makes comments in body text/title return the base page URL instead of "" in RefCommentHTMLURL()

* Add comment explaining branch

Co-authored-by: delvh <dev.lh@web.de>
2 years ago
Gusted 71ca131582
Fix issue overview for teams (#19652)
- Don't use hacky solution to limit to the correct RepoID's, instead use
current code to handle these limits. The existing code is more correct
than the hacky solution.
- Resolves #19636
- Add test-case
2 years ago
zuzuviewer 77e9346342
Fix duplicate entry error when add team member (#19702) 2 years ago
wxiaoguang 368baf9e77
Use Vue to refactor pull merge UI (#19650)
* Use Vue to refactor pull merge UI

* add comments

* fix comments

* small fine tune

* fix tests

* adopt new pull default messages

* clean up

Co-authored-by: 6543 <6543@obermui.de>
2 years ago
6543 f41c2bec4c
Delete user related oauth stuff on user deletion too (#19677)
* delete user related oauth stuff on user deletion too

* extend doctor check-db-consistency
2 years ago
Lunny Xiao cbd45471b1
Move access and repo permission to models/perm/access (#19350)
* Move access and repo permission to models/perm/access

* Remove unnecessary code
2 years ago
Gusted 9d0253a9fa
Use better message for consistency check (#19672)
- Don't log the reflect struct, but instead log the ID of the struct.
This improves the error message, as you would actually know which row is
the error.
2 years ago
singuliere 443675d180
[doctor] Add check/fix for bogus action rows (#19656)
Signed-off-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Loïc Dachary <loic@dachary.org>
2 years ago
Lunny Xiao e435283c0f
Don't select join table's columns (#19660)
* Don't select join table

* Add comment
2 years ago
Lunny Xiao 4ca1d7547a
Move some helper files out of models (#19355)
* Move some helper files out of models

* Some improvements

Co-authored-by: delvh <dev.lh@web.de>
2 years ago
Lunny Xiao d4834071da
Repository level enable package or disable (#19323) 2 years ago
6543 6a969681cd
Delete related PullAutoMerge and ReviewState on User/Repo Deletion (#19649)
* delete pullautomerges on repo/user deletion
* delete reviewstates on repo/user deletion
* optimize automerhe code
* add index to reviewstate
2 years ago
Lunny Xiao 4344a64107
Allow custom default merge message with .gitea/default_merge_message/<merge_style>_TEMPLATE.md (#18177)
* Allow custom default merge message with .gitea/MERGE_MESSAGE_<merge_style>_TEMPLATE.md

* Some improvements

* Follow some advices

* Fix bug

* Fix bug

* Fix lint

* Fix close comment

* Fix test

* Fix and docs

* Improve codes

* Update docs and remove unnecessary variables

* return error for GetDefaultMergeMessage

* Fix test

* improve code

* ignore unknow unit type

* return error for GetDefaultMergeMessage

* Update services/pull/merge.go

* Some improvements

* Follow some advices

* Fix bug

* Fix lint

* Improve codes

* Update docs and remove unnecessary variables

* return error for GetDefaultMergeMessage

* improve code

* Handle deleted HeadRepo in GetDefaultMergeMessage

Signed-off-by: Andrew Thornton <art27@cantab.net>

* Fix test

* Fix test

Co-authored-by: zeripath <art27@cantab.net>
2 years ago
delvh 5ca224a789
Allow to mark files in a PR as viewed (#19007)
Users can now mark files in PRs as viewed, resulting in them not being shown again by default when they reopen the PR again.
2 years ago
kolaente 59b30f060a
Auto merge pull requests when all checks succeeded via API (#9307)
* Fix indention

Signed-off-by: kolaente <k@knt.li>

* Add option to merge a pr right now without waiting for the checks to succeed

Signed-off-by: kolaente <k@knt.li>

* Fix lint

Signed-off-by: kolaente <k@knt.li>

* Add scheduled pr merge to tables used for testing

Signed-off-by: kolaente <k@knt.li>

* Add status param to make GetPullRequestByHeadBranch reusable

Signed-off-by: kolaente <k@knt.li>

* Move "Merge now" to a seperate button to make the ui clearer

Signed-off-by: kolaente <k@knt.li>

* Update models/scheduled_pull_request_merge.go

Co-authored-by: 赵智超 <1012112796@qq.com>

* Update web_src/js/index.js

Co-authored-by: 赵智超 <1012112796@qq.com>

* Update web_src/js/index.js

Co-authored-by: 赵智超 <1012112796@qq.com>

* Re-add migration after merge

* Fix frontend lint

* Fix version compare

* Add vendored dependencies

* Add basic tets

* Make sure the api route is capable of scheduling PRs for merging

* Fix comparing version

* make vendor

* adopt refactor

* apply suggestion: User -> Doer

* init var once

* Fix Test

* Update templates/repo/issue/view_content/comments.tmpl

* adopt

* nits

* next

* code format

* lint

* use same name schema; rm CreateUnScheduledPRToAutoMergeComment

* API: can not create schedule twice

* Add TestGetBranchNamesForSha

* nits

* new go routine for each pull to merge

* Update models/pull.go

Co-authored-by: a1012112796 <1012112796@qq.com>

* Update models/scheduled_pull_request_merge.go

Co-authored-by: a1012112796 <1012112796@qq.com>

* fix & add renaming sugestions

* Update services/automerge/pull_auto_merge.go

Co-authored-by: a1012112796 <1012112796@qq.com>

* fix conflict relicts

* apply latest refactors

* fix: migration after merge

* Update models/error.go

Co-authored-by: delvh <dev.lh@web.de>

* Update options/locale/locale_en-US.ini

Co-authored-by: delvh <dev.lh@web.de>

* Update options/locale/locale_en-US.ini

Co-authored-by: delvh <dev.lh@web.de>

* adapt latest refactors

* fix test

* use more context

* skip potential edgecases

* document func usage

* GetBranchNamesForSha() -> GetRefsBySha()

* start refactoring

* ajust to new changes

* nit

* docu nit

* the great check move

* move checks for branchprotection into own package

* resolve todo now ...

* move & rename

* unexport if posible

* fix

* check if merge is allowed before merge on scheduled pull

* debugg

* wording

* improve SetDefaults & nits

* NotAllowedToMerge -> DisallowedToMerge

* fix test

* merge files

* use package "errors"

* merge files

* add string names

* other implementation for gogit

* adapt refactor

* more context for models/pull.go

* GetUserRepoPermission use context

* more ctx

* use context for loading pull head/base-repo

* more ctx

* more ctx

* models.LoadIssueCtx()

* models.LoadIssueCtx()

* Handle pull_service.Merge in one DB transaction

* add TODOs

* next

* next

* next

* more ctx

* more ctx

* Start refactoring structure of old pull code ...

* move code into new packages

* shorter names ... and finish **restructure**

* Update models/branches.go

Co-authored-by: zeripath <art27@cantab.net>

* finish UpdateProtectBranch

* more and fix

* update datum

* template: use "svg" helper

* rename prQueue 2 prPatchCheckerQueue

* handle automerge in queue

* lock pull on git&db actions ...

* lock pull on git&db actions ...

* add TODO notes

* the regex

* transaction in tests

* GetRepositoryByIDCtx

* shorter table name and lint fix

* close transaction bevore notify

* Update models/pull.go

* next

* CheckPullMergable check all branch protections!

* Update routers/web/repo/pull.go

* CheckPullMergable check all branch protections!

* Revert "PullService lock via pullID (#19520)" (for now...)

This reverts commit 6cde7c9159a5ea75a10356feb7b8c7ad4c434a9a.

* Update services/pull/check.go

* Use for a repo action one database transaction

* Apply suggestions from code review

* Apply suggestions from code review

Co-authored-by: delvh <dev.lh@web.de>

* Update services/issue/status.go

Co-authored-by: delvh <dev.lh@web.de>

* Update services/issue/status.go

Co-authored-by: delvh <dev.lh@web.de>

* use db.WithTx()

* gofmt

* make pr.GetDefaultMergeMessage() context aware

* make MergePullRequestForm.SetDefaults context aware

* use db.WithTx()

* pull.SetMerged only with context

* fix deadlock in `test-sqlite\#TestAPIBranchProtection`

* dont forget templates

* db.WithTx allow to set the parentCtx

* handle db transaction in service packages but not router

* issue_service.ChangeStatus just had caused another deadlock :/
it has to do something with how notification package is handled

* if we merge a pull in one database transaktion, we get a lock, because merge infoce internal api that cant handle open db sessions to the same repo

* ajust to current master

* Apply suggestions from code review

Co-authored-by: delvh <dev.lh@web.de>

* dont open db transaction in router

* make generate-swagger

* one _success less

* wording nit

* rm

* adapt

* remove not needed test files

* rm less diff & use attr in JS

* ...

* Update services/repository/files/commit.go

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>

* ajust db schema for PullAutoMerge

* skip broken pull refs

* more context in error messages

* remove webUI part for another pull

* remove more WebUI only parts

* API: add CancleAutoMergePR

* Apply suggestions from code review

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>

* fix lint

* Apply suggestions from code review

* cancle -> cancel

Co-authored-by: delvh <dev.lh@web.de>

* change queue identifyer

* fix swagger

* prevent nil issue

* fix and dont drop error

* as per @zeripath

* Update integrations/git_test.go

Co-authored-by: delvh <dev.lh@web.de>

* Update integrations/git_test.go

Co-authored-by: delvh <dev.lh@web.de>

* more declarative integration tests (dedup code)

* use assert.False/True helper

Co-authored-by: 赵智超 <1012112796@qq.com>
Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: delvh <dev.lh@web.de>
Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2 years ago
wxiaoguang 994257d266
Add missing `sorting` column in `project_issue` table (#19635) 2 years ago
zeripath a7f52684cb
Prevent NPE when checking repo units if the user is nil (#19625)
CheckRepoUnitUser should tolerate nil users.

Fix #19613

Signed-off-by: Andrew Thornton <art27@cantab.net>

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2 years ago
singuliere b536b65189
GetFeeds must always discard actions with dangling repo_id (#19598)
* GetFeeds must always discard actions with dangling repo_id

See https://discourse.gitea.io/t/blank-page-after-login/5051/12
for a panic in 1.16.6.

* add comment to explain the dangling ID in the fixture

* loadRepoOwner must not attempt to use a nil action.Repo

* make fmt

Co-authored-by: Loïc Dachary <loic@dachary.org>
2 years ago
Gusted 3114cd30b8
Only check for non-finished migrating task (#19601)
* Only check for non-finished migrating task

- Only check if a non-finished migrating task exists for a mirror before
fetching the mirror details from the database.
- Resolves #19600
- Regression: #19588

* Clarify function
2 years ago
6543 92f139d091
Use for a repo action one database transaction (#19576)
... more context

(part of #9307)
2 years ago
Gusted 982b726b08
Don't fetch Mirror when it's migrating (#19588)
- When a repository is still being migrated, don't try to fetch the
Mirror from the database. Instead skip it. This allows to visit
repositories that are still being migrated and were configured to be
mirrored.
- Resolves #19585
- Regression: #19295

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2 years ago
Lunny Xiao 772ad761eb
Fix some slice problems (incorrect slice length) (#19592) 2 years ago
6543 e2a3f3d259
Federation: return useful statistic information for nodeinfo (#19561)
Add statistic information for total user count, active user count, issue count and comment count for `/nodeinfo`
2 years ago
wxiaoguang 71bafa0263
ignore DNS error when doing migration allow/block check (#19566)
Co-authored-by: 6543 <6543@obermui.de>
2 years ago
Jimmy Praet 5aebc4f000
Respect DefaultUserIsRestricted system default when creating new user (#19310)
* Apply DefaultUserIsRestricted in CreateUser

* Enforce system defaults in CreateUser

Allow for overwrites with CreateUserOverwriteOptions

* Fix compilation errors

* Add "restricted" option to create user command

* Add "restricted" option to create user admin api

* Respect default setting.Service.RegisterEmailConfirm and setting.Service.RegisterManualConfirm where needed

* Revert "Respect default setting.Service.RegisterEmailConfirm and setting.Service.RegisterManualConfirm where needed"

This reverts commit ee95d3e8dc9e9fff4fa66a5111e4d3930280e033.
2 years ago
Florin Hillebrand ad6d08d155
Add API to query collaborators permission for a repository (#18761)
Targeting #14936, #15332

Adds a collaborator permissions API endpoint according to GitHub API: https://docs.github.com/en/rest/collaborators/collaborators#get-repository-permissions-for-a-user to retrieve a collaborators permissions for a specific repository.

### Checks the repository permissions of a collaborator. 

`GET` `/repos/{owner}/{repo}/collaborators/{collaborator}/permission`

Possible `permission` values are `admin`, `write`, `read`, `owner`, `none`.

```json
{
  "permission": "admin",
  "role_name": "admin",
  "user": {}
}
```

Where `permission` and `role_name` hold the same `permission` value and `user` is filled with the user API object. Only admins are allowed to use this API endpoint.
2 years ago
qwerty287 8eb1cd9264
Add "Allow edits from maintainer" feature (#18002)
Adds a feature [like GitHub has](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork) (step 7).
If you create a new PR from a forked repo, you can select (and change later, but only if you are the PR creator/poster) the "Allow edits from maintainers" option.
Then users with write access to the base branch get more permissions on this branch:
* use the update pull request button
* push directly from the command line (`git push`)
* edit/delete/upload files via web UI
* use related API endpoints

You can't merge PRs to this branch with this enabled, you'll need "full" code write permissions.

This feature has a pretty big impact on the permission system. I might forgot changing some things or didn't find security vulnerabilities. In this case, please leave a review or comment on this PR.

Closes #17728

Co-authored-by: 6543 <6543@obermui.de>
2 years ago
6543 06e4687cec
more context for models (#19511)
make more usage of context, to have more db transaction in one session

(make diff of  #9307 smaller)
2 years ago
Lunny Xiao 6cc8aed737
Fix two typos (#19504) 2 years ago
Gusted 4e912a61c8
Improve Stopwatch behavior (#18930)
- Don't send empty stopwatch over and over again, only send once.
- Stop interval to update stopwatch's timer when there is no more stopwatch.
2 years ago
6543 ddbbe6e15c
User specific repoID or xorm builder conditions for issue search (#19475)
* extend models.IssuesOptions to have more specific repo filter options

* use new options

* unrelated refactor

* rm RepoIDs
2 years ago
Lunny Xiao fc002860d8
Simplify the code to get issue count (#19380)
* Simple the code to get issue count

* Improve codes
2 years ago
Gusted ebe569a268
Set correct PR status on 3way on conflict checking (#19457)
* Set correct PR status on 3way on conflict checking

- When 3-way merge is enabled for conflict checking, it has a new
interesting behavior that it doesn't return any error when it found a
conflict, so we change the condition to not check for the error, but
instead check if conflictedfiles is populated, this fixes a issue
whereby PR status wasn't correctly on conflicted PR's.
- Refactor the mergeable property(which was incorrectly set and lead me this
bug) to be more maintainable.
- Add a dedicated test for conflicting checking, so it should prevent
future issues with this.

* Fix linter
2 years ago
qwerty287 ae6a52440a
Fix panic in team repos API (#19431)
* Fix panic in team repos API

* Fix pagination

* fmt
2 years ago
KN4CK3R 18727df73a
Add Helm Chart registry (#19406) 2 years ago
Lunny Xiao b8911fb456
Use a struct as test options (#19393)
* Use a struct as test options

* Fix name

* Fix test
2 years ago
wxiaoguang d906858847
Use "main" as default branch name (#19354)
* Use "main" as default branch name

* fix test code
2 years ago
Lunny Xiao 1dfa26e00e
Move milestone to models/issues/ (#19278)
* Move milestone to models/issues/

* Fix lint

* Fix test

* Fix lint

* Fix lint
2 years ago
6543 75f8534c3a
API: Search Issues, dont show 500 if filter result in empty list (#19244)
* remove error who is none

* use setupSessionNoLimit instead of setupSessionWithLimit when no pagination

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2 years ago
KN4CK3R 5e242e021b
Package registry changes (#19305)
* removed debug logs
* fixed SELECT
* removed unneeded error type
* use common SearchVersions method
* remove empty container upload versions
* return err
2 years ago
wxiaoguang 4f27c28947
Remove legacy `unknwon/com` package (#19298)
Follows: #19284
* The `CopyDir` is only used inside test code
* Rewrite `ToSnakeCase` with more test cases
* The `RedisCacher` only put strings into cache, here we use internal `toStr` to replace the legacy `ToStr`
* The `UniqueQueue` can use string as ID directly, no need to call `ToStr`
2 years ago
wxiaoguang 65f17bfc31
Refactor legacy `unknwon/com` package, improve golangci lint (#19284)
The main purpose is to refactor the legacy `unknwon/com` package.
1. Remove most imports of `unknwon/com`, only `util/legacy.go` imports the legacy `unknwon/com`
2. Use golangci's depguard to process denied packages
3. Fix some incorrect values in golangci.yml, eg, the version should be quoted string `"1.18"`
4. Use correctly escaped content for `go-import` and `go-source` meta tags
5. Refactor `com.Expand` to our stable (and the same fast) `vars.Expand`, our `vars.Expand` can still return partially rendered content even if the template is not good (eg: key mistach).
2 years ago
Lunny Xiao 89b9d42f08
Fix broken of team create (#19288)
* Fix broken of team create

* Update models/organization/team.go

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2 years ago
wxiaoguang 124b072f0b
Remove `git.Command.Run` and `git.Command.RunInDir*` (#19280)
Follows #19266, #8553, Close #18553, now there are only three `Run..(&RunOpts{})` functions.
 * before: `stdout, err := RunInDir(path)`
 * now: `stdout, _, err := RunStdString(&git.RunOpts{Dir:path})`
2 years ago
Lunny Xiao 3a73645502
Performance improvement for add team user when org has more than 1000 repositories (#19227)
* performance improvement for add team user when org has more than 1000 repositories

* Fix bug

* Fix bug
2 years ago
6543 9c349a4277
Move checks for pulls before merge into own function (#19271)
This make checks in one single place so they dont differ and maintainer can not forget a check in one place while adding it to the other .... ( as it's atm )

Fix:
* The API does ignore issue dependencies where Web does not
* The API checks if "IsSignedIfRequired" where Web does not - UI probably do but nothing will some to craft custom requests
* Default merge message is crafted a bit different between API and Web if not set on specific cases ...
2 years ago
Lunny Xiao d4f84f1c93
Move reaction to models/issues/ (#19264)
* Move reaction to models/issues/

* Fix test

* move the function

* improve code

* Update models/issues/reaction.go

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2 years ago
Gusted 43332a483f
Update reserved usernames list (#18438)
Adding additional usernames which are already routes, remove unused ones.
In future, avoid reserving names as much as possible, use `/-/` in path instead.
2 years ago
wxiaoguang c83168104b
Use a more general (and faster) method to sanitize URLs with credentials (#19239)
Use a more general method to sanitize URLs with credentials: Simple and intuitive / Faster /  Remove all credentials in all URLs
2 years ago
KN4CK3R 1d332342db
Add Package Registry (#16510)
* Added package store settings.

* Added models.

* Added generic package registry.

* Added tests.

* Added NuGet package registry.

* Moved service index to api file.

* Added NPM package registry.

* Added Maven package registry.

* Added PyPI package registry.

* Summary is deprecated.

* Changed npm name.

* Sanitize project url.

* Allow only scoped packages.

* Added user interface.

* Changed method name.

* Added missing migration file.

* Set page info.

* Added documentation.

* Added documentation links.

* Fixed wrong error message.

* Lint template files.

* Fixed merge errors.

* Fixed unit test storage path.

* Switch to json module.

* Added suggestions.

* Added package webhook.

* Add package api.

* Fixed swagger file.

* Fixed enum and comments.

* Fixed NuGet pagination.

* Print test names.

* Added api tests.

* Fixed access level.

* Fix User unmarshal.

* Added RubyGems package registry.

* Fix lint.

* Implemented io.Writer.

* Added support for sha256/sha512 checksum files.

* Improved maven-metadata.xml support.

* Added support for symbol package uploads.

* Added tests.

* Added overview docs.

* Added npm dependencies and keywords.

* Added no-packages information.

* Display file size.

* Display asset count.

* Fixed filter alignment.

* Added package icons.

* Formatted instructions.

* Allow anonymous package downloads.

* Fixed comments.

* Fixed postgres test.

* Moved file.

* Moved models to models/packages.

* Use correct error response format per client.

* Use simpler search form.

* Fixed IsProd.

* Restructured data model.

* Prevent empty filename.

* Fix swagger.

* Implemented user/org registry.

* Implemented UI.

* Use GetUserByIDCtx.

* Use table for dependencies.

* make svg

* Added support for unscoped npm packages.

* Add support for npm dist tags.

* Added tests for npm tags.

* Unlink packages if repository gets deleted.

* Prevent user/org delete if a packages exist.

* Use package unlink in repository service.

* Added support for composer packages.

* Restructured package docs.

* Added missing tests.

* Fixed generic content page.

* Fixed docs.

* Fixed swagger.

* Added missing type.

* Fixed ambiguous column.

* Organize content store by sha256 hash.

* Added admin package management.

* Added support for sorting.

* Add support for multiple identical versions/files.

* Added missing repository unlink.

* Added file properties.

* make fmt

* lint

* Added Conan package registry.

* Updated docs.

* Unify package names.

* Added swagger enum.

* Use longer TEXT column type.

* Removed version composite key.

* Merged package and container registry.

* Removed index.

* Use dedicated package router.

* Moved files to new location.

* Updated docs.

* Fixed JOIN order.

* Fixed GROUP BY statement.

* Fixed GROUP BY #2.

* Added symbol server support.

* Added more tests.

* Set NOT NULL.

* Added setting to disable package registries.

* Moved auth into service.

* refactor

* Use ctx everywhere.

* Added package cleanup task.

* Changed packages path.

* Added container registry.

* Refactoring

* Updated comparison.

* Fix swagger.

* Fixed table order.

* Use token auth for npm routes.

* Enabled ReverseProxy auth.

* Added packages link for orgs.

* Fixed anonymous org access.

* Enable copy button for setup instructions.

* Merge error

* Added suggestions.

* Fixed merge.

* Handle "generic".

* Added link for TODO.

* Added suggestions.

* Changed temporary buffer filename.

* Added suggestions.

* Apply suggestions from code review

Co-authored-by: Thomas Boerger <thomas@webhippie.de>

* Update docs/content/doc/packages/nuget.en-us.md

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: Thomas Boerger <thomas@webhippie.de>
2 years ago
6543 3e88af898a
Make git.OpenRepository accept Context (#19260)
* OpenRepositoryCtx -> OpenRepository
* OpenRepository -> openRepositoryWithDefaultContext, only for internal usage
2 years ago
zeripath 1eebbf23f0
When conflicts have been previously detected ensure that they can be resolved (#19247)
There is yet another problem with conflicted files not being reset when
the test patch resolves them.

This PR adjusts the code for checkConflicts to reset the ConflictedFiles
field immediately at the top. It also adds a reset to conflictedFiles
for the manuallyMerged and a shortcut for the empty status in
protectedfiles.

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
Lunny Xiao 74731c3a5a
Move some issue methods as functions (#19255)
* Move some issue methods as functions

* Fix bug
2 years ago
Lunny Xiao bd97736b9c
Move project files into models/project sub package (#17704)
* Move project files into models/project sub package

* Fix test

* Fix test

* Fix test

* Fix build

* Fix test

* Fix template bug

* Fix bug

* Fix lint

* Fix test

* Fix import

* Improve codes

Co-authored-by: 6543 <6543@obermui.de>
2 years ago
Lunny Xiao 76aa33d884
Move init repository related functions to modules (#19159)
* Move init repository related functions to modules

* Fix lint

* Use ctx but db.DefaultContext

Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2 years ago
Lunny Xiao b06b9a056c
Move organization related structs into sub package (#18518)
* Move organization related structs into sub package

* Fix test

* Fix lint

* Move more functions into sub packages

* Fix bug

* Fix test

* Update models/organization/team_repo.go

Co-authored-by: KN4CK3R <admin@oldschoolhack.me>

* Apply suggestions from code review

Co-authored-by: KN4CK3R <admin@oldschoolhack.me>

* Fix fmt

* Follow suggestion from @Gusted

* Fix test

* Fix test

* Fix bug

* Use ctx but db.DefaultContext on routers

* Fix bug

* Fix bug

* fix bug

* Update models/organization/team_user.go

* Fix bug

Co-authored-by: KN4CK3R <admin@oldschoolhack.me>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
2 years ago
wxiaoguang d4c789dfc1
Refactor repo clone button and repo clone links, fix JS error on empty repo page (#19208)
The last PR about clone buttons introduced an JS error when visiting an empty repo page:
* https://github.com/go-gitea/gitea/pull/19028
* `Uncaught ReferenceError: isSSH is not defined`, because the variables are scoped and doesn't share between sub templates.

This:
1. Simplify `templates/repo/clone_buttons.tmpl` and make code clear
2. Move most JS code into `initRepoCloneLink`
3. Remove unused `CloneLink.Git`
4. Remove `ctx.Data["DisableSSH"] / ctx.Data["ExposeAnonSSH"] / ctx.Data["DisableHTTP"]`, and only set them when is is needed (eg: deploy keys / ssh keys)
5. Introduce `Data["CloneButton*"]` to provide data for clone buttons and links
6. Introduce `Data["RepoCloneLink"]` for the repo clone link (not the wiki)
7. Remove most `ctx.Data["PageIsWiki"]` because it has been set in the `/wiki` middleware
8. Remove incorrect `quickstart` class in `migrating.tmpl`
2 years ago
Pilou 893c8938fc
New cron task: delete old system notices (#19219)
Add a new cron task which deletes the old system notices.
2 years ago
zeripath d6fa138e7c
Only send webhook events to active system webhooks and only deliver to active hooks (#19234)
There is a bug in the system webhooks whereby the active state is not checked when
webhooks are prepared and there is a bug that deactivating webhooks do not prevent
queued deliveries.

* Only add SystemWebhooks to the prepareWebhooks list if they are active
* At the time of delivery if the underlying webhook is not active mark it
as "delivered" but with a failed delivery so it does not get delivered.

Fix #19220

Signed-off-by: Andrew Thornton <art27@cantab.net>

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
zeripath d2ca021df0
Touch mirrors on even on fail to update (#19217)
* Touch mirrors on even on fail to update

If a mirror fails to be synchronised it should be pushed to the bottom of the queue
of the awaiting mirrors to be synchronised. At present if there LIMIT number of
broken mirrors they can effectively prevent all other mirrors from being synchronized
as their last_updated time will remain earlier than other mirrors.

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
Abheek Dhawan f316582458
Set the default branch for repositories generated from templates (#19136)
* Set the default branch for repositories generated from templates
* Allows default branch to be set through the API for repos generated from templates
* Update swagger API template
* Only set default branch to the one from the template if not specified
* Use specified default branch if it exists while generating git commits

Fix #19082 

Co-authored-by: John Olheiser <john.olheiser@gmail.com>
Co-authored-by: zeripath <art27@cantab.net>
2 years ago
Gusted a5f2894071
Fix showing issues in your repositories (#18916)
- Make a restriction on which issues can be shown based on if you the user or team has write permission to the repository.
- Fixes a issue whereby you wouldn't see any associated issues with a specific team on a organization if you wasn't a member(fixed by zeroing the User{ID} in the options).
- Resolves #18913
2 years ago
wxiaoguang 2b55422cd7
Fix the bug: deploy key with write access can not push (#19010)
Use DeployKeyID to replace the IsDeployKey, then CanWriteCode uses the DeployKeyID to check the write permission.
2 years ago
Norwin 77d1c7bf2f
Cleanup protected branches when deleting users & teams (#19158)
* Clean up protected_branches when deleting user

fixes #19094

* Clean up protected_branches when deleting teams

* fix issue

Co-authored-by: Lauris BH <lauris@nix.lv>
2 years ago
Otto Richter (fnetX) 04fcf23ea3
Delete related notifications on issue deletion too (#18953)
* use .Decr for issue comment counting

* Remove notification on issue removal
2 years ago
6543 45f8d97131
nit fix (#19116) 2 years ago
Aravinth Manivannan fa73cbf5a7
Store the foreign ID of issues during migration (#18446)
Storing the foreign identifier of an imported issue in the database is a prerequisite to implement idempotent migrations or mirror for issues. It is a baby step towards mirroring that introduces a new table.

At the moment when an issue is created by the Gitea uploader, it fails if the issue already exists. The Gitea uploader could be modified so that, instead of failing, it looks up the database to find an existing issue. And if it does it would update the issue instead of creating a new one. However this is not currently possible because an information is missing from the database: the foreign identifier that uniquely represents the issue being migrated is not persisted. With this change, the foreign identifier is stored in the database and the Gitea uploader will then be able to run a query to figure out if a given issue being imported already exists.

The implementation of mirroring for issues, pull requests, releases, etc. can be done in three steps:

1. Store an identifier for the element being mirrored (issue, pull request...) in the database (this is the purpose of these changes)
2. Modify the Gitea uploader to be able to update an existing repository with all it contains (issues, pull request...) instead of failing if it exists
3. Optimize the Gitea uploader to speed up the updates, when possible.

The second step creates code that does not yet exist to enable idempotent migrations with the Gitea uploader. When a migration is done for the first time, the behavior is not changed. But when a migration is done for a repository that already exists, this new code is used to update it.

The third step can use the code created in the second step to optimize and speed up migrations. For instance, when a migration is resumed, an issue that has an update time that is not more recent can be skipped and only newly created issues or updated ones will be updated. Another example of optimization could be that a webhook notifies Gitea when an issue is updated. The code triggered by the webhook would download only this issue and call the code created in the second step to update the issue, as if it was in the process of an idempotent migration.

The ForeignReferences table is added to contain local and foreign ID pairs relative to a given repository. It can later be used for pull requests and other artifacts that can be mirrored. Although the foreign id could be added as a single field in issues or pull requests, it would need to be added to all tables that represent something that can be mirrored. Creating a new table makes for a simpler and more generic design. The drawback is that it requires an extra lookup to obtain the information. However, this extra information is only required during migration or mirroring and does not impact the way Gitea currently works.

The foreign identifier of an issue or pull request is similar to the identifier of an external user, which is stored in reactions, issues, etc. as OriginalPosterID and so on. The representation of a user is however different and the ability of users to link their account to an external user at a later time is also a logic that is different from what is involved in mirroring or migrations. For these reasons, despite some commonalities, it is unclear at this time how the two tables (foreign reference and external user) could be merged together.

The ForeignID field is extracted from the issue migration context so that it can be dumped in files with dump-repo and later restored via restore-repo.

The GetAllComments downloader method is introduced to simplify the implementation and not overload the Context for the purpose of pagination. It also clarifies in which context the comments are paginated and in which context they are not.

The Context interface is no longer useful for the purpose of retrieving the LocalID and ForeignID since they are now both available from the PullRequest and Issue struct. The Reviewable and Commentable interfaces replace and serve the same purpose.

The Context data member of PullRequest and Issue becomes a DownloaderContext to clarify that its purpose is not to support in memory operations while the current downloader is acting but is not otherwise persisted. It is, for instance, used by the GitLab downloader to store the IsMergeRequest boolean and sort out issues.

---
[source](https://lab.forgefriends.org/forgefriends/forgefriends/-/merge_requests/36)

Signed-off-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: Loïc Dachary <loic@dachary.org>
2 years ago
Lunny Xiao 18033f49ba
Restrict email address validation (#17688)
This didn't follow the RFC but it's a subset of that. I think we should narrow the allowed chars at first and discuss more possibility in future PRs.
2 years ago
6543 bc0d2c8ada
RSS/Atom support for Repos (#19055)
* support for repos
* refactor
* advertise the feeds via meta tags
* allow feed suffix and feed header
* optimize performance
2 years ago
zeripath 886b1de949
Update the webauthn_credential_id_sequence in Postgres (#19048)
* Update the webauthn_credential_id_sequence in Postgres

There is (yet) another problem with v210 in that Postgres will silently allow preset
ID insertions ... but it will not update the sequence value.

This PR simply adds a little step to the end of the v210 migration to update the
sequence number.

Users who have already migrated who find that they cannot insert new
webauthn_credentials into the DB can either run:

```bash
gitea doctor recreate-table webauthn_credential
```

or

```bash
./gitea doctor --run=check-db-consistency --fix
```

which will fix the bad sequence.

Fix #19012

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
6543 ba470a85dd
use xorm builder for models.getReviewers() (#19033)
* xorm builder

* dedup code
2 years ago
6543 cc98737ca8
RSS/Atom support for Orgs (#17714)
part of #569
2 years ago
zeripath 75eb6cc9c1
Improve SyncMirrors logging (#19045)
Yet another issue has come up where the logging from SyncMirrors does not provide
enough context. This PR adds more context to these logging events.

Related #19038

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
Norwin eceab9e26f
Allow users to self-request a PR review (#19030)
The review request feature was added in https://github.com/go-gitea/gitea/pull/10756,
where the doer got explicitly excluded from available reviewers. I don't see a
functionality or security related reason to forbid this case.

As shown by GitHubs implementation, it may be useful to self-request a review,
to be reminded oneselves about reviewing, while communicating to team mates that a
review is missing.

Co-authored-by: delvh <dev.lh@web.de>
2 years ago
Otto Richter (fnetX) e46a8c90ea
Fix potential assignee query for repo (#18994)
* Fix potential assignee query for repo

* Add tests for `GetRepoAssignees`

- As per https://github.com/go-gitea/gitea/pull/18994#issuecomment-1058506640

Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: Gusted <williamzijl7@hotmail.com>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
Jimmy Praet 5184c83f6b
Add config option to disable "Update branch by rebase" (#18745) 2 years ago
eladyn 7a893dab39
ignore missing comment for user notifications (#18954)
* ignore missing comment for user notifications

* instead fix bug in notifications model

* use local variable instead

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: 6543 <6543@obermui.de>
2 years ago
6543 eddd2fb242
fix & refactor (#18973)
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
KN4CK3R f3cbdee38e
Don't clean up hardcoded `tmp` (#18983)
* Don't clean up hardcoded `tmp`.

* Fixed import.
2 years ago
Lunny Xiao 04971c33a3
Improve the deletion of issue (#18945)
Co-authored-by: 6543 <6543@obermui.de>
2 years ago
wxiaoguang dd712b77f7
Refactor admin user filter query parameters (#18965)
Only pass `status_filter` on admin page
Use a more general method to pass query parameters, remove hard-coded keys
2 years ago
6543 1f45d1e130
Accounts with WebAuthn only (no TOTP) now exist ... fix code to handle that case (#18897) 2 years ago
Otto Richter (fnetX) 062fd4c217
[API] Allow removing issues (#18879)
Add new feature to delete issues and pulls via API

Co-authored-by: fnetx <git@fralix.ovh>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: Gusted <williamzijl7@hotmail.com>
Co-authored-by: 6543 <6543@obermui.de>
2 years ago
René Schaar 6859b69198
Refactor SecToTime() function (#18863)
- Add helper method to reduce redundancy
- Expand the scope from displaying days to years
- Reduce irrelevance by not displaying small units (hours, minutes, seconds) when bigger ones apply (years)
2 years ago
Lunny Xiao b75ad7b87f
Improve mirror iterator (#18928)
* Improve mirror iterator

* fix test
2 years ago
Gusted 548adb94b4
Avoid database lookups for `DescriptionHTML` (#18924)
* Avoid database lookups for `DescriptionHTML`

- Don't Compose meta's for DescriptionHTML, they are only needed in
order to correctly format and show issue's but it's highly unlikely that
a repository description will refer to a local issue.

Using 125 Connections for 5 seconds: on `/explore/repos`(which is the most
noticeable usage by this function's database lookups):

Before:

Statistics        Avg      Stdev        Max
  Reqs/sec       569.41     506.05    2715.00
  Latency      214.27ms    16.60ms   294.84ms
  HTTP codes:
    1xx - 0, 2xx - 2974, 3xx - 0, 4xx - 0, 5xx - 0
    others - 0
  Throughput:    27.17MB/s

After:

Statistics        Avg      Stdev        Max
  Reqs/sec      1585.04     789.84    4144.56
  Latency       78.89ms    15.89ms   206.94ms
  HTTP codes:
    1xx - 0, 2xx - 7975, 3xx - 0, 4xx - 0, 5xx - 0
    others - 0
  Throughput:    73.85MB/s

Co-authored-by: 6543 <6543@obermui.de>
Co-authored-by: zeripath <art27@cantab.net>
2 years ago
Gusted f56bba1a78
Fix trace log to show value instead of pointers (#18926)
- Fixes a issue with a trace of repo.Units whereby it would show the pointers.

Before:
![image](https://user-images.githubusercontent.com/25481501/155876811-036bf40e-db89-4e09-ac00-0c78ce3f5bef.png)

After:
![image](https://user-images.githubusercontent.com/25481501/155885102-16c9cf29-314b-4f32-bcee-80e332f63dec.png)
2 years ago
qwerty287 1563a45623
Fix page and missing return on unadopted repos API (#18848)
* Fix page and missing return on unadopted repos API

Page must be 1 if it's not specified and it should return after sending an internal server error.

* Allow ignore pages

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
KN4CK3R 5b0cdd6155
Set is_empty in fixtures (#18869) 2 years ago
Gusted 33e19c8004
Don't update email for organisation (#18905)
- Fix regression caused by: f1b1472632
- Don't try to insert a email for Organisation(as they don't have one).
- Resolves #18891

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
KN4CK3R 9d7a431b71
Set is_private in fixtures. (#18868)
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
Lunny Xiao a5e8daee73
Fix migration v210 (#18892) 2 years ago
singuliere 49cab2b01f
migrations: add test for importing pull requests in gitea uploader (#18752)
* logs: add the buffer logger to inspect logs during testing

Signed-off-by: Loïc Dachary <loic@dachary.org>

* migrations: add test for importing pull requests in gitea uploader

Signed-off-by: Loïc Dachary <loic@dachary.org>

* for each git.OpenRepositoryCtx, call Close

* Content is expected to return the content of the log

* test for errors before defer

Co-authored-by: Loïc Dachary <loic@dachary.org>
Co-authored-by: zeripath <art27@cantab.net>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago
Lunny Xiao 6621710deb
Fix update user (#18878) 2 years ago
Lunny Xiao f1b1472632
Fix ldap user sync missed email in email_address table (#18786)
* Fix ldap user sync missed email in email_address table

* Fix test
2 years ago
zeripath cb41f5cae1
Update assignees check to include any writing team and change org sidebar (#18680)
Following the merging of #17811 teams can now have differing write and readonly permissions, however the assignee list will not include teams which have mixed perms.

Further the org sidebar is no longer helpful as it can't describe these mixed permissions situations.

Fix #18572

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
silverwind 2b9df564b8
Lock gofumpt to v0.3.0 and run it (#18866)
We can't depend on `latest` version of gofumpt because the output will
not be stable across versions. Lock it down to the latest version
released yesterday and run it again.
2 years ago
Lunny Xiao dc988eae0c
Fix bug for get user by email (#18833)
Co-authored-by: zeripath <art27@cantab.net>
2 years ago
Wim a387636b9a
Show fullname on issue edits and gpg/ssh signing info (#18827)
Show missing full names when configured to do so

Co-authored-by: zeripath <art27@cantab.net>
2 years ago
Johan Van de Wauw 0cc2675c44
Fix ldap loginname (#18789)
* Use email_address table to check user's email when login with email adress

* Update services/auth/signin.go

* Fix test

* Fix test

* Fix logging in with ldap username != loginname

* Fix if user does not exist yet

* Make more clear this is loginName

* Fix formatting

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: zeripath <art27@cantab.net>
2 years ago
Lunny Xiao 397d2ac303
Move deletebeans into models/db (#18781) 2 years ago
zeripath 3a29a23cdc
Attempt to fix the webauthn migration again - part 3 (#18770)
v208.go is seriously broken as it misses an ID() check. We need to no-op and remigrate all of the u2f keys.

See #18756

Signed-off-by: Andrew Thornton <art27@cantab.net>
2 years ago
René Schaar 609c91665e
Fix display time of milestones (#18753)
* Fix display time of milestones

* Move the SecToTime function

From the models/issue_stopwatch.go file to the modules/util package

* Rename the sec_to_time file

* Updated formatting

* Include copyright notice in sec_to_time.go

* Apply PR review suggestions

- Update copyright notice dates to 2022
- Change `1 day 3h 5min 7s` to `1d 3h 5m 7s`

* Rename hrs var and combine conditions

* Update unit tests to match new time pattern

Changed `1min` to `1m`

Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
2 years ago