2019-09-26 20:22:36 -04:00
// Copyright 2019 The Gitea Authors. All rights reserved.
2022-11-27 13:20:29 -05:00
// SPDX-License-Identifier: MIT
2019-09-26 20:22:36 -04:00
package pull
import (
2024-01-08 21:32:14 -05:00
"bytes"
2019-12-15 04:51:28 -05:00
"context"
2019-09-26 20:22:36 -04:00
"fmt"
2022-01-19 18:26:57 -05:00
"io"
2023-01-28 10:54:40 -05:00
"os"
2021-06-25 13:01:43 -04:00
"regexp"
2020-01-08 20:47:45 -05:00
"strings"
2023-07-28 15:18:12 -04:00
"time"
2019-09-26 20:22:36 -04:00
"code.gitea.io/gitea/models"
2021-09-19 07:49:59 -04:00
"code.gitea.io/gitea/models/db"
2022-06-12 11:51:54 -04:00
git_model "code.gitea.io/gitea/models/git"
2022-06-13 05:37:59 -04:00
issues_model "code.gitea.io/gitea/models/issues"
2021-12-09 20:27:50 -05:00
repo_model "code.gitea.io/gitea/models/repo"
2021-11-24 04:49:20 -05:00
user_model "code.gitea.io/gitea/models/user"
2023-07-28 15:18:12 -04:00
"code.gitea.io/gitea/modules/base"
2022-10-12 01:18:26 -04:00
"code.gitea.io/gitea/modules/container"
2023-07-28 15:18:12 -04:00
gitea_context "code.gitea.io/gitea/modules/context"
2019-10-14 23:28:40 -04:00
"code.gitea.io/gitea/modules/git"
2019-12-15 04:51:28 -05:00
"code.gitea.io/gitea/modules/graceful"
2021-07-24 12:03:58 -04:00
"code.gitea.io/gitea/modules/json"
2019-09-26 20:22:36 -04:00
"code.gitea.io/gitea/modules/log"
2022-05-08 12:46:32 -04:00
repo_module "code.gitea.io/gitea/modules/repository"
2020-04-10 07:26:37 -04:00
"code.gitea.io/gitea/modules/setting"
2022-05-04 12:06:23 -04:00
"code.gitea.io/gitea/modules/sync"
2023-01-28 10:54:40 -05:00
"code.gitea.io/gitea/modules/util"
2019-10-28 12:45:43 -04:00
issue_service "code.gitea.io/gitea/services/issue"
2023-09-05 14:37:47 -04:00
notify_service "code.gitea.io/gitea/services/notify"
2019-09-26 20:22:36 -04:00
)
2022-05-04 12:06:23 -04:00
// TODO: use clustered lock (unique queue? or *abuse* cache)
var pullWorkingPool = sync . NewExclusivePool ( )
2019-09-26 20:22:36 -04:00
// NewPullRequest creates new pull request with labels for repository.
2023-08-09 22:39:21 -04:00
func NewPullRequest ( ctx context . Context , repo * repo_model . Repository , issue * issues_model . Issue , labelIDs [ ] int64 , uuids [ ] string , pr * issues_model . PullRequest , assigneeIDs [ ] int64 ) error {
[MODERATION] User blocking
- Add the ability to block a user via their profile page.
- This will unstar their repositories and visa versa.
- Blocked users cannot create issues or pull requests on your the doer's repositories (mind that this is not the case for organizations).
- Blocked users cannot comment on the doer's opened issues or pull requests.
- Blocked users cannot add reactions to doer's comments.
- Blocked users cannot cause a notification trough mentioning the doer.
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/540
(cherry picked from commit 687d852480388897db4d7b0cb397cf7135ab97b1)
(cherry picked from commit 0c32a4fde531018f74e01d9db6520895fcfa10cc)
(cherry picked from commit 1791130e3cb8470b9b39742e0004d5e4c7d1e64d)
(cherry picked from commit 37858b7e8fb6ba6c6ea0ac2562285b3b144efa19)
(cherry picked from commit a3e2bfd7e9eab82cc2c17061f6bb4e386a108c46)
(cherry picked from commit 7009b9fe87696b6182fab65ae82bf5a25cd39971)
Conflicts: https://codeberg.org/forgejo/forgejo/pulls/1014
routers/web/user/profile.go
templates/user/profile.tmpl
(cherry picked from commit b2aec3479177e725cfc7cbbb9d94753226928d1c)
(cherry picked from commit e2f1b73752f6bd3f830297d8f4ac438837471226)
[MODERATION] organization blocking a user (#802)
- Resolves #476
- Follow up for: #540
- Ensure that the doer and blocked person cannot follow each other.
- Ensure that the block person cannot watch doer's repositories.
- Add unblock button to the blocked user list.
- Add blocked since information to the blocked user list.
- Add extra testing to moderation code.
- Blocked user will unwatch doer's owned repository upon blocking.
- Add flash messages to let the user know the block/unblock action was successful.
- Add "You haven't blocked any users" message.
- Add organization blocking a user.
Co-authored-by: Gusted <postmaster@gusted.xyz>
Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/802
(cherry picked from commit 0505a1042197bd9136b58bc70ec7400a23471585)
(cherry picked from commit 37b4e6ef9b85e97d651cf350c9f3ea272ee8d76a)
(cherry picked from commit c17c121f2cf1f00e2a8d6fd6847705df47d0771e)
[MODERATION] organization blocking a user (#802) (squash)
Changes to adapt to:
6bbccdd177 Improve AJAX link and modal confirm dialog (#25210)
Refs: https://codeberg.org/forgejo/forgejo/pulls/882/files#issuecomment-945962
Refs: https://codeberg.org/forgejo/forgejo/pulls/882#issue-330561
(cherry picked from commit 523635f83cb2a1a4386769b79326088c5c4bbec7)
(cherry picked from commit 4743eaa6a0be0ef47de5b17c211dfe8bad1b7af9)
(cherry picked from commit eff5b43d2e843d5d537756d4fa58a8a010b6b527)
Conflicts: https://codeberg.org/forgejo/forgejo/pulls/1014
routers/web/user/profile.go
(cherry picked from commit 9d359be5ed11237088ccf6328571939af814984e)
(cherry picked from commit b1f3069a22a03734cffbfcd503ce004ba47561b7)
[MODERATION] add user blocking API
- Follow up for: #540, #802
- Add API routes for user blocking from user and organization
perspective.
- The new routes have integration testing.
- The new model functions have unit tests.
- Actually quite boring to write and to read this pull request.
(cherry picked from commit f3afaf15c7e34038363c9ce8e1ef957ec1e22b06)
(cherry picked from commit 6d754db3e5faff93a58fab2867737f81f40f6599)
(cherry picked from commit 2a89ddc0acffa9aea0f02b721934ef9e2b496a88)
(cherry picked from commit 4a147bff7e963ab9dffcfaefa5c2c01c59b4c732)
Conflicts:
routers/api/v1/api.go
templates/swagger/v1_json.tmpl
(cherry picked from commit bb8c33918569f65f25b014f0d7fe6ac20f9036fc)
(cherry picked from commit 5a11569a011b7d0a14391e2b5c07d0af825d7b0e)
(cherry picked from commit 2373c801ee6b84c368b498b16e6ad18650b38f42)
[MODERATION] restore redirect on unblock
ctx.RedirectToFirst(ctx.FormString("redirect_to"), ctx.ContextUser.HomeLink())
was replaced by
ctx.JSONOK()
in 128d77a3a Following up fixes for "Fix inconsistent user profile layout across tabs" (#25739)
thus changing the behavior (nicely spotted by the tests). This
restores it.
(cherry picked from commit 597c243707c3c86e7256faf1e6ba727224554de3)
(cherry picked from commit cfa539e590127b4b953b010fba3dea21c82a1714)
[MODERATION] Add test case (squash)
- Add an test case, to test an property of the function.
(cherry picked from commit 70dadb1916bfef8ba8cbc4e9b042cc8740f45e28)
[MODERATION] Block adding collaborators
- Ensure that the doer and blocked user cannot add each other as
collaborators to repositories.
- The Web UI gets an detailed message of the specific situation, the API
gets an generic Forbidden code.
- Unit tests has been added.
- Integration testing for Web and API has been added.
- This commit doesn't introduce removing each other as collaborators on
the block action, due to the complexity of database calls that needs to
be figured out. That deserves its own commit and test code.
(cherry picked from commit 747be949a1b3cd06f6586512f1af4630e55d7ad4)
[MODERATION] move locale_en-US.ini strings to avoid conflicts
Conflicts:
web_src/css/org.css
web_src/css/user.css
https://codeberg.org/forgejo/forgejo/pulls/1180
(cherry picked from commit e53f955c888ebaafc863a6e463da87f70f5605da)
Conflicts:
services/issue/comments.go
https://codeberg.org/forgejo/forgejo/pulls/1212
(cherry picked from commit b4a454b576eee0c7738b2f7df1acaf5bf7810d12)
Conflicts:
models/forgejo_migrations/migrate.go
options/locale/locale_en-US.ini
services/pull/pull.go
https://codeberg.org/forgejo/forgejo/pulls/1264
[MODERATION] Remove blocked user collaborations with doer
- When the doer blocks an user, who is also an collaborator on an
repository that the doer owns, remove that collaboration.
- Added unit tests.
- Refactor the unit test to be more organized.
(cherry picked from commit ec8701617830152680d69d50d64cb43cc2054a89)
(cherry picked from commit 313e6174d832501c57724ae7a6285194b7b81aab)
[MODERATION] QoL improvements (squash)
- Ensure that organisations cannot be blocked. It currently has no
effect, as all blocked operations cannot be executed from an
organisation standpoint.
- Refactored the API route to make use of the `UserAssignmentAPI`
middleware.
- Make more use of `t.Run` so that the test code is more clear about
which block of code belongs to which test case.
- Added more integration testing (to ensure the organisations cannot be
blocked and some authorization/permission checks).
(cherry picked from commit e9d638d0756ee20b6bf1eb999c988533a5066a68)
[MODERATION] s/{{avatar/{{ctx.AvatarUtils.Avatar/
(cherry picked from commit ce8b30be1327ab98df2ba061dd7e2a278b278c5b)
(cherry picked from commit f911dc402508b04cd5d5fb2f3332c2d640e4556e)
Conflicts:
options/locale/locale_en-US.ini
https://codeberg.org/forgejo/forgejo/pulls/1354
(cherry picked from commit c1b37b7fdaf06ee60da341dff76d703990c08082)
(cherry picked from commit 856a2e09036adf56d987c6eee364c431bc37fb2e)
[MODERATION] Show graceful error on comment creation
- When someone is blocked by the repository owner or issue poster and
try to comment on that issue, they get shown a graceful error.
- Adds integration test.
(cherry picked from commit 490646302e1e3dc3c59c9d75938b4647b6873ce7)
(cherry picked from commit d3d88667cbb928a6ff80658eba8ef0c6c508c9e0)
(cherry picked from commit 6818de13a921753e082b7c3d64c23917cc884e4b)
[MODERATION] Show graceful error on comment creation (squash) typo
(cherry picked from commit 1588d4834a37a744f092f2aeea6c9ef4795d7356)
(cherry picked from commit d510ea52d091503e841d66f2f604348add8b4535)
(cherry picked from commit 8249e93a14f628bb0e89fe3be678e4966539944e)
[MODERATION] Refactor integration testing (squash)
- Motivation for this PR is that I'd noticed that a lot of repeated
calls are happening between the test functions and that certain tests
weren't using helper functions like `GetCSRF`, therefor this refactor of
the integration tests to keep it: clean, small and hopefully more
maintainable and understandable.
- There are now three integration tests: `TestBlockUser`,
`TestBlockUserFromOrganization` and `TestBlockActions` (and has been
moved in that order in the source code).
- `TestBlockUser` is for doing blocking related actions as an user and
`TestBlockUserFromOrganization` as an organisation, even though they
execute the same kind of tests they do not share any database calls or
logic and therefor it currently doesn't make sense to merge them
together (hopefully such oppurtinutiy might be presented in the future).
- `TestBlockActions` now contain all tests for actions that should be
blocked after blocking has happened, most tests now share the same doer
and blocked users and a extra fixture has been added to make this
possible for the comment test.
- Less code, more comments and more re-use between tests.
(cherry picked from commit ffb393213d2f1269aad3c019d039cf60d0fe4b10)
(cherry picked from commit 85505e0f815fede589c272d301c95204f9596985)
(cherry picked from commit 0f3cf17761f6caedb17550f69de96990c2090af1)
[MODERATION] Fix network error (squash)
- Fix network error toast messages on user actions such as follow and
unfollow. This happened because the javascript code now expects an JSON
to be returned, but this wasn't the case due to
cfa539e590127b4953b010fba3dea21c82a1714.
- The integration testing has been adjusted to instead test for the
returned flash cookie.
(cherry picked from commit 112bc25e548d317a4ee00f9efa9068794a733e3b)
(cherry picked from commit 1194fe4899eb39dcb9a2410032ad0cc67a62b92b)
(cherry picked from commit 9abb95a8441e227874fe156095349a3173cc5a81)
[MODERATION] Modernize frontend (squash)
- Unify blocked users list.
- Use the new flex list classes for blocked users list to avoid using
the CSS helper classes and thereby be consistent in the design.
- Fix the modal by using the new modal class.
- Remove the icon in the modal as looks too big in the new design.
- Fix avatar not displaying as it was passing the context where the user
should've been passed.
- Don't use italics for 'Blocked since' text.
- Use namelink template to display the user's name and homelink.
(cherry picked from commit ec935a16a319b14e819ead828d1d9875280d9259)
(cherry picked from commit 67f37c83461aa393c53a799918e9708cb9b89b30)
Conflicts:
models/user/follow.go
models/user/user_test.go
routers/api/v1/user/follower.go
routers/web/shared/user/header.go
routers/web/user/profile.go
templates/swagger/v1_json.tmpl
https://codeberg.org/forgejo/forgejo/pulls/1468
(cherry picked from commit 6a9626839c6342cd2767ea12757ee2f78eaf443b)
Conflicts:
tests/integration/api_nodeinfo_test.go
https://codeberg.org/forgejo/forgejo/pulls/1508#issuecomment-1242385
(cherry picked from commit 7378b251b481ed1e60e816caf8f649e8397ee5fc)
Conflicts:
models/fixtures/watch.yml
models/issues/reaction.go
models/issues/reaction_test.go
routers/api/v1/repo/issue_reaction.go
routers/web/repo/issue.go
services/issue/issue.go
https://codeberg.org/forgejo/forgejo/pulls/1547
(cherry picked from commit c2028930c101223820de0bbafc318e9394c347b8)
(cherry picked from commit d3f9134aeeef784586e8412e8dbba0a8fceb0cd4)
(cherry picked from commit 7afe154c5c40bcc65accdf51c9224b2f7627a684)
(cherry picked from commit 99ac7353eb1e834a77fe42aa89208791cc2364ff)
(cherry picked from commit a9cde00c5c25ea8c427967cb7ab57abb618e44cb)
Conflicts:
services/user/delete.go
https://codeberg.org/forgejo/forgejo/pulls/1736
(cherry picked from commit 008c0cc63d1a3b8eb694bffbf77a7b25c56afd57)
[DEADCODE] add exceptions
(cherry picked from commit 12ddd2b10e3309f6430b0af42855c6af832832ee)
[MODERATION] Remove deadcode (squash)
- Remove deadcode that's no longer used by Forgejo.
(cherry picked from commit 0faeab4fa9b0aa59f86760b24ecbc07815026c82)
[MODERATION] Add repo transfers to blocked functionality (squash)
- When someone gets blocked, remove all pending repository transfers
from the blocked user to the doer.
- Do not allow to start transferring repositories to the doer as blocked user.
- Added unit testing.
- Added integration testing.
(cherry picked from commit 8a3caac33013482ddbee2fa51510c6918ba54466)
(cherry picked from commit a92b4cfeb63b90eb2d90d0feb51cec62e0502d84)
(cherry picked from commit acaaaf07d999974dbe5f9c5e792621c597bfb542)
(cherry picked from commit 735818863c1793aa6f6983afedc4bd3b36026ca5)
(cherry picked from commit f50fa43b32160d0d88eca1dbdca09b5f575fb62b)
(cherry picked from commit e16683643388fb3c60ea478f1419a6af4f4aa283)
(cherry picked from commit 82a0e4a3814a66ce44be6a031bdf08484586c61b)
(cherry picked from commit ff233c19c4a5edcc2b99a6f41a2d19dbe8c08b3b)
(cherry picked from commit 8ad87d215f2b6adb978de77e53ba2bf7ea571430)
[MODERATION] Fix unblock action (squash)
- Pass the whole context instead of only giving pieces.
- This fixes CSRF not correctly being inserted into the unblock buttons.
(cherry picked from commit 2aa51922ba6a0ea2f8644277baa74fc8f34ab95a)
(cherry picked from commit 7ee8db0f018340bc97f125415503e3e5db5f5082)
(cherry picked from commit e4f8b999bcd3b68b3ef7f54f5b17c3ada0308121)
(cherry picked from commit 05aea60b1302bbd3ea574a9c6c34e1005a5d73bf)
(cherry picked from commit dc0d61b012cfaf2385f71e97cda5f220b58b9fa4)
(cherry picked from commit f53fa583de671ff60a0a1d0f3ab8c260e1ba4e1f)
(cherry picked from commit c65b89a58d11b32009c710c2f5e75f0cd3539395)
(cherry picked from commit 69e50b9969db3ab71cefaed520757876a9629a5c)
(cherry picked from commit ec127440b86cb5fcf51799d8bd76a9fd6b9cebcc)
[MODERATION] cope with shared fixtures
* There is one more issue in the fixtures and this breaks some tests
* The users in the shared fixtures were renamed for clarity and that
breaks some tests
(cherry picked from commit 707a4edbdf67d0eb168d7bb430cf85dd8cd63c52)
Conflicts:
modules/indexer/issues/indexer_test.go
https://codeberg.org/forgejo/forgejo/pulls/1508
(cherry picked from commit 82cc044366c749df80ffad44eed2988b8e64211e)
(cherry picked from commit 2776aec7e85850f1d7f01a090a72491550fb9d29)
(cherry picked from commit 1fbde36dc784b5b2cc6193f02ff0d436b0f2a629)
(cherry picked from commit 1293db3c4e5df218501f5add9f9d41101ffcb8aa)
(cherry picked from commit 6476802175bac3ef78dd8f24ff6bebc16f398a78)
(cherry picked from commit 5740f2fc830356acb7929a02fe304008b94a0ca5)
(cherry picked from commit afc12d7b6e9b773fa89718aa79cd95c0e0ce4406)
[MODERATION] Fix transfer confirmation (squash)
- Fix problem caused by the clearer confirmation for dangerous actions commit.
(cherry picked from commit 3488f4a9cb1f7f73103ae0017d644f13ca3ab798)
(cherry picked from commit ed7de91f6ace23a1459bc6552edf719d62c7c941)
(cherry picked from commit 2d97929b9b7b8d979eb12bf0994d3f169d41f7fd)
(cherry picked from commit 50d035a7b058b9c4486c38cd4be0b02a4e1bf4d9)
(cherry picked from commit 0a0c07d78a1dee3489b97ab359bb957e3f7fb94b)
(cherry picked from commit 85e55c4dbc2f513f3d5254dac20915e8c3c22886)
(cherry picked from commit d8282122ad6e8b497de35d1ed89e3093a2cd5ee2)
(cherry picked from commit 3f0b3b6cc582c3d672d371dd9fe1203a56cb88c0)
[MODERATION] Purge issues on user deletion (squash)
(cherry picked from commit 4f529d9596ffbfc4e754c28830ba028f6344dc5b)
(cherry picked from commit f0e3acadd321fcb99e8ea3e3ce1c69df25c4ca4d)
(cherry picked from commit 682c4effe69dc0d4ed304fa7ce6259d9ce573629)
(cherry picked from commit e43c2d84fd4b6fd31e2370cec1034262d12e5c34)
(cherry picked from commit 9c8e53ccc78053026e4f667889959c23c8d95934)
(cherry picked from commit a9eb7ac783b2c16ee3702a88203bf857cb4147fc)
[MODERATION] Purge issues on user deletion (squash) revert shared fixtures workarounds
(cherry picked from commit 7224653a40e32186892e89bfedd49edecf5b8f81)
(cherry picked from commit aa6e8672f9473a9100e7575051dec9eda37709a0)
(cherry picked from commit 58c7947e95648f50237ddcd46b6bd025b224a70f)
(cherry picked from commit f1aacb1851b232082febcd7870a40a56de3855a6)
(cherry picked from commit 0bf174af87f7de9a8d869304f709e2bf41f3dde9)
(cherry picked from commit f9706f4335df3b7688ed60853d917efa72fb464a)
[MODERATION] Prepare moderation for context locale changes (squash)
- Resolves https://codeberg.org/forgejo/forgejo/issues/1711
(cherry picked from commit 2e289baea943dcece88f02d110b03d344308a261)
(cherry picked from commit 97b16bc19ae680db62608d6020b00fe5ac451c60)
[MODERATION] User blocking (squash) do not use shared fixture
It conflicts with a fixtured added in the commit
Fix comment permissions (#28213) (#28216)
(cherry picked from commit ab40799dcab24e9f495d765268b791931da81684)
(cherry picked from commit 996c92cafdb5b33a6d2d05d94038e950d97eb7de)
(cherry picked from commit 259912e3a69071c5ad57871464d0b79f69a8e72c)
Conflicts:
options/locale/locale_en-US.ini
https://codeberg.org/forgejo/forgejo/pulls/1921
(cherry picked from commit 1e82abc032c18015b92c93a7617a5dd06d50bd2d)
(cherry picked from commit a176fee1607d571b25b345184f1c50d403029610)
(cherry picked from commit 0480b76dfeda968849e900da9454a3efd82590fa)
(cherry picked from commit 4bc06b7b3841c74e3d790b1ef635c2b382ca7123)
(cherry picked from commit 073094cf722a927a623408d66537c758d7d64e4c)
2023-08-14 19:07:38 -04:00
// Check if the doer is not blocked by the repository's owner.
if user_model . IsBlocked ( ctx , repo . OwnerID , issue . PosterID ) {
return user_model . ErrBlockedByUser
}
2023-08-09 22:39:21 -04:00
prCtx , cancel , err := createTemporaryRepoForPR ( ctx , pr )
2020-04-14 09:53:34 -04:00
if err != nil {
2023-08-09 22:39:21 -04:00
if ! git_model . IsErrBranchNotExist ( err ) {
log . Error ( "CreateTemporaryRepoForPR %-v: %v" , pr , err )
2019-10-28 12:45:43 -04:00
}
2023-08-09 22:39:21 -04:00
return err
2019-10-28 12:45:43 -04:00
}
2023-08-09 22:39:21 -04:00
defer cancel ( )
2019-10-28 12:45:43 -04:00
2023-08-09 22:39:21 -04:00
if err := testPatch ( ctx , prCtx , pr ) ; err != nil {
2019-12-14 22:28:51 -05:00
return err
}
2023-08-09 22:39:21 -04:00
divergence , err := git . GetDivergingCommits ( ctx , prCtx . tmpBasePath , baseBranch , trackingBranch )
2021-01-02 12:04:02 -05:00
if err != nil {
return err
}
2023-08-09 22:39:21 -04:00
pr . CommitsAhead = divergence . Ahead
pr . CommitsBehind = divergence . Behind
2021-01-02 12:04:02 -05:00
2023-08-09 22:39:21 -04:00
assigneeCommentMap := make ( map [ int64 ] * issues_model . Comment )
2019-09-26 20:22:36 -04:00
2020-05-20 08:47:24 -04:00
// add first push codes comment
2023-08-09 22:39:21 -04:00
baseGitRepo , err := git . OpenRepository ( ctx , pr . BaseRepo . RepoPath ( ) )
2020-05-20 08:47:24 -04:00
if err != nil {
return err
}
defer baseGitRepo . Close ( )
2023-08-09 22:39:21 -04:00
if err := db . WithTx ( ctx , func ( ctx context . Context ) error {
if err := issues_model . NewPullRequest ( ctx , repo , issue , labelIDs , uuids , pr ) ; err != nil {
return err
}
for _ , assigneeID := range assigneeIDs {
comment , err := issue_service . AddAssigneeIfNotAssigned ( ctx , issue , issue . Poster , assigneeID , false )
if err != nil {
return err
}
assigneeCommentMap [ assigneeID ] = comment
}
pr . Issue = issue
issue . PullRequest = pr
if pr . Flow == issues_model . PullRequestFlowGithub {
err = PushToBaseRepo ( ctx , pr )
} else {
err = UpdateRef ( ctx , pr )
}
if err != nil {
return err
}
compareInfo , err := baseGitRepo . GetCompareInfo ( pr . BaseRepo . RepoPath ( ) ,
git . BranchPrefix + pr . BaseBranch , pr . GetGitRefName ( ) , false , false )
if err != nil {
return err
}
if len ( compareInfo . Commits ) == 0 {
return nil
}
2020-05-20 08:47:24 -04:00
2022-06-13 05:37:59 -04:00
data := issues_model . PushActionContent { IsForcePush : false }
2021-08-09 14:08:51 -04:00
data . CommitIDs = make ( [ ] string , 0 , len ( compareInfo . Commits ) )
for i := len ( compareInfo . Commits ) - 1 ; i >= 0 ; i -- {
data . CommitIDs = append ( data . CommitIDs , compareInfo . Commits [ i ] . ID . String ( ) )
2020-05-20 08:47:24 -04:00
}
dataJSON , err := json . Marshal ( data )
if err != nil {
return err
}
2022-06-13 05:37:59 -04:00
ops := & issues_model . CreateCommentOptions {
Type : issues_model . CommentTypePullRequestPush ,
2023-08-09 22:39:21 -04:00
Doer : issue . Poster ,
2020-05-20 08:47:24 -04:00
Repo : repo ,
Issue : pr . Issue ,
IsForcePush : false ,
Content : string ( dataJSON ) ,
}
2023-08-09 22:39:21 -04:00
if _ , err = issues_model . CreateComment ( ctx , ops ) ; err != nil {
return err
}
2023-06-08 04:56:05 -04:00
2023-10-11 00:24:07 -04:00
if ! pr . IsWorkInProgress ( ctx ) {
2023-08-09 22:39:21 -04:00
if err := issues_model . PullRequestCodeOwnersReview ( ctx , issue , pr ) ; err != nil {
2023-06-08 04:56:05 -04:00
return err
}
}
2023-08-09 22:39:21 -04:00
return nil
} ) ; err != nil {
// cleanup: this will only remove the reference, the real commit will be clean up when next GC
if err1 := baseGitRepo . RemoveReference ( pr . GetGitRefName ( ) ) ; err1 != nil {
log . Error ( "RemoveReference: %v" , err1 )
}
return err
}
baseGitRepo . Close ( ) // close immediately to avoid notifications will open the repository again
2023-06-08 04:56:05 -04:00
2023-08-09 22:39:21 -04:00
mentions , err := issues_model . FindAndUpdateIssueMentions ( ctx , issue , issue . Poster , issue . Content )
if err != nil {
return err
}
2023-09-05 14:37:47 -04:00
notify_service . NewPullRequest ( ctx , pr , mentions )
2023-08-09 22:39:21 -04:00
if len ( issue . Labels ) > 0 {
2023-09-05 14:37:47 -04:00
notify_service . IssueChangeLabels ( ctx , issue . Poster , issue , issue . Labels , nil )
2023-08-09 22:39:21 -04:00
}
if issue . Milestone != nil {
2023-09-05 14:37:47 -04:00
notify_service . IssueChangeMilestone ( ctx , issue . Poster , issue , 0 )
2023-08-09 22:39:21 -04:00
}
2023-10-06 02:49:37 -04:00
for _ , assigneeID := range assigneeIDs {
assignee , err := user_model . GetUserByID ( ctx , assigneeID )
if err != nil {
return ErrDependenciesLeft
2023-08-09 22:39:21 -04:00
}
2023-10-06 02:49:37 -04:00
notify_service . IssueChangeAssignee ( ctx , issue . Poster , issue , assignee , false , assigneeCommentMap [ assigneeID ] )
2020-05-20 08:47:24 -04:00
}
2019-09-26 20:22:36 -04:00
return nil
}
2019-10-14 23:28:40 -04:00
2019-12-16 01:20:25 -05:00
// ChangeTargetBranch changes the target branch of this pull request, as the given user.
2022-06-13 05:37:59 -04:00
func ChangeTargetBranch ( ctx context . Context , pr * issues_model . PullRequest , doer * user_model . User , targetBranch string ) ( err error ) {
2022-05-04 12:06:23 -04:00
pullWorkingPool . CheckIn ( fmt . Sprint ( pr . ID ) )
defer pullWorkingPool . CheckOut ( fmt . Sprint ( pr . ID ) )
2019-12-16 01:20:25 -05:00
// Current target branch is already the same
if pr . BaseBranch == targetBranch {
return nil
}
if pr . Issue . IsClosed {
2022-06-13 05:37:59 -04:00
return issues_model . ErrIssueIsClosed {
2019-12-16 01:20:25 -05:00
ID : pr . Issue . ID ,
RepoID : pr . Issue . RepoID ,
Index : pr . Issue . Index ,
}
}
if pr . HasMerged {
return models . ErrPullRequestHasMerged {
ID : pr . ID ,
IssueID : pr . Index ,
HeadRepoID : pr . HeadRepoID ,
BaseRepoID : pr . BaseRepoID ,
HeadBranch : pr . HeadBranch ,
BaseBranch : pr . BaseBranch ,
}
}
// Check if branches are equal
2022-01-19 18:26:57 -05:00
branchesEqual , err := IsHeadEqualWithBranch ( ctx , pr , targetBranch )
2019-12-16 01:20:25 -05:00
if err != nil {
return err
}
if branchesEqual {
2023-06-29 06:03:20 -04:00
return git_model . ErrBranchesEqual {
2019-12-16 01:20:25 -05:00
HeadBranchName : pr . HeadBranch ,
BaseBranchName : targetBranch ,
}
}
// Check if pull request for the new target branch already exists
2022-11-19 03:12:33 -05:00
existingPr , err := issues_model . GetUnmergedPullRequest ( ctx , pr . HeadRepoID , pr . BaseRepoID , pr . HeadBranch , targetBranch , issues_model . PullRequestFlowGithub )
2019-12-16 01:20:25 -05:00
if existingPr != nil {
2022-06-13 05:37:59 -04:00
return issues_model . ErrPullRequestAlreadyExists {
2019-12-16 01:20:25 -05:00
ID : existingPr . ID ,
IssueID : existingPr . Index ,
HeadRepoID : existingPr . HeadRepoID ,
BaseRepoID : existingPr . BaseRepoID ,
HeadBranch : existingPr . HeadBranch ,
BaseBranch : existingPr . BaseBranch ,
}
}
2022-06-13 05:37:59 -04:00
if err != nil && ! issues_model . IsErrPullRequestNotExist ( err ) {
2019-12-16 01:20:25 -05:00
return err
}
// Set new target branch
oldBranch := pr . BaseBranch
pr . BaseBranch = targetBranch
// Refresh patch
if err := TestPatch ( pr ) ; err != nil {
return err
}
// Update target branch, PR diff and status
// This is the same as checkAndUpdateStatus in check service, but also updates base_branch
2022-06-13 05:37:59 -04:00
if pr . Status == issues_model . PullRequestStatusChecking {
pr . Status = issues_model . PullRequestStatusMergeable
2019-12-16 01:20:25 -05:00
}
2020-06-16 13:52:33 -04:00
// Update Commit Divergence
2022-01-19 18:26:57 -05:00
divergence , err := GetDiverging ( ctx , pr )
2020-06-16 13:52:33 -04:00
if err != nil {
return err
}
pr . CommitsAhead = divergence . Ahead
pr . CommitsBehind = divergence . Behind
2022-11-19 03:12:33 -05:00
if err := pr . UpdateColsIfNotMerged ( ctx , "merge_base" , "status" , "conflicted_files" , "changed_protected_files" , "base_branch" , "commits_ahead" , "commits_behind" ) ; err != nil {
2019-12-16 01:20:25 -05:00
return err
}
// Create comment
2022-06-13 05:37:59 -04:00
options := & issues_model . CreateCommentOptions {
Type : issues_model . CommentTypeChangeTargetBranch ,
2019-12-16 01:20:25 -05:00
Doer : doer ,
Repo : pr . Issue . Repo ,
Issue : pr . Issue ,
OldRef : oldBranch ,
NewRef : targetBranch ,
}
2023-08-04 09:34:34 -04:00
if _ , err = issues_model . CreateComment ( ctx , options ) ; err != nil {
2022-10-24 15:29:17 -04:00
return fmt . Errorf ( "CreateChangeTargetBranchComment: %w" , err )
2019-12-16 01:20:25 -05:00
}
return nil
}
2022-06-13 05:37:59 -04:00
func checkForInvalidation ( ctx context . Context , requests issues_model . PullRequestList , repoID int64 , doer * user_model . User , branch string ) error {
2022-12-02 21:48:26 -05:00
repo , err := repo_model . GetRepositoryByID ( ctx , repoID )
2019-10-14 23:28:40 -04:00
if err != nil {
2022-11-19 03:12:33 -05:00
return fmt . Errorf ( "GetRepositoryByIDCtx: %w" , err )
2019-10-14 23:28:40 -04:00
}
2022-03-29 15:13:41 -04:00
gitRepo , err := git . OpenRepository ( ctx , repo . RepoPath ( ) )
2019-10-14 23:28:40 -04:00
if err != nil {
2022-10-24 15:29:17 -04:00
return fmt . Errorf ( "git.OpenRepository: %w" , err )
2019-10-14 23:28:40 -04:00
}
go func ( ) {
2019-12-15 04:51:28 -05:00
// FIXME: graceful: We need to tell the manager we're doing something...
2023-01-17 16:03:44 -05:00
err := InvalidateCodeComments ( ctx , requests , doer , gitRepo , branch )
2019-10-14 23:28:40 -04:00
if err != nil {
log . Error ( "PullRequestList.InvalidateCodeComments: %v" , err )
}
2019-11-13 02:01:19 -05:00
gitRepo . Close ( )
2019-10-14 23:28:40 -04:00
} ( )
return nil
}
// AddTestPullRequestTask adds new test tasks by given head/base repository and head/base branch,
// and generate new patch for testing as needed.
2021-11-24 04:49:20 -05:00
func AddTestPullRequestTask ( doer * user_model . User , repoID int64 , branch string , isSync bool , oldCommitID , newCommitID string ) {
2019-10-14 23:28:40 -04:00
log . Trace ( "AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests" , repoID , branch )
2019-12-15 04:51:28 -05:00
graceful . GetManager ( ) . RunWithShutdownContext ( func ( ctx context . Context ) {
// There is no sensible way to shut this down ":-("
// If you don't let it run all the way then you will lose data
2022-05-07 13:05:52 -04:00
// TODO: graceful: AddTestPullRequestTask needs to become a queue!
2019-10-14 23:28:40 -04:00
2023-05-08 02:39:32 -04:00
// GetUnmergedPullRequestsByHeadInfo() only return open and unmerged PR.
2023-07-22 10:14:27 -04:00
prs , err := issues_model . GetUnmergedPullRequestsByHeadInfo ( ctx , repoID , branch )
2019-12-15 04:51:28 -05:00
if err != nil {
log . Error ( "Find pull requests [head_repo_id: %d, head_branch: %s]: %v" , repoID , branch , err )
return
2019-10-14 23:28:40 -04:00
}
2019-12-15 04:51:28 -05:00
2023-02-05 06:57:38 -05:00
for _ , pr := range prs {
log . Trace ( "Updating PR[%d]: composing new test task" , pr . ID )
if pr . Flow == issues_model . PullRequestFlowGithub {
if err := PushToBaseRepo ( ctx , pr ) ; err != nil {
log . Error ( "PushToBaseRepo: %v" , err )
continue
}
} else {
continue
}
2023-07-22 10:14:27 -04:00
AddToTaskQueue ( ctx , pr )
2023-02-05 06:57:38 -05:00
comment , err := CreatePushPullComment ( ctx , doer , pr , oldCommitID , newCommitID )
2023-05-08 02:39:32 -04:00
if err == nil && comment != nil {
2023-09-05 14:37:47 -04:00
notify_service . PullRequestPushCommits ( ctx , doer , pr , comment )
2023-02-05 06:57:38 -05:00
}
}
2019-12-15 04:51:28 -05:00
if isSync {
2022-06-13 05:37:59 -04:00
requests := issues_model . PullRequestList ( prs )
2023-07-22 10:14:27 -04:00
if err = requests . LoadAttributes ( ctx ) ; err != nil {
2019-12-15 04:51:28 -05:00
log . Error ( "PullRequestList.LoadAttributes: %v" , err )
}
2022-01-19 18:26:57 -05:00
if invalidationErr := checkForInvalidation ( ctx , requests , repoID , doer , branch ) ; invalidationErr != nil {
2019-12-15 04:51:28 -05:00
log . Error ( "checkForInvalidation: %v" , invalidationErr )
}
if err == nil {
for _ , pr := range prs {
2023-12-13 16:02:00 -05:00
objectFormat , _ := git . GetObjectFormatOfRepo ( ctx , pr . BaseRepo . RepoPath ( ) )
2023-12-17 06:56:08 -05:00
if newCommitID != "" && newCommitID != objectFormat . EmptyObjectID ( ) . String ( ) {
2022-01-19 18:26:57 -05:00
changed , err := checkIfPRContentChanged ( ctx , pr , oldCommitID , newCommitID )
2020-01-08 20:47:45 -05:00
if err != nil {
log . Error ( "checkIfPRContentChanged: %v" , err )
}
if changed {
// Mark old reviews as stale if diff to mergebase has changed
2023-09-29 08:12:54 -04:00
if err := issues_model . MarkReviewsAsStale ( ctx , pr . IssueID ) ; err != nil {
2020-01-08 20:47:45 -05:00
log . Error ( "MarkReviewsAsStale: %v" , err )
}
2023-07-20 03:18:52 -04:00
// dismiss all approval reviews if protected branch rule item enabled.
pb , err := git_model . GetFirstMatchProtectedBranchRule ( ctx , pr . BaseRepoID , pr . BaseBranch )
if err != nil {
log . Error ( "GetFirstMatchProtectedBranchRule: %v" , err )
}
if pb != nil && pb . DismissStaleApprovals {
if err := DismissApprovalReviews ( ctx , doer , pr ) ; err != nil {
log . Error ( "DismissApprovalReviews: %v" , err )
}
}
2020-01-08 20:47:45 -05:00
}
2023-09-29 08:12:54 -04:00
if err := issues_model . MarkReviewsAsNotStale ( ctx , pr . IssueID , newCommitID ) ; err != nil {
2020-01-08 20:47:45 -05:00
log . Error ( "MarkReviewsAsNotStale: %v" , err )
}
2022-01-19 18:26:57 -05:00
divergence , err := GetDiverging ( ctx , pr )
2020-04-14 09:53:34 -04:00
if err != nil {
log . Error ( "GetDiverging: %v" , err )
} else {
2022-05-20 10:08:52 -04:00
err = pr . UpdateCommitDivergence ( ctx , divergence . Ahead , divergence . Behind )
2020-04-14 09:53:34 -04:00
if err != nil {
log . Error ( "UpdateCommitDivergence: %v" , err )
}
}
2020-01-08 20:47:45 -05:00
}
2023-09-05 14:37:47 -04:00
notify_service . PullRequestSynchronized ( ctx , doer , pr )
2019-12-15 04:51:28 -05:00
}
2019-10-14 23:28:40 -04:00
}
}
2019-12-15 04:51:28 -05:00
log . Trace ( "AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests" , repoID , branch )
2023-07-22 10:14:27 -04:00
prs , err = issues_model . GetUnmergedPullRequestsByBaseInfo ( ctx , repoID , branch )
2019-12-15 04:51:28 -05:00
if err != nil {
log . Error ( "Find pull requests [base_repo_id: %d, base_branch: %s]: %v" , repoID , branch , err )
return
}
for _ , pr := range prs {
2022-01-19 18:26:57 -05:00
divergence , err := GetDiverging ( ctx , pr )
2020-04-14 09:53:34 -04:00
if err != nil {
2023-06-29 06:03:20 -04:00
if git_model . IsErrBranchNotExist ( err ) && ! git . IsBranchExist ( ctx , pr . HeadRepo . RepoPath ( ) , pr . HeadBranch ) {
2021-07-12 19:26:25 -04:00
log . Warn ( "Cannot test PR %s/%d: head_branch %s no longer exists" , pr . BaseRepo . Name , pr . IssueID , pr . HeadBranch )
} else {
log . Error ( "GetDiverging: %v" , err )
}
2020-04-14 09:53:34 -04:00
} else {
2022-05-20 10:08:52 -04:00
err = pr . UpdateCommitDivergence ( ctx , divergence . Ahead , divergence . Behind )
2020-04-14 09:53:34 -04:00
if err != nil {
log . Error ( "UpdateCommitDivergence: %v" , err )
}
}
2023-07-22 10:14:27 -04:00
AddToTaskQueue ( ctx , pr )
2019-12-15 04:51:28 -05:00
}
} )
2019-10-14 23:28:40 -04:00
}
2019-12-14 22:28:51 -05:00
2020-01-08 20:47:45 -05:00
// checkIfPRContentChanged checks if diff to target branch has changed by push
// A commit can be considered to leave the PR untouched if the patch/diff with its merge base is unchanged
2022-06-13 05:37:59 -04:00
func checkIfPRContentChanged ( ctx context . Context , pr * issues_model . PullRequest , oldCommitID , newCommitID string ) ( hasChanged bool , err error ) {
2023-03-07 15:07:35 -05:00
prCtx , cancel , err := createTemporaryRepoForPR ( ctx , pr )
2020-01-08 20:47:45 -05:00
if err != nil {
2023-03-07 15:07:35 -05:00
log . Error ( "CreateTemporaryRepoForPR %-v: %v" , pr , err )
2023-01-28 10:54:40 -05:00
return false , err
2020-01-08 20:47:45 -05:00
}
2023-03-07 15:07:35 -05:00
defer cancel ( )
2023-01-28 10:54:40 -05:00
2023-03-07 15:07:35 -05:00
tmpRepo , err := git . OpenRepository ( ctx , prCtx . tmpBasePath )
2020-01-08 20:47:45 -05:00
if err != nil {
2023-01-28 10:54:40 -05:00
return false , fmt . Errorf ( "OpenRepository: %w" , err )
2020-01-08 20:47:45 -05:00
}
2023-01-28 10:54:40 -05:00
defer tmpRepo . Close ( )
2020-01-08 20:47:45 -05:00
2023-01-28 10:54:40 -05:00
// Find the merge-base
_ , base , err := tmpRepo . GetMergeBase ( "" , "base" , "tracking" )
if err != nil {
return false , fmt . Errorf ( "GetMergeBase: %w" , err )
2020-01-08 20:47:45 -05:00
}
2023-01-28 10:54:40 -05:00
cmd := git . NewCommand ( ctx , "diff" , "--name-only" , "-z" ) . AddDynamicArguments ( newCommitID , oldCommitID , base )
stdoutReader , stdoutWriter , err := os . Pipe ( )
if err != nil {
return false , fmt . Errorf ( "unable to open pipe for to run diff: %w" , err )
}
2024-01-08 21:32:14 -05:00
stderr := new ( bytes . Buffer )
2023-01-28 10:54:40 -05:00
if err := cmd . Run ( & git . RunOpts {
2023-03-07 15:07:35 -05:00
Dir : prCtx . tmpBasePath ,
2023-01-28 10:54:40 -05:00
Stdout : stdoutWriter ,
2024-01-08 21:32:14 -05:00
Stderr : stderr ,
2023-01-28 10:54:40 -05:00
PipelineFunc : func ( ctx context . Context , cancel context . CancelFunc ) error {
_ = stdoutWriter . Close ( )
defer func ( ) {
_ = stdoutReader . Close ( )
} ( )
return util . IsEmptyReader ( stdoutReader )
} ,
} ) ; err != nil {
if err == util . ErrNotEmpty {
2020-01-08 20:47:45 -05:00
return true , nil
}
2024-01-08 21:32:14 -05:00
err = git . ConcatenateError ( err , stderr . String ( ) )
2020-01-08 20:47:45 -05:00
2023-01-28 10:54:40 -05:00
log . Error ( "Unable to run diff on %s %s %s in tempRepo for PR[%d]%s/%s...%s/%s: Error: %v" ,
newCommitID , oldCommitID , base ,
pr . ID , pr . BaseRepo . FullName ( ) , pr . BaseBranch , pr . HeadRepo . FullName ( ) , pr . HeadBranch ,
err )
return false , fmt . Errorf ( "Unable to run git diff --name-only -z %s %s %s: %w" , newCommitID , oldCommitID , base , err )
2020-01-08 20:47:45 -05:00
}
return false , nil
}
2019-12-14 22:28:51 -05:00
// PushToBaseRepo pushes commits from branches of head repository to
// corresponding branches of base repository.
// FIXME: Only push branches that are actually updates?
2022-06-13 05:37:59 -04:00
func PushToBaseRepo ( ctx context . Context , pr * issues_model . PullRequest ) ( err error ) {
2022-01-19 18:26:57 -05:00
return pushToBaseRepoHelper ( ctx , pr , "" )
2021-06-23 17:08:26 -04:00
}
2022-06-13 05:37:59 -04:00
func pushToBaseRepoHelper ( ctx context . Context , pr * issues_model . PullRequest , prefixHeadBranch string ) ( err error ) {
2019-12-14 22:28:51 -05:00
log . Trace ( "PushToBaseRepo[%d]: pushing commits to base repo '%s'" , pr . BaseRepoID , pr . GetGitRefName ( ) )
2022-11-19 03:12:33 -05:00
if err := pr . LoadHeadRepo ( ctx ) ; err != nil {
2020-02-21 13:18:13 -05:00
log . Error ( "Unable to load head repository for PR[%d] Error: %v" , pr . ID , err )
return err
}
2019-12-14 22:28:51 -05:00
headRepoPath := pr . HeadRepo . RepoPath ( )
2020-01-28 05:23:58 -05:00
2022-11-19 03:12:33 -05:00
if err := pr . LoadBaseRepo ( ctx ) ; err != nil {
2020-02-21 13:18:13 -05:00
log . Error ( "Unable to load base repository for PR[%d] Error: %v" , pr . ID , err )
return err
}
2020-09-14 23:32:31 -04:00
baseRepoPath := pr . BaseRepo . RepoPath ( )
2019-12-14 22:28:51 -05:00
2022-11-19 03:12:33 -05:00
if err = pr . LoadIssue ( ctx ) ; err != nil {
2022-10-24 15:29:17 -04:00
return fmt . Errorf ( "unable to load issue %d for pr %d: %w" , pr . IssueID , pr . ID , err )
2019-12-27 16:15:04 -05:00
}
2022-11-19 03:12:33 -05:00
if err = pr . Issue . LoadPoster ( ctx ) ; err != nil {
2022-10-24 15:29:17 -04:00
return fmt . Errorf ( "unable to load poster %d for pr %d: %w" , pr . Issue . PosterID , pr . ID , err )
2019-12-27 16:15:04 -05:00
}
2020-09-14 23:32:31 -04:00
gitRefName := pr . GetGitRefName ( )
2022-01-19 18:26:57 -05:00
if err := git . Push ( ctx , headRepoPath , git . PushOptions {
2020-09-14 23:32:31 -04:00
Remote : baseRepoPath ,
2021-06-23 17:08:26 -04:00
Branch : prefixHeadBranch + pr . HeadBranch + ":" + gitRefName ,
2019-12-14 22:28:51 -05:00
Force : true ,
2019-12-27 16:15:04 -05:00
// Use InternalPushingEnvironment here because we know that pre-receive and post-receive do not run on a refs/pulls/...
2022-05-08 12:46:32 -04:00
Env : repo_module . InternalPushingEnvironment ( pr . Issue . Poster , pr . BaseRepo ) ,
2019-12-14 22:28:51 -05:00
} ) ; err != nil {
2020-06-08 14:07:41 -04:00
if git . IsErrPushOutOfDate ( err ) {
// This should not happen as we're using force!
2020-09-14 23:32:31 -04:00
log . Error ( "Unable to push PR head for %s#%d (%-v:%s) due to ErrPushOfDate: %v" , pr . BaseRepo . FullName ( ) , pr . Index , pr . BaseRepo , gitRefName , err )
2020-06-08 14:07:41 -04:00
return err
} else if git . IsErrPushRejected ( err ) {
rejectErr := err . ( * git . ErrPushRejected )
2020-09-14 23:32:31 -04:00
log . Info ( "Unable to push PR head for %s#%d (%-v:%s) due to rejection:\nStdout: %s\nStderr: %s\nError: %v" , pr . BaseRepo . FullName ( ) , pr . Index , pr . BaseRepo , gitRefName , rejectErr . StdOut , rejectErr . StdErr , rejectErr . Err )
2020-06-08 14:07:41 -04:00
return err
2021-06-23 17:08:26 -04:00
} else if git . IsErrMoreThanOne ( err ) {
if prefixHeadBranch != "" {
log . Info ( "Can't push with %s%s" , prefixHeadBranch , pr . HeadBranch )
return err
}
2022-01-19 18:26:57 -05:00
log . Info ( "Retrying to push with %s%s" , git . BranchPrefix , pr . HeadBranch )
err = pushToBaseRepoHelper ( ctx , pr , git . BranchPrefix )
2021-06-23 17:08:26 -04:00
return err
2020-06-08 14:07:41 -04:00
}
2020-09-14 23:32:31 -04:00
log . Error ( "Unable to push PR head for %s#%d (%-v:%s) due to Error: %v" , pr . BaseRepo . FullName ( ) , pr . Index , pr . BaseRepo , gitRefName , err )
2022-10-24 15:29:17 -04:00
return fmt . Errorf ( "Push: %s:%s %s:%s %w" , pr . HeadRepo . FullName ( ) , pr . HeadBranch , pr . BaseRepo . FullName ( ) , gitRefName , err )
2019-12-14 22:28:51 -05:00
}
return nil
}
2020-01-24 21:48:22 -05:00
2021-07-28 05:42:56 -04:00
// UpdateRef update refs/pull/id/head directly for agit flow pull request
2022-06-13 05:37:59 -04:00
func UpdateRef ( ctx context . Context , pr * issues_model . PullRequest ) ( err error ) {
2021-07-28 05:42:56 -04:00
log . Trace ( "UpdateRef[%d]: upgate pull request ref in base repo '%s'" , pr . ID , pr . GetGitRefName ( ) )
2022-11-19 03:12:33 -05:00
if err := pr . LoadBaseRepo ( ctx ) ; err != nil {
2021-07-28 05:42:56 -04:00
log . Error ( "Unable to load base repository for PR[%d] Error: %v" , pr . ID , err )
return err
}
2022-10-23 10:44:45 -04:00
_ , _ , err = git . NewCommand ( ctx , "update-ref" ) . AddDynamicArguments ( pr . GetGitRefName ( ) , pr . HeadCommitID ) . RunStdString ( & git . RunOpts { Dir : pr . BaseRepo . RepoPath ( ) } )
2021-07-28 05:42:56 -04:00
if err != nil {
log . Error ( "Unable to update ref in base repository for PR[%d] Error: %v" , pr . ID , err )
}
return err
}
2020-01-24 21:48:22 -05:00
type errlist [ ] error
func ( errs errlist ) Error ( ) string {
if len ( errs ) > 0 {
var buf strings . Builder
for i , err := range errs {
if i > 0 {
buf . WriteString ( ", " )
}
buf . WriteString ( err . Error ( ) )
}
return buf . String ( )
}
return ""
}
// CloseBranchPulls close all the pull requests who's head branch is the branch
2023-07-22 10:14:27 -04:00
func CloseBranchPulls ( ctx context . Context , doer * user_model . User , repoID int64 , branch string ) error {
prs , err := issues_model . GetUnmergedPullRequestsByHeadInfo ( ctx , repoID , branch )
2020-01-24 21:48:22 -05:00
if err != nil {
return err
}
2023-07-22 10:14:27 -04:00
prs2 , err := issues_model . GetUnmergedPullRequestsByBaseInfo ( ctx , repoID , branch )
2020-01-24 21:48:22 -05:00
if err != nil {
return err
}
prs = append ( prs , prs2 ... )
2023-07-22 10:14:27 -04:00
if err := issues_model . PullRequestList ( prs ) . LoadAttributes ( ctx ) ; err != nil {
2020-01-24 21:48:22 -05:00
return err
}
var errs errlist
for _ , pr := range prs {
2023-07-22 10:14:27 -04:00
if err = issue_service . ChangeStatus ( ctx , pr . Issue , doer , "" , true ) ; err != nil && ! issues_model . IsErrPullWasClosed ( err ) && ! issues_model . IsErrDependenciesLeft ( err ) {
2020-01-24 21:48:22 -05:00
errs = append ( errs , err )
}
}
if len ( errs ) > 0 {
return errs
}
return nil
}
2021-03-01 12:39:44 -05:00
// CloseRepoBranchesPulls close all pull requests which head branches are in the given repository, but only whose base repo is not in the given repository
2022-01-19 18:26:57 -05:00
func CloseRepoBranchesPulls ( ctx context . Context , doer * user_model . User , repo * repo_model . Repository ) error {
branches , _ , err := git . GetBranchesByPath ( ctx , repo . RepoPath ( ) , 0 , 0 )
2020-01-24 21:48:22 -05:00
if err != nil {
return err
}
var errs errlist
for _ , branch := range branches {
2023-07-22 10:14:27 -04:00
prs , err := issues_model . GetUnmergedPullRequestsByHeadInfo ( ctx , repo . ID , branch . Name )
2020-01-24 21:48:22 -05:00
if err != nil {
return err
}
2023-07-22 10:14:27 -04:00
if err = issues_model . PullRequestList ( prs ) . LoadAttributes ( ctx ) ; err != nil {
2020-01-24 21:48:22 -05:00
return err
}
for _ , pr := range prs {
2021-03-01 12:39:44 -05:00
// If the base repository for this pr is this repository there is no need to close it
// as it is going to be deleted anyway
if pr . BaseRepoID == repo . ID {
continue
}
2023-07-22 10:14:27 -04:00
if err = issue_service . ChangeStatus ( ctx , pr . Issue , doer , "" , true ) ; err != nil && ! issues_model . IsErrPullWasClosed ( err ) {
2020-01-24 21:48:22 -05:00
errs = append ( errs , err )
}
}
}
if len ( errs ) > 0 {
return errs
}
return nil
}
2020-04-10 07:26:37 -04:00
2021-06-25 13:01:43 -04:00
var commitMessageTrailersPattern = regexp . MustCompile ( ` (?:^|\n\n)(?:[\w-]+[ \t]*:[^\n]+\n*(?:[ \t]+[^\n]+\n*)*)+$ ` )
2020-12-21 11:46:14 -05:00
// GetSquashMergeCommitMessages returns the commit messages between head and merge base (if there is one)
2022-06-13 05:37:59 -04:00
func GetSquashMergeCommitMessages ( ctx context . Context , pr * issues_model . PullRequest ) string {
2022-11-19 03:12:33 -05:00
if err := pr . LoadIssue ( ctx ) ; err != nil {
2020-04-10 07:26:37 -04:00
log . Error ( "Cannot load issue %d for PR id %d: Error: %v" , pr . IssueID , pr . ID , err )
return ""
}
2022-11-19 03:12:33 -05:00
if err := pr . Issue . LoadPoster ( ctx ) ; err != nil {
2020-04-10 07:26:37 -04:00
log . Error ( "Cannot load poster %d for pr id %d, index %d Error: %v" , pr . Issue . PosterID , pr . ID , pr . Index , err )
return ""
}
if pr . HeadRepo == nil {
var err error
2022-12-02 21:48:26 -05:00
pr . HeadRepo , err = repo_model . GetRepositoryByID ( ctx , pr . HeadRepoID )
2020-04-10 07:26:37 -04:00
if err != nil {
2022-11-19 03:12:33 -05:00
log . Error ( "GetRepositoryByIdCtx[%d]: %v" , pr . HeadRepoID , err )
2020-04-10 07:26:37 -04:00
return ""
}
}
2022-01-19 18:26:57 -05:00
gitRepo , closer , err := git . RepositoryFromContextOrOpen ( ctx , pr . HeadRepo . RepoPath ( ) )
2020-04-10 07:26:37 -04:00
if err != nil {
log . Error ( "Unable to open head repository: Error: %v" , err )
return ""
}
2022-01-19 18:26:57 -05:00
defer closer . Close ( )
2020-04-10 07:26:37 -04:00
2021-07-28 05:42:56 -04:00
var headCommit * git . Commit
2022-06-13 05:37:59 -04:00
if pr . Flow == issues_model . PullRequestFlowGithub {
2021-07-28 05:42:56 -04:00
headCommit , err = gitRepo . GetBranchCommit ( pr . HeadBranch )
} else {
pr . HeadCommitID , err = gitRepo . GetRefCommitID ( pr . GetGitRefName ( ) )
if err != nil {
log . Error ( "Unable to get head commit: %s Error: %v" , pr . GetGitRefName ( ) , err )
return ""
}
headCommit , err = gitRepo . GetCommit ( pr . HeadCommitID )
}
2020-04-10 07:26:37 -04:00
if err != nil {
log . Error ( "Unable to get head commit: %s Error: %v" , pr . HeadBranch , err )
return ""
}
mergeBase , err := gitRepo . GetCommit ( pr . MergeBase )
if err != nil {
log . Error ( "Unable to get merge base commit: %s Error: %v" , pr . MergeBase , err )
return ""
}
limit := setting . Repository . PullRequest . DefaultMergeMessageCommitsLimit
2021-08-09 14:08:51 -04:00
commits , err := gitRepo . CommitsBetweenLimit ( headCommit , mergeBase , limit , 0 )
2020-04-10 07:26:37 -04:00
if err != nil {
log . Error ( "Unable to get commits between: %s %s Error: %v" , pr . HeadBranch , pr . MergeBase , err )
return ""
}
posterSig := pr . Issue . Poster . NewGitSig ( ) . String ( )
2022-10-12 01:18:26 -04:00
uniqueAuthors := make ( container . Set [ string ] )
2021-08-09 14:08:51 -04:00
authors := make ( [ ] string , 0 , len ( commits ) )
2020-04-10 07:26:37 -04:00
stringBuilder := strings . Builder { }
2020-12-21 11:46:14 -05:00
2021-06-18 18:08:22 -04:00
if ! setting . Repository . PullRequest . PopulateSquashCommentWithCommitMessages {
2021-06-25 13:01:43 -04:00
message := strings . TrimSpace ( pr . Issue . Content )
stringBuilder . WriteString ( message )
2021-06-18 18:08:22 -04:00
if stringBuilder . Len ( ) > 0 {
stringBuilder . WriteRune ( '\n' )
2021-06-25 13:01:43 -04:00
if ! commitMessageTrailersPattern . MatchString ( message ) {
stringBuilder . WriteRune ( '\n' )
}
2021-06-18 18:08:22 -04:00
}
2020-12-21 11:46:14 -05:00
}
2020-11-25 15:08:17 -05:00
// commits list is in reverse chronological order
2021-08-09 14:08:51 -04:00
first := true
for i := len ( commits ) - 1 ; i >= 0 ; i -- {
commit := commits [ i ]
2021-06-18 18:08:22 -04:00
if setting . Repository . PullRequest . PopulateSquashCommentWithCommitMessages {
maxSize := setting . Repository . PullRequest . DefaultMergeMessageSize
if maxSize < 0 || stringBuilder . Len ( ) < maxSize {
var toWrite [ ] byte
2021-08-09 14:08:51 -04:00
if first {
first = false
2021-06-18 18:08:22 -04:00
toWrite = [ ] byte ( strings . TrimPrefix ( commit . CommitMessage , pr . Issue . Title ) )
} else {
toWrite = [ ] byte ( commit . CommitMessage )
}
if len ( toWrite ) > maxSize - stringBuilder . Len ( ) && maxSize > - 1 {
toWrite = append ( toWrite [ : maxSize - stringBuilder . Len ( ) ] , "..." ... )
}
if _ , err := stringBuilder . Write ( toWrite ) ; err != nil {
log . Error ( "Unable to write commit message Error: %v" , err )
return ""
}
if _ , err := stringBuilder . WriteRune ( '\n' ) ; err != nil {
log . Error ( "Unable to write commit message Error: %v" , err )
return ""
}
}
}
2020-04-10 07:26:37 -04:00
authorString := commit . Author . String ( )
2022-10-12 01:18:26 -04:00
if uniqueAuthors . Add ( authorString ) && authorString != posterSig {
2023-03-09 22:17:04 -05:00
// Compare use account as well to avoid adding the same author multiple times
// times when email addresses are private or multiple emails are used.
commitUser , _ := user_model . GetUserByEmail ( ctx , commit . Author . Email )
if commitUser == nil || commitUser . ID != pr . Issue . Poster . ID {
authors = append ( authors , authorString )
}
2020-04-10 07:26:37 -04:00
}
}
// Consider collecting the remaining authors
if limit >= 0 && setting . Repository . PullRequest . DefaultMergeMessageAllAuthors {
skip := limit
limit = 30
for {
2021-08-09 14:08:51 -04:00
commits , err := gitRepo . CommitsBetweenLimit ( headCommit , mergeBase , limit , skip )
2020-04-10 07:26:37 -04:00
if err != nil {
log . Error ( "Unable to get commits between: %s %s Error: %v" , pr . HeadBranch , pr . MergeBase , err )
return ""
}
2021-08-09 14:08:51 -04:00
if len ( commits ) == 0 {
2020-04-10 07:26:37 -04:00
break
}
2021-08-09 14:08:51 -04:00
for _ , commit := range commits {
2020-04-10 07:26:37 -04:00
authorString := commit . Author . String ( )
2022-10-12 01:18:26 -04:00
if uniqueAuthors . Add ( authorString ) && authorString != posterSig {
2023-03-09 22:17:04 -05:00
commitUser , _ := user_model . GetUserByEmail ( ctx , commit . Author . Email )
if commitUser == nil || commitUser . ID != pr . Issue . Poster . ID {
authors = append ( authors , authorString )
}
2020-04-10 07:26:37 -04:00
}
}
2020-11-27 15:00:52 -05:00
skip += limit
2020-04-10 07:26:37 -04:00
}
}
for _ , author := range authors {
2023-08-28 12:43:16 -04:00
if _ , err := stringBuilder . WriteString ( "Co-authored-by: " ) ; err != nil {
2020-04-10 07:26:37 -04:00
log . Error ( "Unable to write to string builder Error: %v" , err )
return ""
}
2023-08-28 12:43:16 -04:00
if _ , err := stringBuilder . WriteString ( author ) ; err != nil {
2020-04-10 07:26:37 -04:00
log . Error ( "Unable to write to string builder Error: %v" , err )
return ""
}
if _ , err := stringBuilder . WriteRune ( '\n' ) ; err != nil {
log . Error ( "Unable to write to string builder Error: %v" , err )
return ""
}
}
return stringBuilder . String ( )
}
2022-04-26 18:40:01 -04:00
// GetIssuesLastCommitStatus returns a map of issue ID to the most recent commit's latest status
2022-06-13 05:37:59 -04:00
func GetIssuesLastCommitStatus ( ctx context . Context , issues issues_model . IssueList ) ( map [ int64 ] * git_model . CommitStatus , error ) {
2022-04-26 18:40:01 -04:00
_ , lastStatus , err := GetIssuesAllCommitStatus ( ctx , issues )
return lastStatus , err
}
// GetIssuesAllCommitStatus returns a map of issue ID to a list of all statuses for the most recent commit as well as a map of issue ID to only the commit's latest status
2022-06-13 05:37:59 -04:00
func GetIssuesAllCommitStatus ( ctx context . Context , issues issues_model . IssueList ) ( map [ int64 ] [ ] * git_model . CommitStatus , map [ int64 ] * git_model . CommitStatus , error ) {
2022-11-19 03:12:33 -05:00
if err := issues . LoadPullRequests ( ctx ) ; err != nil {
2022-04-26 18:40:01 -04:00
return nil , nil , err
2021-04-15 13:34:43 -04:00
}
2022-11-19 03:12:33 -05:00
if _ , err := issues . LoadRepositories ( ctx ) ; err != nil {
2022-04-26 18:40:01 -04:00
return nil , nil , err
2021-04-15 13:34:43 -04:00
}
var (
gitRepos = make ( map [ int64 ] * git . Repository )
2022-06-12 11:51:54 -04:00
res = make ( map [ int64 ] [ ] * git_model . CommitStatus )
lastRes = make ( map [ int64 ] * git_model . CommitStatus )
2021-04-15 13:34:43 -04:00
err error
)
defer func ( ) {
for _ , gitRepo := range gitRepos {
gitRepo . Close ( )
}
} ( )
for _ , issue := range issues {
if ! issue . IsPull {
continue
}
gitRepo , ok := gitRepos [ issue . RepoID ]
if ! ok {
2022-03-29 15:13:41 -04:00
gitRepo , err = git . OpenRepository ( ctx , issue . Repo . RepoPath ( ) )
2021-04-15 13:34:43 -04:00
if err != nil {
2021-12-16 14:01:14 -05:00
log . Error ( "Cannot open git repository %-v for issue #%d[%d]. Error: %v" , issue . Repo , issue . Index , issue . ID , err )
continue
2021-04-15 13:34:43 -04:00
}
gitRepos [ issue . RepoID ] = gitRepo
}
2023-10-14 04:37:24 -04:00
statuses , lastStatus , err := getAllCommitStatus ( ctx , gitRepo , issue . PullRequest )
2021-04-15 13:34:43 -04:00
if err != nil {
2022-04-26 18:40:01 -04:00
log . Error ( "getAllCommitStatus: cant get commit statuses of pull [%d]: %v" , issue . PullRequest . ID , err )
2021-05-04 08:03:02 -04:00
continue
2021-04-15 13:34:43 -04:00
}
2022-04-26 18:40:01 -04:00
res [ issue . PullRequest . ID ] = statuses
lastRes [ issue . PullRequest . ID ] = lastStatus
2021-04-15 13:34:43 -04:00
}
2022-04-26 18:40:01 -04:00
return res , lastRes , nil
2021-04-15 13:34:43 -04:00
}
2022-04-26 18:40:01 -04:00
// getAllCommitStatus get pr's commit statuses.
2023-10-14 04:37:24 -04:00
func getAllCommitStatus ( ctx context . Context , gitRepo * git . Repository , pr * issues_model . PullRequest ) ( statuses [ ] * git_model . CommitStatus , lastStatus * git_model . CommitStatus , err error ) {
2022-04-26 18:40:01 -04:00
sha , shaErr := gitRepo . GetRefCommitID ( pr . GetGitRefName ( ) )
if shaErr != nil {
return nil , nil , shaErr
2020-04-10 07:26:37 -04:00
}
2023-10-14 04:37:24 -04:00
statuses , _ , err = git_model . GetLatestCommitStatus ( ctx , pr . BaseRepo . ID , sha , db . ListOptions { ListAll : true } )
2022-06-12 11:51:54 -04:00
lastStatus = git_model . CalcCommitStatus ( statuses )
2022-04-26 18:40:01 -04:00
return statuses , lastStatus , err
2020-04-10 07:26:37 -04:00
}
// IsHeadEqualWithBranch returns if the commits of branchName are available in pull request head
2022-06-13 05:37:59 -04:00
func IsHeadEqualWithBranch ( ctx context . Context , pr * issues_model . PullRequest , branchName string ) ( bool , error ) {
2020-04-10 07:26:37 -04:00
var err error
2022-11-19 03:12:33 -05:00
if err = pr . LoadBaseRepo ( ctx ) ; err != nil {
2020-04-10 07:26:37 -04:00
return false , err
}
2022-01-19 18:26:57 -05:00
baseGitRepo , closer , err := git . RepositoryFromContextOrOpen ( ctx , pr . BaseRepo . RepoPath ( ) )
2020-04-10 07:26:37 -04:00
if err != nil {
return false , err
}
2022-01-19 18:26:57 -05:00
defer closer . Close ( )
2021-01-06 14:23:57 -05:00
2020-04-10 07:26:37 -04:00
baseCommit , err := baseGitRepo . GetBranchCommit ( branchName )
if err != nil {
return false , err
}
2022-11-19 03:12:33 -05:00
if err = pr . LoadHeadRepo ( ctx ) ; err != nil {
2020-04-10 07:26:37 -04:00
return false , err
}
2022-01-19 18:26:57 -05:00
var headGitRepo * git . Repository
if pr . HeadRepoID == pr . BaseRepoID {
headGitRepo = baseGitRepo
} else {
var closer io . Closer
headGitRepo , closer , err = git . RepositoryFromContextOrOpen ( ctx , pr . HeadRepo . RepoPath ( ) )
if err != nil {
return false , err
}
defer closer . Close ( )
2020-04-10 07:26:37 -04:00
}
2021-01-06 14:23:57 -05:00
2021-07-28 05:42:56 -04:00
var headCommit * git . Commit
2022-06-13 05:37:59 -04:00
if pr . Flow == issues_model . PullRequestFlowGithub {
2021-07-28 05:42:56 -04:00
headCommit , err = headGitRepo . GetBranchCommit ( pr . HeadBranch )
if err != nil {
return false , err
}
} else {
pr . HeadCommitID , err = baseGitRepo . GetRefCommitID ( pr . GetGitRefName ( ) )
if err != nil {
return false , err
}
if headCommit , err = baseGitRepo . GetCommit ( pr . HeadCommitID ) ; err != nil {
return false , err
}
2020-04-10 07:26:37 -04:00
}
return baseCommit . HasPreviousCommit ( headCommit . ID )
}
2023-07-28 15:18:12 -04:00
type CommitInfo struct {
Summary string ` json:"summary" `
CommitterOrAuthorName string ` json:"committer_or_author_name" `
ID string ` json:"id" `
ShortSha string ` json:"short_sha" `
Time string ` json:"time" `
}
// GetPullCommits returns all commits on given pull request and the last review commit sha
func GetPullCommits ( ctx * gitea_context . Context , issue * issues_model . Issue ) ( [ ] CommitInfo , string , error ) {
pull := issue . PullRequest
baseGitRepo := ctx . Repo . GitRepo
if err := pull . LoadBaseRepo ( ctx ) ; err != nil {
return nil , "" , err
}
baseBranch := pull . BaseBranch
if pull . HasMerged {
baseBranch = pull . MergeBase
}
prInfo , err := baseGitRepo . GetCompareInfo ( pull . BaseRepo . RepoPath ( ) , baseBranch , pull . GetGitRefName ( ) , true , false )
if err != nil {
return nil , "" , err
}
commits := make ( [ ] CommitInfo , 0 , len ( prInfo . Commits ) )
for _ , commit := range prInfo . Commits {
var committerOrAuthorName string
var commitTime time . Time
if commit . Committer != nil {
committerOrAuthorName = commit . Committer . Name
commitTime = commit . Committer . When
} else {
committerOrAuthorName = commit . Author . Name
commitTime = commit . Author . When
}
commits = append ( commits , CommitInfo {
Summary : commit . Summary ( ) ,
CommitterOrAuthorName : committerOrAuthorName ,
ID : commit . ID . String ( ) ,
ShortSha : base . ShortSha ( commit . ID . String ( ) ) ,
Time : commitTime . Format ( time . RFC3339 ) ,
} )
}
var lastReviewCommitID string
if ctx . IsSigned {
// get last review of current user and store information in context (if available)
lastreview , err := issues_model . FindLatestReviews ( ctx , issues_model . FindReviewOptions {
IssueID : issue . ID ,
ReviewerID : ctx . Doer . ID ,
Type : issues_model . ReviewTypeUnknown ,
} )
if err != nil && ! issues_model . IsErrReviewNotExist ( err ) {
return nil , "" , err
}
if len ( lastreview ) > 0 {
lastReviewCommitID = lastreview [ 0 ] . CommitID
}
}
return commits , lastReviewCommitID , nil
}