Skip to content

Commit 9ed86bb

Browse files
mifitouscallum-pcpt1gl0Olcod
authored
Merge Request rebuild triggers (#244)
Co-authored-by: Callum Pember <[email protected]> Co-authored-by: Alexander Schmidt <[email protected]> Co-authored-by: Constantin Oleinic <[email protected]>
1 parent adf30a3 commit 9ed86bb

File tree

8 files changed

+380
-38
lines changed

8 files changed

+380
-38
lines changed

README.md

Lines changed: 39 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ you require the following plugins:
1414
* GitLab Branch Source Plugin - Contains two packages:
1515

1616
* `io.jenkins.plugins.gitlabserverconfig` - Manages server configuration and web hooks management. Ideally should reside inside another plugin with name `GitLab Plugin`. In future, this package will be moved into a new plugin.
17-
17+
1818
* `io.jenkins.plugins.gitlabbranchsource` - Adds GitLab Branch Source for Multi-branch Pipeline Jobs (including
1919
Merge Requests) and Folder organization.
2020

@@ -83,7 +83,7 @@ Here are a few ways to setup your own Jenkins server:
8383
Refer to Bitnami [docs](https://docs.bitnami.com/general/apps/jenkins/).
8484

8585
5. Using [Jenkins CLI](https://github.com/jenkins-zh/jenkins-cli) run it for development:
86-
86+
8787
Run it via: `jcli plugin run`
8888

8989
### Configuring Jenkins instance:
@@ -121,7 +121,7 @@ Here are a few ways to setup your own Jenkins server:
121121
You can use any one of these ways:
122122

123123
1. Install from Jenkins Update Center. Go to Jenkins > Configure > Manage Plugins > Available and search for `gitlab branch source plugin` then select Install.
124-
124+
125125
2. Using [Plugin Management Tool](https://github.com/jenkinsci/plugin-installation-manager-tool)
126126

127127
```bash
@@ -134,12 +134,12 @@ You can use any one of these ways:
134134
3. From Source:
135135

136136
i. Checkout out source code to your local machine:
137-
137+
138138
```
139139
git clone https://github.com/jenkinsci/gitlab-branch-source-plugin.git
140140
cd gitlab-branch-source-plugin
141141
```
142-
142+
143143
ii. Install the plugin:
144144
```
145145
mvn clean install
@@ -148,7 +148,7 @@ You can use any one of these ways:
148148
```
149149

150150
iii. Run the Plugin:
151-
151+
152152
```
153153
mvn hpi:run # runs a Jenkins instance at localhost:8080
154154
or
@@ -201,9 +201,9 @@ After installing the plugin on your Jenkins instance, you need configure your Gi
201201
202202
iii. `Credentials` - Contains a list of credentials entries that are of type GitLab Personal Access Token. When no credential has been added it shows "-none-". User can add a credential by clicking "Add" button.
203203
204-
iv. `Mange Web Hook` - If you want the plugin to setup web hook on your GitLab project(s) to get push/mr/tag/note events then check this box.
205-
206-
iv. `Mange System Hook` - If you want the plugin to setup system hook on your GitLab project(s) to detect if a project is removed then check this box. Remember plugin can only setup system hook on your server if supplied access token has `Admin` access.
204+
iv. `Mange Web Hook` - If you want the plugin to setup web hook on your GitLab project(s) to get push/mr/tag/note events then check this box.
205+
206+
iv. `Mange System Hook` - If you want the plugin to setup system hook on your GitLab project(s) to detect if a project is removed then check this box. Remember plugin can only setup system hook on your server if supplied access token has `Admin` access.
207207
208208
v. `Secret Token` - The secret token is required to authenticate the webhook payloads received from GitLab Server. Use generate secret token from Advanced options or use your own. If you are a old plugin user and did not set a secret token previously and want secret token to applied to the hooks of your existing jobs, you can add the secret token and rescan your jobs. Existing hooks with new secret token will be applied.
209209
@@ -283,7 +283,7 @@ GitLab Personal Access Token credentials to Jenkins server credentials.
283283
7. The token creator will create a Personal Access Token in your GitLab Server for the given user with the required scope and also create a credentials for the same inside Jenkins server. You can go back to the GitLab Server Configuration to select the new credentials generated (select "-none-" first then new credentials will appear). For security reasons this token is not revealed as plain text rather returns an `id`. It is a 128-bit long UUID-4 string (36 characters).
284284
285285
![gitlab-token-creator](/docs/img/gitlab-token-creator.png)
286-
286+
287287
### Manually create hooks on GitLab Server
288288
289289
Use the following end points for web hooks and system hooks setup on your GitLab Server. The `Jenkins Url` needs to be a fully qualified domain name (FQDN) so cannot be `localhost`.
@@ -379,17 +379,17 @@ To create a `Multibranch Pipeline Job`:
379379
3. In `Branch Sources` sections, select `Add source` | select `GitLab Project`.
380380
381381
4. Now you need to configure your jobs.
382-
382+
383383
![branch-source](/docs/img/branch-source.png)
384-
384+
385385
i. Select `Server` configured in the initial server setup.
386-
386+
387387
ii. [Optional] Add `Checkout Credentials` (SSHPrivateKey or Username/Password) if there is any private projects that will be built by the plugin.
388-
388+
389389
iii. Add path to the owner where the project you want to build exists. If user, enter `username`. If group, enter `group name`. If subgroup, enter `subgroup path with namespace`.
390-
390+
391391
iv. Based on the owner provided. All the projects are discovered in the path and added to the `Projects` listbox. You can now choose the project you want to build.
392-
392+
393393
v. `Behaviours` (a.k.a. SCM Traits) allow different configurations option to your build. More about it in the SCM Trait APIs section.
394394
395395
5. Now you can go ahead and save the job.
@@ -402,7 +402,7 @@ The Job results are notified to the GitLab Server as Pipeline Status for the HEA
402402
403403
We have a workaround for this. Jenkins will build the MRs from forked projects if the MR author is a trusted owner i.e. has `Developer`/`Maintainer`/`Owner` access level. More about it in the SCM Trait APIs section.
404404
405-
As the web hook is now setup on your Jenkins CI by the GitLab server. Any push-events or merge-request events or tag events trigger the concerned build in Jenkins.
405+
As the web hook is now setup on your Jenkins CI by the GitLab server. Any push-events or merge-request events or tag events trigger the concerned build in Jenkins.
406406
407407
### Folder Organization
408408
@@ -415,7 +415,7 @@ To create a `GitLab Group Job`:
415415
2. Enter a name for your job, select `GitLab Group` | select `Ok`.
416416
417417
3. Now you need to configure your jobs.
418-
418+
419419
i. Select `Server` configured in the initial server setup.
420420
421421
ii. [Optional] Add `Checkout Credentials` (SSHPrivateKey or Username/Password) only if there are any private projects required to be built.
@@ -439,26 +439,26 @@ The following behaviours apply to both `Multibranch Pipeline Jobs` and `Folder O
439439
* `All Branches` - Ignores whether the branch is also filed as a merge request and instead discovers all branches on the origin project.
440440
441441
* `Discover merge requests from origin` - To discover merge requests made from origin branches.
442-
442+
443443
* `Merging the merge request merged with current target revision` - Discover each merge request once with the discovered revision corresponding to the result of merging with the current revision of the target branch.
444444
* `The current merge request revision` - Discover each merge request once with the discovered revision corresponding to the merge request head revision without merging.
445445
* `Both current mr revision and the mr merged with current target revision` - Discover each merge request twice. The first discovered revision corresponds to the result of merging with the current revision of the target branch in each scan. The second parallel discovered revision corresponds to the merge request head revision without merging.
446446
447447
* `Discover merge requests from forks` - To discover merge requests made from forked project branches.
448448
449449
* Strategy:
450-
450+
451451
* `Merging the merge request merged with current target revision` - Discover each merge request once with the discovered revision corresponding to the result of merging with the current revision of the target branch.
452452
* `The current merge request revision` - Discover each merge request once with the discovered revision corresponding to the merge request head revision without merging.
453453
* `Both current mr revision and the mr merged with current target revision` - Discover each merge request twice. The first discovered revision corresponds to the result of merging with the current revision of the target branch in each scan. The second parallel discovered revision corresponds to the merge request head revision without merging.
454-
454+
455455
* Trust
456-
456+
457457
* `Members` - Discover MRs from Forked Projects whose author is a member of the origin project.
458458
* `Trusted Members` - [Recommended] Discover MRs from Forked Projects whose author is has Developer/Maintainer/Owner accesslevel in the origin project.
459459
* `Everyone` - Discover MRs from Forked Projects filed by anybody. For security reasons you should never use this option. It may be used to reveal your Pipeline secrets environment variables.
460460
* `Nobody` - Discover no MRs from Forked Projects at all. Equivalent to removing the trait altogether.
461-
461+
462462
If `Members` or `Trusted Members` is selected, then plugin will build the target branch of MRs from non/untrusted members.
463463
464464
### Additional Traits:
@@ -469,7 +469,7 @@ These traits can be selected by selecting `Add` in the `Behaviours` section.
469469
470470
* `Discover group/subgroup projects` - Discover subgroup projects inside a group/subgroup. Only applicable to `GitLab Group` Job type whose owner is a `Group`/`Subgroup` but not `User`.
471471
472-
* `Log build status as comment on GitLab` - Enable logging build status as comment on GitLab. A comment is logged on the commit or merge request once the build is completed. You can decide if you want to log success builds or not. You can also use sudo user to comment the build status as commment e.g. `jenkinsadmin` or something similar.
472+
* `Log build status as comment on GitLab` - Enable logging build status as comment on GitLab. A comment is logged on the commit or merge request once the build is completed. You can decide if you want to log success builds or not. You can also use sudo user to comment the build status as commment e.g. `jenkinsadmin` or something similar.
473473
474474
* `Trigger build on merge request comment` - Enable trigger a rebuild of a merge request by comment with your desired comment body (default: `jenkins rebuild`). The job can only be triggered by trusted members of the project i.e. users with Developer/Maintainer/Owner accesslevel (also includes inherited from ancestor groups). By default only trusted members of project can trigger MR.
475475
You may want to disable this option because trusted members do not include members inherited from shared group (there is no way to get it from GitLabApi as of GitLab 13.0.0). If disabled, MR comment trigger can be done by any user having access to your project.
@@ -488,6 +488,8 @@ You may want to disable this option because trusted members do not include membe
488488
489489
* `Checkout over SSH` - [Not Recommended] Use this mode to checkout over SSH. Use `Checkout Credentials` instead.
490490
491+
* `Webhook Listener Conditions` - Set conditions based on the webhook content on when a build should be triggered.
492+
491493
## Environment Variables
492494
493495
By default Multibranch Jobs have the following environment variables (provided by Branch API Plugin):
@@ -498,19 +500,19 @@ Merge Request - `BRANCH_NAME`, `CHANGE_ID`, `CHANGE_TARGET`, `CHANGE_BRANCH`, `C
498500
499501
Tag - `BRANCH_NAME`, `TAG_NAME`, `TAG_TIMESTAMP`, `TAG_DATE`, `TAG_UNIXTIME`
500502
501-
This plugin adds a few more environment variables to Builds (`WorkflowRun` type only) which is the payload received as WebHook) See https://docs.gitlab.com/ee/user/project/integrations/webhooks.html#events.
503+
This plugin adds a few more environment variables to Builds (`WorkflowRun` type only) which is the payload received as WebHook) See https://docs.gitlab.com/ee/user/project/integrations/webhooks.html#events.
502504
503-
A few points to note:
505+
A few points to note:
504506
505507
> If no response is recorded for any field in the Web Hook Payload, it returns an empty String. To add more variables see `package io.jenkins.plugins.gitlabbranchsource.Cause`.
506-
>
508+
>
507509
> `GITLAB_OBJECT_KIND` - This environment variable should be used to check the event type before accessing the environment variables. Possible values are `none`, `push`, `tag_push` and `merge_request`.
508510
>
509511
> Any variables ending with `#` indicates the index of the list of the payload starting from 1.
510512
511513
Environment Variables are available from Push Event, Tag Push Event and Merge Request Event.
512514
513-
### Push Event:
515+
### Push Event:
514516
515517
See https://docs.gitlab.com/ee/user/project/integrations/webhooks.html#push-events
516518
@@ -561,12 +563,12 @@ GITLAB_REFS_HEAD
561563
562564
### Tag Event:
563565
564-
Note:
565-
> Jenkins by default refrains from automatically building Tags on push ([See reason](https://issues.jenkins-ci.org/browse/JENKINS-47496?focusedCommentId=332369&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-332369)). You need to install Branch Build Strategy Plugin to solve this.
566-
>
566+
Note:
567+
> Jenkins by default refrains from automatically building Tags on push ([See reason](https://issues.jenkins-ci.org/browse/JENKINS-47496?focusedCommentId=332369&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-332369)). You need to install Branch Build Strategy Plugin to solve this.
568+
>
567569
> See Guide: https://github.com/jenkinsci/basic-branch-build-strategies-plugin/blob/master/docs/user.adoc
568570
>
569-
> Do remember if you are using Basic Branch Build for tag builds you also need to add strategies for branch and pull request (change request) else they would not be automatically built (See GIF below).
571+
> Do remember if you are using Basic Branch Build for tag builds you also need to add strategies for branch and pull request (change request) else they would not be automatically built (See GIF below).
570572
571573
![branch-build-strategy](/docs/img/branch-build-strategy.gif)
572574
@@ -760,7 +762,7 @@ organizationFolder('GitLab Organization Folder') {
760762
// "Traits" ("Behaviours" in the GUI) that are NOT "declarative-compatible"
761763
// For some 'traits, we need to configure this stuff by hand until JobDSL handles it
762764
// https://issues.jenkins.io/browse/JENKINS-45504
763-
configure {
765+
configure {
764766
def traits = it / navigators / 'io.jenkins.plugins.gitlabbranchsource.GitLabSCMNavigator' / traits
765767
traits << 'io.jenkins.plugins.gitlabbranchsource.ForkMergeRequestDiscoveryTrait' {
766768
strategyId(2)
@@ -879,10 +881,10 @@ This plugin is built and maintained by the Google Summer of Code (GSoC) Team for
879881
880882
Maintainers:
881883
882-
* [Parichay](https://github.com/baymac)
883-
* [Marky](https://github.com/markyjackson-taulia)
884-
* [Joseph](https://github.com/casz)
885-
* [Justin](https://github.com/justinharringa)
884+
* [Parichay](https://github.com/baymac)
885+
* [Marky](https://github.com/markyjackson-taulia)
886+
* [Joseph](https://github.com/casz)
887+
* [Justin](https://github.com/justinharringa)
886888
887889
External Support:
888890
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package io.jenkins.plugins.gitlabbranchsource;
2+
3+
import edu.umd.cs.findbugs.annotations.NonNull;
4+
import java.util.logging.Level;
5+
import java.util.logging.Logger;
6+
import jenkins.scm.api.SCMHeadObserver;
7+
import org.gitlab4j.api.webhook.MergeRequestEvent;
8+
import org.gitlab4j.api.webhook.MergeRequestEvent.ObjectAttributes;
9+
10+
public class GitLabMergeRequestTrigger extends GitLabMergeRequestSCMEvent {
11+
12+
public static final Logger LOGGER = Logger
13+
.getLogger(GitLabMergeRequestTrigger.class.getName());
14+
15+
public GitLabMergeRequestTrigger(MergeRequestEvent mrEvent, String origin) {
16+
super(mrEvent, origin);
17+
}
18+
19+
@Override
20+
public boolean isMatch(@NonNull GitLabSCMSource source) {
21+
final GitLabSCMSourceContext sourceContext = new GitLabSCMSourceContext(
22+
null, SCMHeadObserver.none())
23+
.withTraits(source.getTraits());
24+
25+
boolean shouldBuild = this.shouldBuild(getPayload(), sourceContext);
26+
LOGGER.log(Level.FINE, "isMatch() result for MR-{0}: {1}",
27+
new Object[]{
28+
getPayload().getObjectAttributes().getIid(),
29+
String.valueOf(shouldBuild)
30+
});
31+
32+
return getPayload().getObjectAttributes().getTargetProjectId()
33+
.equals(source.getProjectId()) && shouldBuild;
34+
}
35+
36+
private boolean shouldBuild(MergeRequestEvent mrEvent, GitLabSCMSourceContext context) {
37+
ObjectAttributes attributes = mrEvent.getObjectAttributes();
38+
String action = attributes.getAction();
39+
boolean shouldBuild = true;
40+
41+
if (action != null) {
42+
if (action.equals("update") && context.alwaysIgnoreNonCodeRelatedUpdates()) {
43+
if (mrEvent.getChanges().getAssignees() != null) {
44+
shouldBuild = false;
45+
}
46+
47+
if (mrEvent.getChanges().getDescription() != null) {
48+
shouldBuild = false;
49+
}
50+
51+
if (mrEvent.getChanges().getMilestoneId() != null) {
52+
shouldBuild = false;
53+
}
54+
55+
if (mrEvent.getChanges().getTitle() != null) {
56+
shouldBuild = false;
57+
}
58+
59+
if (mrEvent.getChanges().getTotalTimeSpent() != null) {
60+
shouldBuild = false;
61+
}
62+
63+
if (mrEvent.getChanges().getLabels() != null) {
64+
shouldBuild = false;
65+
}
66+
}
67+
68+
if (!shouldBuild) {
69+
LOGGER.log(Level.FINE, "shouldBuild for MR-{0} set to false due to non-code related updates.",
70+
getPayload().getObjectAttributes().getIid());
71+
}
72+
73+
if (action.equals("open")) {
74+
return context.alwaysBuildMROpen();
75+
}
76+
77+
if (action.equals("reopen")) {
78+
return context.alwaysBuildMRReOpen();
79+
}
80+
81+
if (action.equals("approved")) {
82+
return !context.alwaysIgnoreMRApprove();
83+
}
84+
85+
if (action.equals("unapproved")) {
86+
return !context.alwaysIgnoreMRUnApprove();
87+
}
88+
}
89+
90+
return shouldBuild;
91+
}
92+
}

src/main/java/io/jenkins/plugins/gitlabbranchsource/GitLabSCMSource.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -899,7 +899,8 @@ public List<SCMSourceTrait> getTraitsDefaults() {
899899
new BranchDiscoveryTrait(true, false),
900900
new OriginMergeRequestDiscoveryTrait(EnumSet.of(ChangeRequestCheckoutStrategy.MERGE)),
901901
new ForkMergeRequestDiscoveryTrait(EnumSet.of(ChangeRequestCheckoutStrategy.MERGE),
902-
new ForkMergeRequestDiscoveryTrait.TrustPermission()));
902+
new ForkMergeRequestDiscoveryTrait.TrustPermission()),
903+
new WebhookListenerBuildConditionsTrait());
903904
}
904905

905906
@NonNull

0 commit comments

Comments
 (0)