2019-09-27 02:22:36 +02:00
// Copyright 2019 The Gitea Authors. All rights reserved.
2022-11-27 19:20:29 +01:00
// SPDX-License-Identifier: MIT
2019-09-27 02:22:36 +02:00
package pull
import (
2019-12-15 10:51:28 +01:00
"context"
2019-09-27 02:22:36 +02:00
"fmt"
2022-01-20 00:26:57 +01:00
"io"
2023-01-28 16:54:40 +01:00
"os"
2021-06-25 19:01:43 +02:00
"regexp"
2020-01-09 02:47:45 +01:00
"strings"
2023-07-28 21:18:12 +02:00
"time"
2019-09-27 02:22:36 +02:00
"code.gitea.io/gitea/models"
2021-09-19 13:49:59 +02:00
"code.gitea.io/gitea/models/db"
2022-06-12 17:51:54 +02:00
git_model "code.gitea.io/gitea/models/git"
2022-06-13 11:37:59 +02:00
issues_model "code.gitea.io/gitea/models/issues"
2021-12-10 02:27:50 +01:00
repo_model "code.gitea.io/gitea/models/repo"
2021-11-24 10:49:20 +01:00
user_model "code.gitea.io/gitea/models/user"
2023-07-28 21:18:12 +02:00
"code.gitea.io/gitea/modules/base"
2022-10-12 07:18:26 +02:00
"code.gitea.io/gitea/modules/container"
2023-07-28 21:18:12 +02:00
gitea_context "code.gitea.io/gitea/modules/context"
2019-10-15 05:28:40 +02:00
"code.gitea.io/gitea/modules/git"
2019-12-15 10:51:28 +01:00
"code.gitea.io/gitea/modules/graceful"
2021-07-24 18:03:58 +02:00
"code.gitea.io/gitea/modules/json"
2019-09-27 02:22:36 +02:00
"code.gitea.io/gitea/modules/log"
2022-05-08 18:46:32 +02:00
repo_module "code.gitea.io/gitea/modules/repository"
2020-04-10 13:26:37 +02:00
"code.gitea.io/gitea/modules/setting"
2022-05-04 18:06:23 +02:00
"code.gitea.io/gitea/modules/sync"
2023-01-28 16:54:40 +01:00
"code.gitea.io/gitea/modules/util"
2019-10-28 17:45:43 +01:00
issue_service "code.gitea.io/gitea/services/issue"
2023-09-05 20:37:47 +02:00
notify_service "code.gitea.io/gitea/services/notify"
2019-09-27 02:22:36 +02:00
)
2022-05-04 18:06:23 +02:00
// TODO: use clustered lock (unique queue? or *abuse* cache)
var pullWorkingPool = sync . NewExclusivePool ( )
2019-09-27 02:22:36 +02:00
// NewPullRequest creates new pull request with labels for repository.
2023-08-10 04:39:21 +02: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
2023-08-15 01:07:38 +02: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-10 04:39:21 +02:00
prCtx , cancel , err := createTemporaryRepoForPR ( ctx , pr )
2020-04-14 15:53:34 +02:00
if err != nil {
2023-08-10 04:39:21 +02:00
if ! git_model . IsErrBranchNotExist ( err ) {
log . Error ( "CreateTemporaryRepoForPR %-v: %v" , pr , err )
2019-10-28 17:45:43 +01:00
}
2023-08-10 04:39:21 +02:00
return err
2019-10-28 17:45:43 +01:00
}
2023-08-10 04:39:21 +02:00
defer cancel ( )
2019-10-28 17:45:43 +01:00
2023-08-10 04:39:21 +02:00
if err := testPatch ( ctx , prCtx , pr ) ; err != nil {
2019-12-15 04:28:51 +01:00
return err
}
2023-08-10 04:39:21 +02:00
divergence , err := git . GetDivergingCommits ( ctx , prCtx . tmpBasePath , baseBranch , trackingBranch )
2021-01-02 18:04:02 +01:00
if err != nil {
return err
}
2023-08-10 04:39:21 +02:00
pr . CommitsAhead = divergence . Ahead
pr . CommitsBehind = divergence . Behind
2021-01-02 18:04:02 +01:00
2023-08-10 04:39:21 +02:00
assigneeCommentMap := make ( map [ int64 ] * issues_model . Comment )
2019-09-27 02:22:36 +02:00
2020-05-20 14:47:24 +02:00
// add first push codes comment
2023-08-10 04:39:21 +02:00
baseGitRepo , err := git . OpenRepository ( ctx , pr . BaseRepo . RepoPath ( ) )
2020-05-20 14:47:24 +02:00
if err != nil {
return err
}
defer baseGitRepo . Close ( )
2023-08-10 04:39:21 +02: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 14:47:24 +02:00
2022-06-13 11:37:59 +02:00
data := issues_model . PushActionContent { IsForcePush : false }
2021-08-09 20:08:51 +02: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 14:47:24 +02:00
}
dataJSON , err := json . Marshal ( data )
if err != nil {
return err
}
2022-06-13 11:37:59 +02:00
ops := & issues_model . CreateCommentOptions {
Type : issues_model . CommentTypePullRequestPush ,
2023-08-10 04:39:21 +02:00
Doer : issue . Poster ,
2020-05-20 14:47:24 +02:00
Repo : repo ,
Issue : pr . Issue ,
IsForcePush : false ,
Content : string ( dataJSON ) ,
}
2023-08-10 04:39:21 +02:00
if _ , err = issues_model . CreateComment ( ctx , ops ) ; err != nil {
return err
}
2023-06-08 10:56:05 +02:00
2023-10-11 06:24:07 +02:00
if ! pr . IsWorkInProgress ( ctx ) {
2023-08-10 04:39:21 +02:00
if err := issues_model . PullRequestCodeOwnersReview ( ctx , issue , pr ) ; err != nil {
2023-06-08 10:56:05 +02:00
return err
}
}
2023-08-10 04:39:21 +02: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 10:56:05 +02:00
2023-08-10 04:39:21 +02:00
mentions , err := issues_model . FindAndUpdateIssueMentions ( ctx , issue , issue . Poster , issue . Content )
if err != nil {
return err
}
2023-09-05 20:37:47 +02:00
notify_service . NewPullRequest ( ctx , pr , mentions )
2023-08-10 04:39:21 +02:00
if len ( issue . Labels ) > 0 {
2023-09-05 20:37:47 +02:00
notify_service . IssueChangeLabels ( ctx , issue . Poster , issue , issue . Labels , nil )
2023-08-10 04:39:21 +02:00
}
if issue . Milestone != nil {
2023-09-05 20:37:47 +02:00
notify_service . IssueChangeMilestone ( ctx , issue . Poster , issue , 0 )
2023-08-10 04:39:21 +02:00
}
2023-10-06 08:49:37 +02:00
for _ , assigneeID := range assigneeIDs {
assignee , err := user_model . GetUserByID ( ctx , assigneeID )
if err != nil {
return ErrDependenciesLeft
2023-08-10 04:39:21 +02:00
}
2023-10-06 08:49:37 +02:00
notify_service . IssueChangeAssignee ( ctx , issue . Poster , issue , assignee , false , assigneeCommentMap [ assigneeID ] )
2020-05-20 14:47:24 +02:00
}
2019-09-27 02:22:36 +02:00
return nil
}
2019-10-15 05:28:40 +02:00
2019-12-16 07:20:25 +01:00
// ChangeTargetBranch changes the target branch of this pull request, as the given user.
2022-06-13 11:37:59 +02:00
func ChangeTargetBranch ( ctx context . Context , pr * issues_model . PullRequest , doer * user_model . User , targetBranch string ) ( err error ) {
2022-05-04 18:06:23 +02:00
pullWorkingPool . CheckIn ( fmt . Sprint ( pr . ID ) )
defer pullWorkingPool . CheckOut ( fmt . Sprint ( pr . ID ) )
2019-12-16 07:20:25 +01:00
// Current target branch is already the same
if pr . BaseBranch == targetBranch {
return nil
}
if pr . Issue . IsClosed {
2022-06-13 11:37:59 +02:00
return issues_model . ErrIssueIsClosed {
2019-12-16 07:20:25 +01: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-20 00:26:57 +01:00
branchesEqual , err := IsHeadEqualWithBranch ( ctx , pr , targetBranch )
2019-12-16 07:20:25 +01:00
if err != nil {
return err
}
if branchesEqual {
2023-06-29 12:03:20 +02:00
return git_model . ErrBranchesEqual {
2019-12-16 07:20:25 +01:00
HeadBranchName : pr . HeadBranch ,
BaseBranchName : targetBranch ,
}
}
// Check if pull request for the new target branch already exists
2022-11-19 09:12:33 +01:00
existingPr , err := issues_model . GetUnmergedPullRequest ( ctx , pr . HeadRepoID , pr . BaseRepoID , pr . HeadBranch , targetBranch , issues_model . PullRequestFlowGithub )
2019-12-16 07:20:25 +01:00
if existingPr != nil {
2022-06-13 11:37:59 +02:00
return issues_model . ErrPullRequestAlreadyExists {
2019-12-16 07:20:25 +01:00
ID : existingPr . ID ,
IssueID : existingPr . Index ,
HeadRepoID : existingPr . HeadRepoID ,
BaseRepoID : existingPr . BaseRepoID ,
HeadBranch : existingPr . HeadBranch ,
BaseBranch : existingPr . BaseBranch ,
}
}
2022-06-13 11:37:59 +02:00
if err != nil && ! issues_model . IsErrPullRequestNotExist ( err ) {
2019-12-16 07:20:25 +01: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 11:37:59 +02:00
if pr . Status == issues_model . PullRequestStatusChecking {
pr . Status = issues_model . PullRequestStatusMergeable
2019-12-16 07:20:25 +01:00
}
2020-06-16 19:52:33 +02:00
// Update Commit Divergence
2022-01-20 00:26:57 +01:00
divergence , err := GetDiverging ( ctx , pr )
2020-06-16 19:52:33 +02:00
if err != nil {
return err
}
pr . CommitsAhead = divergence . Ahead
pr . CommitsBehind = divergence . Behind
2022-11-19 09:12:33 +01: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 07:20:25 +01:00
return err
}
// Create comment
2022-06-13 11:37:59 +02:00
options := & issues_model . CreateCommentOptions {
Type : issues_model . CommentTypeChangeTargetBranch ,
2019-12-16 07:20:25 +01:00
Doer : doer ,
Repo : pr . Issue . Repo ,
Issue : pr . Issue ,
OldRef : oldBranch ,
NewRef : targetBranch ,
}
2023-08-04 15:34:34 +02:00
if _ , err = issues_model . CreateComment ( ctx , options ) ; err != nil {
2022-10-24 21:29:17 +02:00
return fmt . Errorf ( "CreateChangeTargetBranchComment: %w" , err )
2019-12-16 07:20:25 +01:00
}
return nil
}
2022-06-13 11:37:59 +02:00
func checkForInvalidation ( ctx context . Context , requests issues_model . PullRequestList , repoID int64 , doer * user_model . User , branch string ) error {
2022-12-03 03:48:26 +01:00
repo , err := repo_model . GetRepositoryByID ( ctx , repoID )
2019-10-15 05:28:40 +02:00
if err != nil {
2022-11-19 09:12:33 +01:00
return fmt . Errorf ( "GetRepositoryByIDCtx: %w" , err )
2019-10-15 05:28:40 +02:00
}
2022-03-29 21:13:41 +02:00
gitRepo , err := git . OpenRepository ( ctx , repo . RepoPath ( ) )
2019-10-15 05:28:40 +02:00
if err != nil {
2022-10-24 21:29:17 +02:00
return fmt . Errorf ( "git.OpenRepository: %w" , err )
2019-10-15 05:28:40 +02:00
}
go func ( ) {
2019-12-15 10:51:28 +01:00
// FIXME: graceful: We need to tell the manager we're doing something...
2023-01-17 22:03:44 +01:00
err := InvalidateCodeComments ( ctx , requests , doer , gitRepo , branch )
2019-10-15 05:28:40 +02:00
if err != nil {
log . Error ( "PullRequestList.InvalidateCodeComments: %v" , err )
}
2019-11-13 08:01:19 +01:00
gitRepo . Close ( )
2019-10-15 05:28:40 +02: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 10:49:20 +01:00
func AddTestPullRequestTask ( doer * user_model . User , repoID int64 , branch string , isSync bool , oldCommitID , newCommitID string ) {
2019-10-15 05:28:40 +02:00
log . Trace ( "AddTestPullRequestTask [head_repo_id: %d, head_branch: %s]: finding pull requests" , repoID , branch )
2019-12-15 10:51:28 +01: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 19:05:52 +02:00
// TODO: graceful: AddTestPullRequestTask needs to become a queue!
2019-10-15 05:28:40 +02:00
2023-05-08 08:39:32 +02:00
// GetUnmergedPullRequestsByHeadInfo() only return open and unmerged PR.
2023-07-22 16:14:27 +02:00
prs , err := issues_model . GetUnmergedPullRequestsByHeadInfo ( ctx , repoID , branch )
2019-12-15 10:51:28 +01:00
if err != nil {
log . Error ( "Find pull requests [head_repo_id: %d, head_branch: %s]: %v" , repoID , branch , err )
return
2019-10-15 05:28:40 +02:00
}
2019-12-15 10:51:28 +01:00
2023-02-05 12:57:38 +01: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 16:14:27 +02:00
AddToTaskQueue ( ctx , pr )
2023-02-05 12:57:38 +01:00
comment , err := CreatePushPullComment ( ctx , doer , pr , oldCommitID , newCommitID )
2023-05-08 08:39:32 +02:00
if err == nil && comment != nil {
2023-09-05 20:37:47 +02:00
notify_service . PullRequestPushCommits ( ctx , doer , pr , comment )
2023-02-05 12:57:38 +01:00
}
}
2019-12-15 10:51:28 +01:00
if isSync {
2022-06-13 11:37:59 +02:00
requests := issues_model . PullRequestList ( prs )
2023-07-22 16:14:27 +02:00
if err = requests . LoadAttributes ( ctx ) ; err != nil {
2019-12-15 10:51:28 +01:00
log . Error ( "PullRequestList.LoadAttributes: %v" , err )
}
2022-01-20 00:26:57 +01:00
if invalidationErr := checkForInvalidation ( ctx , requests , repoID , doer , branch ) ; invalidationErr != nil {
2019-12-15 10:51:28 +01:00
log . Error ( "checkForInvalidation: %v" , invalidationErr )
}
if err == nil {
for _ , pr := range prs {
2020-01-09 02:47:45 +01:00
if newCommitID != "" && newCommitID != git . EmptySHA {
2022-01-20 00:26:57 +01:00
changed , err := checkIfPRContentChanged ( ctx , pr , oldCommitID , newCommitID )
2020-01-09 02:47:45 +01: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 14:12:54 +02:00
if err := issues_model . MarkReviewsAsStale ( ctx , pr . IssueID ) ; err != nil {
2020-01-09 02:47:45 +01:00
log . Error ( "MarkReviewsAsStale: %v" , err )
}
2023-07-20 09:18:52 +02: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-09 02:47:45 +01:00
}
2023-09-29 14:12:54 +02:00
if err := issues_model . MarkReviewsAsNotStale ( ctx , pr . IssueID , newCommitID ) ; err != nil {
2020-01-09 02:47:45 +01:00
log . Error ( "MarkReviewsAsNotStale: %v" , err )
}
2022-01-20 00:26:57 +01:00
divergence , err := GetDiverging ( ctx , pr )
2020-04-14 15:53:34 +02:00
if err != nil {
log . Error ( "GetDiverging: %v" , err )
} else {
2022-05-20 16:08:52 +02:00
err = pr . UpdateCommitDivergence ( ctx , divergence . Ahead , divergence . Behind )
2020-04-14 15:53:34 +02:00
if err != nil {
log . Error ( "UpdateCommitDivergence: %v" , err )
}
}
2020-01-09 02:47:45 +01:00
}
2023-09-05 20:37:47 +02:00
notify_service . PullRequestSynchronized ( ctx , doer , pr )
2019-12-15 10:51:28 +01:00
}
2019-10-15 05:28:40 +02:00
}
}
2019-12-15 10:51:28 +01:00
log . Trace ( "AddTestPullRequestTask [base_repo_id: %d, base_branch: %s]: finding pull requests" , repoID , branch )
2023-07-22 16:14:27 +02:00
prs , err = issues_model . GetUnmergedPullRequestsByBaseInfo ( ctx , repoID , branch )
2019-12-15 10:51:28 +01: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-20 00:26:57 +01:00
divergence , err := GetDiverging ( ctx , pr )
2020-04-14 15:53:34 +02:00
if err != nil {
2023-06-29 12:03:20 +02:00
if git_model . IsErrBranchNotExist ( err ) && ! git . IsBranchExist ( ctx , pr . HeadRepo . RepoPath ( ) , pr . HeadBranch ) {
2021-07-13 01:26:25 +02: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 15:53:34 +02:00
} else {
2022-05-20 16:08:52 +02:00
err = pr . UpdateCommitDivergence ( ctx , divergence . Ahead , divergence . Behind )
2020-04-14 15:53:34 +02:00
if err != nil {
log . Error ( "UpdateCommitDivergence: %v" , err )
}
}
2023-07-22 16:14:27 +02:00
AddToTaskQueue ( ctx , pr )
2019-12-15 10:51:28 +01:00
}
} )
2019-10-15 05:28:40 +02:00
}
2019-12-15 04:28:51 +01:00
2020-01-09 02:47:45 +01: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 11:37:59 +02:00
func checkIfPRContentChanged ( ctx context . Context , pr * issues_model . PullRequest , oldCommitID , newCommitID string ) ( hasChanged bool , err error ) {
2023-03-07 21:07:35 +01:00
prCtx , cancel , err := createTemporaryRepoForPR ( ctx , pr )
2020-01-09 02:47:45 +01:00
if err != nil {
2023-03-07 21:07:35 +01:00
log . Error ( "CreateTemporaryRepoForPR %-v: %v" , pr , err )
2023-01-28 16:54:40 +01:00
return false , err
2020-01-09 02:47:45 +01:00
}
2023-03-07 21:07:35 +01:00
defer cancel ( )
2023-01-28 16:54:40 +01:00
2023-03-07 21:07:35 +01:00
tmpRepo , err := git . OpenRepository ( ctx , prCtx . tmpBasePath )
2020-01-09 02:47:45 +01:00
if err != nil {
2023-01-28 16:54:40 +01:00
return false , fmt . Errorf ( "OpenRepository: %w" , err )
2020-01-09 02:47:45 +01:00
}
2023-01-28 16:54:40 +01:00
defer tmpRepo . Close ( )
2020-01-09 02:47:45 +01:00
2023-01-28 16:54:40 +01:00
// Find the merge-base
_ , base , err := tmpRepo . GetMergeBase ( "" , "base" , "tracking" )
if err != nil {
return false , fmt . Errorf ( "GetMergeBase: %w" , err )
2020-01-09 02:47:45 +01:00
}
2023-01-28 16:54:40 +01: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 )
}
if err := cmd . Run ( & git . RunOpts {
2023-03-07 21:07:35 +01:00
Dir : prCtx . tmpBasePath ,
2023-01-28 16:54:40 +01:00
Stdout : stdoutWriter ,
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-09 02:47:45 +01:00
return true , nil
}
2023-01-28 16:54:40 +01: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-09 02:47:45 +01:00
}
return false , nil
}
2019-12-15 04:28:51 +01: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 11:37:59 +02:00
func PushToBaseRepo ( ctx context . Context , pr * issues_model . PullRequest ) ( err error ) {
2022-01-20 00:26:57 +01:00
return pushToBaseRepoHelper ( ctx , pr , "" )
2021-06-23 23:08:26 +02:00
}
2022-06-13 11:37:59 +02:00
func pushToBaseRepoHelper ( ctx context . Context , pr * issues_model . PullRequest , prefixHeadBranch string ) ( err error ) {
2019-12-15 04:28:51 +01:00
log . Trace ( "PushToBaseRepo[%d]: pushing commits to base repo '%s'" , pr . BaseRepoID , pr . GetGitRefName ( ) )
2022-11-19 09:12:33 +01:00
if err := pr . LoadHeadRepo ( ctx ) ; err != nil {
2020-02-21 19:18:13 +01:00
log . Error ( "Unable to load head repository for PR[%d] Error: %v" , pr . ID , err )
return err
}
2019-12-15 04:28:51 +01:00
headRepoPath := pr . HeadRepo . RepoPath ( )
2020-01-28 11:23:58 +01:00
2022-11-19 09:12:33 +01:00
if err := pr . LoadBaseRepo ( ctx ) ; err != nil {
2020-02-21 19:18:13 +01:00
log . Error ( "Unable to load base repository for PR[%d] Error: %v" , pr . ID , err )
return err
}
2020-09-15 05:32:31 +02:00
baseRepoPath := pr . BaseRepo . RepoPath ( )
2019-12-15 04:28:51 +01:00
2022-11-19 09:12:33 +01:00
if err = pr . LoadIssue ( ctx ) ; err != nil {
2022-10-24 21:29:17 +02:00
return fmt . Errorf ( "unable to load issue %d for pr %d: %w" , pr . IssueID , pr . ID , err )
2019-12-27 22:15:04 +01:00
}
2022-11-19 09:12:33 +01:00
if err = pr . Issue . LoadPoster ( ctx ) ; err != nil {
2022-10-24 21:29:17 +02:00
return fmt . Errorf ( "unable to load poster %d for pr %d: %w" , pr . Issue . PosterID , pr . ID , err )
2019-12-27 22:15:04 +01:00
}
2020-09-15 05:32:31 +02:00
gitRefName := pr . GetGitRefName ( )
2022-01-20 00:26:57 +01:00
if err := git . Push ( ctx , headRepoPath , git . PushOptions {
2020-09-15 05:32:31 +02:00
Remote : baseRepoPath ,
2021-06-23 23:08:26 +02:00
Branch : prefixHeadBranch + pr . HeadBranch + ":" + gitRefName ,
2019-12-15 04:28:51 +01:00
Force : true ,
2019-12-27 22:15:04 +01:00
// Use InternalPushingEnvironment here because we know that pre-receive and post-receive do not run on a refs/pulls/...
2022-05-08 18:46:32 +02:00
Env : repo_module . InternalPushingEnvironment ( pr . Issue . Poster , pr . BaseRepo ) ,
2019-12-15 04:28:51 +01:00
} ) ; err != nil {
2020-06-08 20:07:41 +02:00
if git . IsErrPushOutOfDate ( err ) {
// This should not happen as we're using force!
2020-09-15 05:32:31 +02: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 20:07:41 +02:00
return err
} else if git . IsErrPushRejected ( err ) {
rejectErr := err . ( * git . ErrPushRejected )
2020-09-15 05:32:31 +02: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 20:07:41 +02:00
return err
2021-06-23 23:08:26 +02:00
} else if git . IsErrMoreThanOne ( err ) {
if prefixHeadBranch != "" {
log . Info ( "Can't push with %s%s" , prefixHeadBranch , pr . HeadBranch )
return err
}
2022-01-20 00:26:57 +01:00
log . Info ( "Retrying to push with %s%s" , git . BranchPrefix , pr . HeadBranch )
err = pushToBaseRepoHelper ( ctx , pr , git . BranchPrefix )
2021-06-23 23:08:26 +02:00
return err
2020-06-08 20:07:41 +02:00
}
2020-09-15 05:32:31 +02: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 21:29:17 +02:00
return fmt . Errorf ( "Push: %s:%s %s:%s %w" , pr . HeadRepo . FullName ( ) , pr . HeadBranch , pr . BaseRepo . FullName ( ) , gitRefName , err )
2019-12-15 04:28:51 +01:00
}
return nil
}
2020-01-25 03:48:22 +01:00
2021-07-28 11:42:56 +02:00
// UpdateRef update refs/pull/id/head directly for agit flow pull request
2022-06-13 11:37:59 +02:00
func UpdateRef ( ctx context . Context , pr * issues_model . PullRequest ) ( err error ) {
2021-07-28 11:42:56 +02:00
log . Trace ( "UpdateRef[%d]: upgate pull request ref in base repo '%s'" , pr . ID , pr . GetGitRefName ( ) )
2022-11-19 09:12:33 +01:00
if err := pr . LoadBaseRepo ( ctx ) ; err != nil {
2021-07-28 11:42:56 +02:00
log . Error ( "Unable to load base repository for PR[%d] Error: %v" , pr . ID , err )
return err
}
2022-10-23 16:44:45 +02:00
_ , _ , err = git . NewCommand ( ctx , "update-ref" ) . AddDynamicArguments ( pr . GetGitRefName ( ) , pr . HeadCommitID ) . RunStdString ( & git . RunOpts { Dir : pr . BaseRepo . RepoPath ( ) } )
2021-07-28 11:42:56 +02: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-25 03:48:22 +01: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 16:14:27 +02: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-25 03:48:22 +01:00
if err != nil {
return err
}
2023-07-22 16:14:27 +02:00
prs2 , err := issues_model . GetUnmergedPullRequestsByBaseInfo ( ctx , repoID , branch )
2020-01-25 03:48:22 +01:00
if err != nil {
return err
}
prs = append ( prs , prs2 ... )
2023-07-22 16:14:27 +02:00
if err := issues_model . PullRequestList ( prs ) . LoadAttributes ( ctx ) ; err != nil {
2020-01-25 03:48:22 +01:00
return err
}
var errs errlist
for _ , pr := range prs {
2023-07-22 16:14:27 +02:00
if err = issue_service . ChangeStatus ( ctx , pr . Issue , doer , "" , true ) ; err != nil && ! issues_model . IsErrPullWasClosed ( err ) && ! issues_model . IsErrDependenciesLeft ( err ) {
2020-01-25 03:48:22 +01:00
errs = append ( errs , err )
}
}
if len ( errs ) > 0 {
return errs
}
return nil
}
2021-03-01 18:39:44 +01: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-20 00:26:57 +01: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-25 03:48:22 +01:00
if err != nil {
return err
}
var errs errlist
for _ , branch := range branches {
2023-07-22 16:14:27 +02:00
prs , err := issues_model . GetUnmergedPullRequestsByHeadInfo ( ctx , repo . ID , branch . Name )
2020-01-25 03:48:22 +01:00
if err != nil {
return err
}
2023-07-22 16:14:27 +02:00
if err = issues_model . PullRequestList ( prs ) . LoadAttributes ( ctx ) ; err != nil {
2020-01-25 03:48:22 +01:00
return err
}
for _ , pr := range prs {
2021-03-01 18:39:44 +01: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 16:14:27 +02:00
if err = issue_service . ChangeStatus ( ctx , pr . Issue , doer , "" , true ) ; err != nil && ! issues_model . IsErrPullWasClosed ( err ) {
2020-01-25 03:48:22 +01:00
errs = append ( errs , err )
}
}
}
if len ( errs ) > 0 {
return errs
}
return nil
}
2020-04-10 13:26:37 +02:00
2021-06-25 19:01:43 +02:00
var commitMessageTrailersPattern = regexp . MustCompile ( ` (?:^|\n\n)(?:[\w-]+[ \t]*:[^\n]+\n*(?:[ \t]+[^\n]+\n*)*)+$ ` )
2020-12-21 17:46:14 +01:00
// GetSquashMergeCommitMessages returns the commit messages between head and merge base (if there is one)
2022-06-13 11:37:59 +02:00
func GetSquashMergeCommitMessages ( ctx context . Context , pr * issues_model . PullRequest ) string {
2022-11-19 09:12:33 +01:00
if err := pr . LoadIssue ( ctx ) ; err != nil {
2020-04-10 13:26:37 +02:00
log . Error ( "Cannot load issue %d for PR id %d: Error: %v" , pr . IssueID , pr . ID , err )
return ""
}
2022-11-19 09:12:33 +01:00
if err := pr . Issue . LoadPoster ( ctx ) ; err != nil {
2020-04-10 13:26:37 +02: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-03 03:48:26 +01:00
pr . HeadRepo , err = repo_model . GetRepositoryByID ( ctx , pr . HeadRepoID )
2020-04-10 13:26:37 +02:00
if err != nil {
2022-11-19 09:12:33 +01:00
log . Error ( "GetRepositoryByIdCtx[%d]: %v" , pr . HeadRepoID , err )
2020-04-10 13:26:37 +02:00
return ""
}
}
2022-01-20 00:26:57 +01:00
gitRepo , closer , err := git . RepositoryFromContextOrOpen ( ctx , pr . HeadRepo . RepoPath ( ) )
2020-04-10 13:26:37 +02:00
if err != nil {
log . Error ( "Unable to open head repository: Error: %v" , err )
return ""
}
2022-01-20 00:26:57 +01:00
defer closer . Close ( )
2020-04-10 13:26:37 +02:00
2021-07-28 11:42:56 +02:00
var headCommit * git . Commit
2022-06-13 11:37:59 +02:00
if pr . Flow == issues_model . PullRequestFlowGithub {
2021-07-28 11:42:56 +02: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 13:26:37 +02: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 20:08:51 +02:00
commits , err := gitRepo . CommitsBetweenLimit ( headCommit , mergeBase , limit , 0 )
2020-04-10 13:26:37 +02: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 07:18:26 +02:00
uniqueAuthors := make ( container . Set [ string ] )
2021-08-09 20:08:51 +02:00
authors := make ( [ ] string , 0 , len ( commits ) )
2020-04-10 13:26:37 +02:00
stringBuilder := strings . Builder { }
2020-12-21 17:46:14 +01:00
2021-06-19 00:08:22 +02:00
if ! setting . Repository . PullRequest . PopulateSquashCommentWithCommitMessages {
2021-06-25 19:01:43 +02:00
message := strings . TrimSpace ( pr . Issue . Content )
stringBuilder . WriteString ( message )
2021-06-19 00:08:22 +02:00
if stringBuilder . Len ( ) > 0 {
stringBuilder . WriteRune ( '\n' )
2021-06-25 19:01:43 +02:00
if ! commitMessageTrailersPattern . MatchString ( message ) {
stringBuilder . WriteRune ( '\n' )
}
2021-06-19 00:08:22 +02:00
}
2020-12-21 17:46:14 +01:00
}
2020-11-25 21:08:17 +01:00
// commits list is in reverse chronological order
2021-08-09 20:08:51 +02:00
first := true
for i := len ( commits ) - 1 ; i >= 0 ; i -- {
commit := commits [ i ]
2021-06-19 00:08:22 +02:00
if setting . Repository . PullRequest . PopulateSquashCommentWithCommitMessages {
maxSize := setting . Repository . PullRequest . DefaultMergeMessageSize
if maxSize < 0 || stringBuilder . Len ( ) < maxSize {
var toWrite [ ] byte
2021-08-09 20:08:51 +02:00
if first {
first = false
2021-06-19 00:08:22 +02: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 13:26:37 +02:00
authorString := commit . Author . String ( )
2022-10-12 07:18:26 +02:00
if uniqueAuthors . Add ( authorString ) && authorString != posterSig {
2023-03-10 04:17:04 +01: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 13:26:37 +02:00
}
}
// Consider collecting the remaining authors
if limit >= 0 && setting . Repository . PullRequest . DefaultMergeMessageAllAuthors {
skip := limit
limit = 30
for {
2021-08-09 20:08:51 +02:00
commits , err := gitRepo . CommitsBetweenLimit ( headCommit , mergeBase , limit , skip )
2020-04-10 13:26:37 +02:00
if err != nil {
log . Error ( "Unable to get commits between: %s %s Error: %v" , pr . HeadBranch , pr . MergeBase , err )
return ""
}
2021-08-09 20:08:51 +02:00
if len ( commits ) == 0 {
2020-04-10 13:26:37 +02:00
break
}
2021-08-09 20:08:51 +02:00
for _ , commit := range commits {
2020-04-10 13:26:37 +02:00
authorString := commit . Author . String ( )
2022-10-12 07:18:26 +02:00
if uniqueAuthors . Add ( authorString ) && authorString != posterSig {
2023-03-10 04:17:04 +01: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 13:26:37 +02:00
}
}
2020-11-27 21:00:52 +01:00
skip += limit
2020-04-10 13:26:37 +02:00
}
}
for _ , author := range authors {
2023-08-28 18:43:16 +02:00
if _ , err := stringBuilder . WriteString ( "Co-authored-by: " ) ; err != nil {
2020-04-10 13:26:37 +02:00
log . Error ( "Unable to write to string builder Error: %v" , err )
return ""
}
2023-08-28 18:43:16 +02:00
if _ , err := stringBuilder . WriteString ( author ) ; err != nil {
2020-04-10 13:26:37 +02: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-27 00:40:01 +02:00
// GetIssuesLastCommitStatus returns a map of issue ID to the most recent commit's latest status
2022-06-13 11:37:59 +02:00
func GetIssuesLastCommitStatus ( ctx context . Context , issues issues_model . IssueList ) ( map [ int64 ] * git_model . CommitStatus , error ) {
2022-04-27 00:40:01 +02: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 11:37:59 +02:00
func GetIssuesAllCommitStatus ( ctx context . Context , issues issues_model . IssueList ) ( map [ int64 ] [ ] * git_model . CommitStatus , map [ int64 ] * git_model . CommitStatus , error ) {
2022-11-19 09:12:33 +01:00
if err := issues . LoadPullRequests ( ctx ) ; err != nil {
2022-04-27 00:40:01 +02:00
return nil , nil , err
2021-04-15 19:34:43 +02:00
}
2022-11-19 09:12:33 +01:00
if _ , err := issues . LoadRepositories ( ctx ) ; err != nil {
2022-04-27 00:40:01 +02:00
return nil , nil , err
2021-04-15 19:34:43 +02:00
}
var (
gitRepos = make ( map [ int64 ] * git . Repository )
2022-06-12 17:51:54 +02:00
res = make ( map [ int64 ] [ ] * git_model . CommitStatus )
lastRes = make ( map [ int64 ] * git_model . CommitStatus )
2021-04-15 19:34:43 +02: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 21:13:41 +02:00
gitRepo , err = git . OpenRepository ( ctx , issue . Repo . RepoPath ( ) )
2021-04-15 19:34:43 +02:00
if err != nil {
2021-12-16 20:01:14 +01: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 19:34:43 +02:00
}
gitRepos [ issue . RepoID ] = gitRepo
}
2023-10-14 10:37:24 +02:00
statuses , lastStatus , err := getAllCommitStatus ( ctx , gitRepo , issue . PullRequest )
2021-04-15 19:34:43 +02:00
if err != nil {
2022-04-27 00:40:01 +02:00
log . Error ( "getAllCommitStatus: cant get commit statuses of pull [%d]: %v" , issue . PullRequest . ID , err )
2021-05-04 14:03:02 +02:00
continue
2021-04-15 19:34:43 +02:00
}
2022-04-27 00:40:01 +02:00
res [ issue . PullRequest . ID ] = statuses
lastRes [ issue . PullRequest . ID ] = lastStatus
2021-04-15 19:34:43 +02:00
}
2022-04-27 00:40:01 +02:00
return res , lastRes , nil
2021-04-15 19:34:43 +02:00
}
2022-04-27 00:40:01 +02:00
// getAllCommitStatus get pr's commit statuses.
2023-10-14 10:37:24 +02: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-27 00:40:01 +02:00
sha , shaErr := gitRepo . GetRefCommitID ( pr . GetGitRefName ( ) )
if shaErr != nil {
return nil , nil , shaErr
2020-04-10 13:26:37 +02:00
}
2023-10-14 10:37:24 +02:00
statuses , _ , err = git_model . GetLatestCommitStatus ( ctx , pr . BaseRepo . ID , sha , db . ListOptions { ListAll : true } )
2022-06-12 17:51:54 +02:00
lastStatus = git_model . CalcCommitStatus ( statuses )
2022-04-27 00:40:01 +02:00
return statuses , lastStatus , err
2020-04-10 13:26:37 +02:00
}
// IsHeadEqualWithBranch returns if the commits of branchName are available in pull request head
2022-06-13 11:37:59 +02:00
func IsHeadEqualWithBranch ( ctx context . Context , pr * issues_model . PullRequest , branchName string ) ( bool , error ) {
2020-04-10 13:26:37 +02:00
var err error
2022-11-19 09:12:33 +01:00
if err = pr . LoadBaseRepo ( ctx ) ; err != nil {
2020-04-10 13:26:37 +02:00
return false , err
}
2022-01-20 00:26:57 +01:00
baseGitRepo , closer , err := git . RepositoryFromContextOrOpen ( ctx , pr . BaseRepo . RepoPath ( ) )
2020-04-10 13:26:37 +02:00
if err != nil {
return false , err
}
2022-01-20 00:26:57 +01:00
defer closer . Close ( )
2021-01-06 20:23:57 +01:00
2020-04-10 13:26:37 +02:00
baseCommit , err := baseGitRepo . GetBranchCommit ( branchName )
if err != nil {
return false , err
}
2022-11-19 09:12:33 +01:00
if err = pr . LoadHeadRepo ( ctx ) ; err != nil {
2020-04-10 13:26:37 +02:00
return false , err
}
2022-01-20 00:26:57 +01: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 13:26:37 +02:00
}
2021-01-06 20:23:57 +01:00
2021-07-28 11:42:56 +02:00
var headCommit * git . Commit
2022-06-13 11:37:59 +02:00
if pr . Flow == issues_model . PullRequestFlowGithub {
2021-07-28 11:42:56 +02: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 13:26:37 +02:00
}
return baseCommit . HasPreviousCommit ( headCommit . ID )
}
2023-07-28 21:18:12 +02: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
}