Debian Codegraph @

jenkins_jobs/modules/triggers.py

raw
1 # Copyright 2012 Hewlett-Packard Development Company, L.P.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14
15
16 """
17 Triggers define what causes a Jenkins job to start building.
18
19 **Component**: triggers
20 :Macro: trigger
21 :Entry Point: jenkins_jobs.triggers
22
23 Example::
24
25 job:
26 name: test_job
27
28 triggers:
29 - timed: '@daily'
30 """
31
32 import logging
33 import re
34 import xml.etree.ElementTree as XML
35
36 import six
37
38 from jenkins_jobs.errors import InvalidAttributeError
39 from jenkins_jobs.errors import JenkinsJobsException
40 from jenkins_jobs.errors import MissingAttributeError
41 import jenkins_jobs.modules.base
42 from jenkins_jobs.modules import hudson_model
43 import jenkins_jobs.modules.helpers as helpers
44
45 logger = logging.getLogger(str(__name__))
46
47
48 def gerrit_handle_legacy_configuration(data):
49 hyphenizer = re.compile("[A-Z]")
50
51 def hyphenize(attr):
52 """Convert strings like triggerOn to trigger-on."""
53 return hyphenizer.sub(lambda x: "-%s" % x.group(0).lower(), attr)
54
55 def convert_dict(d, old_keys):
56 for old_key in old_keys:
57 if old_key in d:
58 new_key = hyphenize(old_key)
59 logger.warning(
60 "'%s' is deprecated and will be removed after "
61 "1.0.0, please use '%s' instead",
62 old_key,
63 new_key,
64 )
65 d[new_key] = d[old_key]
66 del d[old_key]
67
68 convert_dict(
69 data,
70 [
71 "triggerOnPatchsetUploadedEvent",
72 "triggerOnChangeAbandonedEvent",
73 "triggerOnChangeMergedEvent",
74 "triggerOnChangeRestoredEvent",
75 "triggerOnCommentAddedEvent",
76 "triggerOnDraftPublishedEvent",
77 "triggerOnRefUpdatedEvent",
78 "triggerApprovalCategory",
79 "triggerApprovalValue",
80 "overrideVotes",
81 "gerritBuildSuccessfulVerifiedValue",
82 "gerritBuildFailedVerifiedValue",
83 "failureMessage",
84 "skipVote",
85 ],
86 )
87
88 for project in data.get("projects", []):
89 convert_dict(
90 project,
91 [
92 "projectCompareType",
93 "projectPattern",
94 "branchCompareType",
95 "branchPattern",
96 ],
97 )
98
99 mapping_obj_type = type(data)
100
101 old_format_events = mapping_obj_type(
102 (key, should_register)
103 for key, should_register in six.iteritems(data)
104 if key.startswith("trigger-on-")
105 )
106 trigger_on = data.setdefault("trigger-on", [])
107 if old_format_events:
108 logger.warning(
109 "The events: %s; which you used is/are deprecated. "
110 "Please use 'trigger-on' instead.",
111 ", ".join(old_format_events),
112 )
113
114 if old_format_events and trigger_on:
115 raise JenkinsJobsException(
116 "Both, the new format (trigger-on) and old format (trigger-on-*) "
117 "gerrit events format found. Please use either the new or the old "
118 "format of trigger events definition."
119 )
120
121 trigger_on.extend(
122 event_name[len("trigger-on-") :]
123 for event_name, should_register in six.iteritems(old_format_events)
124 if should_register
125 )
126
127 for idx, event in enumerate(trigger_on):
128 if event == "comment-added-event":
129 trigger_on[idx] = events = mapping_obj_type()
130 try:
131 events["comment-added-event"] = mapping_obj_type(
132 (
133 ("approval-category", data["trigger-approval-category"]),
134 ("approval-value", data["trigger-approval-value"]),
135 )
136 )
137 except KeyError:
138 raise JenkinsJobsException(
139 "The comment-added-event trigger requires which approval "
140 "category and value you want to trigger the job. "
141 "It should be specified by the approval-category "
142 "and approval-value properties."
143 )
144
145
146 def build_gerrit_triggers(xml_parent, data, plugin_ver):
147 available_simple_triggers = {
148 "change-abandoned-event": "PluginChangeAbandonedEvent",
149 "change-merged-event": "PluginChangeMergedEvent",
150 "change-restored-event": "PluginChangeRestoredEvent",
151 "draft-published-event": "PluginDraftPublishedEvent",
152 "patchset-uploaded-event": "PluginPatchsetCreatedEvent",
153 "patchset-created-event": "PluginPatchsetCreatedEvent",
154 "private-state-changed-event": "PluginPrivateStateChangedEvent",
155 "ref-updated-event": "PluginRefUpdatedEvent",
156 "topic-changed-event": "PluginTopicChangedEvent",
157 "wip-state-changed-event": "PluginWipStateChangedEvent",
158 }
159 tag_namespace = (
160 "com.sonyericsson.hudson.plugins.gerrit.trigger." "hudsontrigger.events"
161 )
162
163 trigger_on_events = XML.SubElement(xml_parent, "triggerOnEvents")
164
165 for event in data.get("trigger-on", []):
166 if isinstance(event, six.string_types):
167 tag_name = available_simple_triggers.get(event)
168 if event == "patchset-uploaded-event":
169 logger.warning(
170 "'%s' is deprecated. Use 'patchset-created-event' "
171 "format instead.",
172 event,
173 )
174
175 if not tag_name:
176 known = ", ".join(
177 available_simple_triggers.keys()
178 + ["comment-added-event", "comment-added-contains-event"]
179 )
180 msg = (
181 "The event '%s' under 'trigger-on' is not one of the " "known: %s."
182 ) % (event, known)
183 raise JenkinsJobsException(msg)
184 XML.SubElement(trigger_on_events, "%s.%s" % (tag_namespace, tag_name))
185 else:
186 if "patchset-created-event" in event.keys():
187 pce = event["patchset-created-event"]
188 pc = XML.SubElement(
189 trigger_on_events,
190 "%s.%s" % (tag_namespace, "PluginPatchsetCreatedEvent"),
191 )
192 mapping = [
193 ("exclude-drafts", "excludeDrafts", False),
194 ("exclude-trivial-rebase", "excludeTrivialRebase", False),
195 ("exclude-no-code-change", "excludeNoCodeChange", False),
196 ("exclude-private", "excludePrivateState", False),
197 ("exclude-wip", "excludeWipState", False),
198 ]
199 if plugin_ver >= "2.32.0":
200 mapping.append(
201 (
202 "commit-message-contains-regex",
203 "commitMessageContainsRegEx",
204 "",
205 )
206 )
207
208 helpers.convert_mapping_to_xml(pc, pce, mapping, fail_required=True)
209
210 if "comment-added-event" in event.keys():
211 comment_added_event = event["comment-added-event"]
212 cadded = XML.SubElement(
213 trigger_on_events,
214 "%s.%s" % (tag_namespace, "PluginCommentAddedEvent"),
215 )
216 mapping = [
217 ("approval-category", "verdictCategory", None),
218 ("approval-value", "commentAddedTriggerApprovalValue", None),
219 ]
220 helpers.convert_mapping_to_xml(
221 cadded, comment_added_event, mapping, fail_required=True
222 )
223
224 if "comment-added-contains-event" in event.keys():
225 comment_added_event = event["comment-added-contains-event"]
226 caddedc = XML.SubElement(
227 trigger_on_events,
228 "%s.%s" % (tag_namespace, "PluginCommentAddedContainsEvent"),
229 )
230 XML.SubElement(
231 caddedc, "commentAddedCommentContains"
232 ).text = comment_added_event["comment-contains-value"]
233
234
235 def build_gerrit_skip_votes(xml_parent, data, plugin_ver):
236 outcomes = [
237 ("successful", "onSuccessful"),
238 ("failed", "onFailed"),
239 ("unstable", "onUnstable"),
240 ("notbuilt", "onNotBuilt"),
241 ]
242 if plugin_ver >= "2.32.0":
243 outcomes.append(("aborted", "onAborted"))
244
245 skip_vote_node = XML.SubElement(xml_parent, "skipVote")
246 skip_vote = data.get("skip-vote", {})
247 for result_kind, tag_name in outcomes:
248 setting = skip_vote.get(result_kind, False)
249 XML.SubElement(skip_vote_node, tag_name).text = str(setting).lower()
250
251
252 def build_cancellation_policy(xml_parent, data, plugin_ver):
253 if plugin_ver >= "2.32.0":
254 options = [
255 ("abort-new-patchsets", "abortNewPatchsets"),
256 ("abort-manual-patchsets", "abortManualPatchsets"),
257 ("abort-same-topic", "abortSameTopic"),
258 ]
259
260 build_cancellation_policy_node = XML.SubElement(
261 xml_parent, "buildCancellationPolicy"
262 )
263 build_cancellation_policy_object = data.get("build-cancellation-policy", {})
264 XML.SubElement(build_cancellation_policy_node, "enabled").text = "true"
265 for tag, tag_name in options:
266 setting = build_cancellation_policy_object.get(tag, False)
267 XML.SubElement(build_cancellation_policy_node, tag_name).text = str(
268 setting
269 ).lower()
270
271
272 def build_gerrit_parameter_modes(xml_parent, data, plugin_ver):
273 if plugin_ver < "2.18.0":
274 for parameter_name in (
275 "commit-message",
276 "name-and-email",
277 "change-subject",
278 "comment-text",
279 ):
280 parameter_mode = "{}-parameter-mode".format(parameter_name)
281 if parameter_mode in data:
282 logger.warning(
283 "Gerrit Trigger property '{}' is not supported in this "
284 "plugin version".format(parameter_mode)
285 )
286
287 deprecated_mappings = (
288 ("no-name-and-email", "noNameAndEmailParameters", False),
289 ("readable-message", "readableMessage", False),
290 )
291 helpers.convert_mapping_to_xml(
292 xml_parent, data, deprecated_mappings, fail_required=True
293 )
294 else: # version >= 2.18.0
295 readable_message = data.get("readable-message")
296 if readable_message is not None:
297 logger.warning("Gerrit Trigger property 'readable-message' is deprecated")
298 no_name_and_email = data.get("no-name-and-email")
299 if no_name_and_email is not None:
300 logger.warning("Gerrit Trigger property 'no-name-and-email' is deprecated")
301 allowed_parameter_modes = ["NONE", "PLAIN", "BASE64"]
302 new_mappings = (
303 (
304 "commit-message-parameter-mode",
305 "commitMessageParameterMode",
306 "BASE64" if readable_message is not True else "PLAIN",
307 allowed_parameter_modes,
308 ),
309 (
310 "name-and-email-parameter-mode",
311 "nameAndEmailParameterMode",
312 "PLAIN" if no_name_and_email is not True else "NONE",
313 allowed_parameter_modes,
314 ),
315 (
316 "change-subject-parameter-mode",
317 "changeSubjectParameterMode",
318 "PLAIN",
319 allowed_parameter_modes,
320 ),
321 (
322 "comment-text-parameter-mode",
323 "commentTextParameterMode",
324 "BASE64",
325 allowed_parameter_modes,
326 ),
327 )
328 helpers.convert_mapping_to_xml(
329 xml_parent, data, new_mappings, fail_required=True
330 )
331
332
333 def gerrit(registry, xml_parent, data):
334 """yaml: gerrit
335
336 Trigger on a Gerrit event.
337
338 Requires the Jenkins :jenkins-plugins:`Gerrit Trigger Plugin
339 <gerrit-trigger>` version >= 2.6.0.
340
341 :arg list trigger-on: Events to react on. Please use either the new
342 **trigger-on**, or the old **trigger-on-*** events definitions. You
343 cannot use both at once.
344
345 .. _trigger_on:
346
347 :Trigger on:
348
349 * **patchset-created-event** (`dict`) -- Trigger upon patchset
350 creation.
351
352 :Patchset created:
353 * **exclude-drafts** (`bool`) -- exclude drafts (default false)
354 * **exclude-trivial-rebase** (`bool`) -- exclude trivial rebase
355 (default false)
356 * **exclude-no-code-change** (`bool`) -- exclude no code change
357 (default false)
358 * **exclude-private** (`bool`) -- exclude private change
359 (default false)
360 * **exclude-wip** (`bool`) -- exclude wip change
361 (default false)
362 * **commit-message-contains-regex** (`str`) -- Commit message
363 contains regular expression. (default '')
364 Requires Gerrit Trigger Plugin >= 2.32.0
365
366 exclude-private|exclude-wip needs
367 Gerrit Trigger v2.29.0
368 Exclude drafts|trivial-rebase|no-code-change needs
369 Gerrit Trigger v2.12.0
370
371 * **patchset-uploaded-event** -- Trigger upon patchset creation
372 (this is a alias for `patchset-created-event`).
373
374 .. deprecated:: 1.1.0 Please use :ref:`trigger-on <trigger_on>`.
375
376 * **change-abandoned-event** -- Trigger on patchset abandoned.
377 Requires Gerrit Trigger Plugin version >= 2.8.0.
378 * **change-merged-event** -- Trigger on change merged
379 * **change-restored-event** -- Trigger on change restored. Requires
380 Gerrit Trigger Plugin version >= 2.8.0
381 * **draft-published-event** -- Trigger on draft published event.
382 * **ref-updated-event** -- Trigger on ref-updated.
383 Gerrit Trigger Plugin version >= 2.29.0
384 * **topic-changed-event** -- Trigger on topic-changed.
385 Gerrit Trigger Plugin version >= 2.26.0
386 * **private-state-changed-event** -- Trigger on private state changed event.
387 * **wip-state-changed-event** -- Trigger on wip state changed event.
388 Gerrit Trigger Plugin version >= 2.8.0
389 * **comment-added-event** (`dict`) -- Trigger on comment added.
390
391 :Comment added:
392 * **approval-category** (`str`) -- Approval (verdict) category
393 (for example 'APRV', 'CRVW', 'VRIF' -- see `Gerrit access
394 control
395 <https://gerrit-review.googlesource.com/Documentation/
396 access-control.html#access_categories>`_
397
398 * **approval-value** -- Approval value for the comment added.
399 * **comment-added-contains-event** (`dict`) -- Trigger on comment
400 added contains Regular Expression.
401
402 :Comment added contains:
403 * **comment-contains-value** (`str`) -- Comment contains
404 Regular Expression value.
405
406 :arg bool trigger-on-patchset-uploaded-event: Trigger on patchset upload.
407
408 .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
409
410 :arg bool trigger-on-change-abandoned-event: Trigger on change abandoned.
411 Requires Gerrit Trigger Plugin version >= 2.8.0
412
413 .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
414
415 :arg bool trigger-on-change-merged-event: Trigger on change merged
416
417 .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
418
419 :arg bool trigger-on-change-restored-event: Trigger on change restored.
420 Requires Gerrit Trigger Plugin version >= 2.8.0
421
422 .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
423
424 :arg bool trigger-on-comment-added-event: Trigger on comment added
425
426 .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
427
428 :arg bool trigger-on-draft-published-event: Trigger on draft published
429 event
430
431 .. deprecated:: 1.1.0 Please use :ref:`trigger-on <trigger_on>`.
432
433 :arg bool trigger-on-ref-updated-event: Trigger on ref-updated
434
435 .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
436
437 :arg str trigger-approval-category: Approval category for comment added
438
439 .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
440
441 :arg int trigger-approval-value: Approval value for comment added
442
443 .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
444
445 :arg bool override-votes: Override default vote values
446 :arg int gerrit-build-started-verified-value: Started ''Verified'' value
447 :arg int gerrit-build-successful-verified-value: Successful ''Verified''
448 value
449 :arg int gerrit-build-failed-verified-value: Failed ''Verified'' value
450 :arg int gerrit-build-unstable-verified-value: Unstable ''Verified'' value
451 :arg int gerrit-build-notbuilt-verified-value: Not built ''Verified''
452 value
453 :arg int gerrit-build-aborted-verified-value: Aborted ''Verified'' value
454 Requires Gerrit Trigger Plugin version >= 2.31.0
455 :arg int gerrit-build-started-codereview-value: Started ''CodeReview''
456 value
457 :arg int gerrit-build-successful-codereview-value: Successful
458 ''CodeReview'' value
459 :arg int gerrit-build-failed-codereview-value: Failed ''CodeReview'' value
460 :arg int gerrit-build-unstable-codereview-value: Unstable ''CodeReview''
461 value
462 :arg int gerrit-build-notbuilt-codereview-value: Not built ''CodeReview''
463 value
464 :arg int gerrit-build-aborted-codereview-value: Aborted ''CodeReview''
465 value
466 Requires Gerrit Trigger Plugin version >= 2.31.0
467 :arg str failure-message: Message to leave on failure (default '')
468 :arg str successful-message: Message to leave on success (default '')
469 :arg str unstable-message: Message to leave when unstable (default '')
470 :arg str notbuilt-message: Message to leave when not built (default '')
471 :arg str aborted-message: Message to leave when aborted (default '')
472 :arg str failure-message-file: Sets the filename within the workspace from
473 which to retrieve the unsuccessful review message. (optional)
474 :arg list projects: list of projects to match
475
476 :Project: * **project-compare-type** (`str`) -- ''PLAIN'', ''ANT'' or
477 ''REG_EXP''
478 * **project-pattern** (`str`) -- Project name pattern to match
479 * **branch-compare-type** (`str`) -- ''PLAIN'', ''ANT'' or
480 ''REG_EXP'' (not used if `branches` list is specified)
481
482 .. deprecated:: 1.1.0 Please use :ref:`branches <branches>`.
483
484 * **branch-pattern** (`str`) -- Branch name pattern to match
485 (not used if `branches` list is specified)
486
487 .. deprecated:: 1.1.0 Please use :ref:`branches <branches>`.
488
489 .. _branches:
490
491 * **branches** (`list`) -- List of branches to match
492 (optional)
493
494 :Branch: * **branch-compare-type** (`str`) -- ''PLAIN'',
495 ''ANT'' or ''REG_EXP'' (optional) (default
496 ''PLAIN'')
497 * **branch-pattern** (`str`) -- Branch name pattern
498 to match
499
500 * **file-paths** (`list`) -- List of file paths to match
501 (optional)
502
503 :File Path: * **compare-type** (`str`) -- ''PLAIN'', ''ANT''
504 or ''REG_EXP'' (optional) (default ''PLAIN'')
505 * **pattern** (`str`) -- File path pattern to
506 match
507
508 * **forbidden-file-paths** (`list`) -- List of file paths to
509 skip triggering (optional)
510
511 :Forbidden File Path: * **compare-type** (`str`) --
512 ''PLAIN'', ''ANT'' or ''REG_EXP'' (optional)
513 (default ''PLAIN'')
514 * **pattern** (`str`) -- File path pattern to
515 match
516
517 * **topics** (`list`) -- List of topics to match
518 (optional)
519
520 :Topic: * **compare-type** (`str`) -- ''PLAIN'', ''ANT'' or
521 ''REG_EXP'' (optional) (default ''PLAIN'')
522 * **pattern** (`str`) -- Topic name pattern to
523 match
524
525 * **disable-strict-forbidden-file-verification** (`bool`) --
526 Enabling this option will allow an event to trigger a
527 build if the event contains BOTH one or more wanted file
528 paths AND one or more forbidden file paths. In other
529 words, with this option, the build will not get
530 triggered if the change contains only forbidden files,
531 otherwise it will get triggered. Requires plugin
532 version >= 2.16.0 (default false)
533
534 :arg dict skip-vote: map of build outcomes for which Jenkins must skip
535 vote. Requires Gerrit Trigger Plugin version >= 2.7.0
536
537 :Outcome: * **successful** (`bool`)
538 * **failed** (`bool`)
539 * **unstable** (`bool`)
540 * **notbuilt** (`bool`)
541 * **aborted** (`bool`) -- Requires Gerrit Trigger Plugin version >= 2.31.0
542
543 :arg bool silent: When silent mode is on there will be no communication
544 back to Gerrit, i.e. no build started/failed/successful approve
545 messages etc. If other non-silent jobs are triggered by the same
546 Gerrit event as this job, the result of this job's build will not be
547 counted in the end result of the other jobs. (default false)
548 :arg bool silent-start: Sets silent start mode to on or off. When silent
549 start mode is on there will be no 'build started' messages sent back
550 to Gerrit. (default false)
551 :arg bool escape-quotes: escape quotes in the values of Gerrit change
552 parameters (default true)
553 :arg dict build-cancellation-policy: If used, rules regarding
554 cancellation of builds can be set with this option when
555 patchsets of the same change comes in. This setting overrides global
556 server configuration. If build-cancellation-policy is not present in
557 YAML the global server configuration is used.
558 Requires Gerrit Trigger Plugin version >= 2.32.0
559
560 :Options: * **abort-new-patchsets** (`bool`) -- Only running jobs
561 will be cancelled if a new patch version is pushed over
562 (default false).
563 * **abort-manual-patchsets** (`bool`) -- Builds triggered
564 manually will be aborted when a new patch set arrives
565 (default false).
566 * **abort-same-topic** (`bool`) -- Builds triggered with
567 topic will be aborted when a new patch set with the
568 same topic arrives (default false).
569
570 :arg bool no-name-and-email: Do not pass compound 'name and email'
571 parameters (default false)
572
573 .. deprecated:: 3.5.0 Please use `name-and-email-parameter-mode`
574 parameter.
575
576 :arg bool readable-message: If parameters regarding multiline text,
577 e.g. commit message, should be as human readable or not. If false,
578 those parameters are Base64 encoded to keep environment variables
579 clean. (default false)
580
581 .. deprecated:: 3.5.0 Please use `commit-message-parameter-mode`
582 parameter.
583
584 :arg str name-and-email-parameter-mode: The parameter mode for the compound
585 "name and email" parameters (like GERRIT_PATCHSET_UPLOADER or
586 GERRIT_CHANGE_OWNER). This can either be 'NONE' to avoid passing the
587 parameter all together, 'PLAIN' to pass the parameter in human readable
588 form, or 'BASE64' to pass the parameter in base64 encoded form (default
589 'PLAIN'). Requires Gerrit Trigger Plugin version >= 2.18.0.
590 :arg str commit-message-parameter-mode: The parameter mode for the
591 GERRIT_CHANGE_COMMIT_MESSAGE parameter. This can either be 'NONE' to
592 avoid passing the parameter all together, 'PLAIN' to pass the parameter
593 in human readable form, or 'BASE64' to pass the parameter in base64
594 encoded form (default 'BASE64'). Requires Gerrit Trigger Plugin version
595 >= 2.18.0.
596 :arg str change-subject-parameter-mode: The parameter mode for the
597 GERRIT_CHANGE_SUBJECT parameter. This can either be 'NONE' to avoid
598 passing the parameter all together, 'PLAIN' to pass the parameter in
599 human readable form, or 'BASE64' to pass the parameter in base64
600 encoded form (default 'PLAIN'). Requires Gerrit Trigger Plugin version
601 >= 2.18.0.
602 :arg str comment-text-parameter-mode: The parameter mode for the
603 GERRIT_EVENT_COMMENT_TEXT parameter. This can either be 'NONE' to avoid
604 passing the parameter all together, 'PLAIN' to pass the parameter in
605 human readable form, or 'BASE64' to pass the parameter in base64
606 encoded form (default 'BASE64'). Requires Gerrit Trigger Plugin version
607 >= 2.18.0.
608 :arg str dependency-jobs: All jobs on which this job depends. If a commit
609 should trigger both a dependency and this job, the dependency will be
610 built first. Use commas to separate job names. Beware of cyclic
611 dependencies. (optional)
612 :arg str notification-level: Defines to whom email notifications should be
613 sent. This can either be nobody ('NONE'), the change owner ('OWNER'),
614 reviewers and change owner ('OWNER_REVIEWERS'), all interested users
615 i.e. owning, reviewing, watching, and starring ('ALL') or server
616 default ('SERVER_DEFAULT'). (default 'SERVER_DEFAULT')
617 :arg bool dynamic-trigger-enabled: Enable/disable the dynamic trigger
618 (default false)
619 :arg str dynamic-trigger-url: if you specify this option, the Gerrit
620 trigger configuration will be fetched from there on a regular interval
621 :arg bool trigger-for-unreviewed-patches: trigger patchset-created events
622 for changes that were uploaded while connection to Gerrit was down
623 (default false). Requires Gerrit Trigger Plugin version >= 2.11.0.
624
625 .. deprecated:: 3.5.0 Supported for Gerrit Trigger Plugin versions
626 < 2.14.0. See
627 :jenkins-plugins:`Missed Events Playback Feature <gerrit-trigger/#plugin-content-missed-events-playback-feature-available-from-v-2140>`.
628
629 :arg str custom-url: Custom URL for a message sent to Gerrit. Build
630 details URL will be used if empty. (default '')
631 :arg str server-name: Name of the server to trigger on, or ''__ANY__'' to
632 trigger on any configured Gerrit server (default '__ANY__'). Requires
633 Gerrit Trigger Plugin version >= 2.11.0
634
635 You may select one or more Gerrit events upon which to trigger.
636 You must also supply at least one project and branch, optionally
637 more. If you select the comment-added trigger, you should also
638 indicate which approval category and value you want to trigger the
639 job.
640
641 Until version 0.4.0 of Jenkins Job Builder, camelCase keys were used to
642 configure Gerrit Trigger Plugin, instead of hyphenated-keys. While still
643 supported, camedCase keys are deprecated and should not be used. Support
644 for this will be removed after 1.0.0 is released.
645
646 Example:
647
648 .. literalinclude:: /../../tests/triggers/fixtures/gerrit004.yaml
649 :language: yaml
650
651 """
652
653 def get_compare_type(xml_tag, compare_type):
654 valid_compare_types = ["PLAIN", "ANT", "REG_EXP"]
655
656 if compare_type not in valid_compare_types:
657 raise InvalidAttributeError(xml_tag, compare_type, valid_compare_types)
658 return compare_type
659
660 gerrit_handle_legacy_configuration(data)
661
662 plugin_ver = registry.get_plugin_version("Gerrit Trigger")
663
664 projects = data.get("projects", [])
665 gtrig = XML.SubElement(
666 xml_parent,
667 "com.sonyericsson.hudson.plugins.gerrit.trigger." "hudsontrigger.GerritTrigger",
668 )
669 XML.SubElement(gtrig, "spec")
670 gprojects = XML.SubElement(gtrig, "gerritProjects")
671 for project in projects:
672 gproj = XML.SubElement(
673 gprojects,
674 "com.sonyericsson.hudson.plugins.gerrit."
675 "trigger.hudsontrigger.data.GerritProject",
676 )
677 XML.SubElement(gproj, "compareType").text = get_compare_type(
678 "project-compare-type", project.get("project-compare-type", "PLAIN")
679 )
680 XML.SubElement(gproj, "pattern").text = project["project-pattern"]
681
682 branches = XML.SubElement(gproj, "branches")
683 project_branches = project.get("branches", [])
684
685 if "branch-compare-type" in project and "branch-pattern" in project:
686 warning = (
687 "branch-compare-type and branch-pattern at project "
688 "level are deprecated and support will be removed "
689 "in a later version of Jenkins Job Builder; "
690 )
691 if project_branches:
692 warning += "discarding values and using values from " "branches section"
693 else:
694 warning += "please use branches section instead"
695 logger.warning(warning)
696 if not project_branches:
697 project_branches = [
698 {
699 "branch-compare-type": project.get("branch-compare-type", "PLAIN"),
700 "branch-pattern": project["branch-pattern"],
701 }
702 ]
703 for branch in project_branches:
704 gbranch = XML.SubElement(
705 branches,
706 "com.sonyericsson.hudson.plugins."
707 "gerrit.trigger.hudsontrigger.data.Branch",
708 )
709 XML.SubElement(gbranch, "compareType").text = get_compare_type(
710 "branch-compare-type", branch.get("branch-compare-type", "PLAIN")
711 )
712 XML.SubElement(gbranch, "pattern").text = branch["branch-pattern"]
713
714 project_file_paths = project.get("file-paths", [])
715 if project_file_paths:
716 fps_tag = XML.SubElement(gproj, "filePaths")
717 for file_path in project_file_paths:
718 fp_tag = XML.SubElement(
719 fps_tag,
720 "com.sonyericsson.hudson.plugins."
721 "gerrit.trigger.hudsontrigger.data."
722 "FilePath",
723 )
724 XML.SubElement(fp_tag, "compareType").text = get_compare_type(
725 "compare-type", file_path.get("compare-type", "PLAIN")
726 )
727 XML.SubElement(fp_tag, "pattern").text = file_path["pattern"]
728
729 project_forbidden_file_paths = project.get("forbidden-file-paths", [])
730 if project_forbidden_file_paths:
731 ffps_tag = XML.SubElement(gproj, "forbiddenFilePaths")
732 for forbidden_file_path in project_forbidden_file_paths:
733 ffp_tag = XML.SubElement(
734 ffps_tag,
735 "com.sonyericsson.hudson.plugins."
736 "gerrit.trigger.hudsontrigger.data."
737 "FilePath",
738 )
739 XML.SubElement(ffp_tag, "compareType").text = get_compare_type(
740 "compare-type", forbidden_file_path.get("compare-type", "PLAIN")
741 )
742 XML.SubElement(ffp_tag, "pattern").text = forbidden_file_path["pattern"]
743
744 topics = project.get("topics", [])
745 if topics:
746 topics_tag = XML.SubElement(gproj, "topics")
747 for topic in topics:
748 topic_tag = XML.SubElement(
749 topics_tag,
750 "com.sonyericsson.hudson.plugins."
751 "gerrit.trigger.hudsontrigger.data."
752 "Topic",
753 )
754 XML.SubElement(topic_tag, "compareType").text = get_compare_type(
755 "compare-type", topic.get("compare-type", "PLAIN")
756 )
757 XML.SubElement(topic_tag, "pattern").text = topic["pattern"]
758
759 XML.SubElement(gproj, "disableStrictForbiddenFileVerification").text = str(
760 project.get("disable-strict-forbidden-file-verification", False)
761 ).lower()
762
763 build_gerrit_skip_votes(gtrig, data, plugin_ver)
764 if "build-cancellation-policy" in data:
765 build_cancellation_policy(gtrig, data, plugin_ver)
766 general_mappings = [
767 ("silent", "silentMode", False),
768 ("silent-start", "silentStartMode", False),
769 ("escape-quotes", "escapeQuotes", True),
770 ("dependency-jobs", "dependencyJobsNames", ""),
771 ]
772 helpers.convert_mapping_to_xml(gtrig, data, general_mappings, fail_required=True)
773 build_gerrit_parameter_modes(gtrig, data, plugin_ver)
774 notification_levels = ["NONE", "OWNER", "OWNER_REVIEWERS", "ALL", "SERVER_DEFAULT"]
775 notification_level = data.get("notification-level", "SERVER_DEFAULT")
776 if notification_level not in notification_levels:
777 raise InvalidAttributeError(
778 "notification-level", notification_level, notification_levels
779 )
780 if notification_level == "SERVER_DEFAULT":
781 XML.SubElement(gtrig, "notificationLevel").text = ""
782 else:
783 XML.SubElement(gtrig, "notificationLevel").text = notification_level
784 XML.SubElement(gtrig, "dynamicTriggerConfiguration").text = str(
785 data.get("dynamic-trigger-enabled", False)
786 ).lower()
787 XML.SubElement(gtrig, "triggerConfigURL").text = str(
788 data.get("dynamic-trigger-url", "")
789 )
790 if data.get("dynamic-trigger-enabled", False) is False:
791 XML.SubElement(gtrig, "dynamicGerritProjects").set("class", "empty-list")
792 XML.SubElement(gtrig, "triggerInformationAction").text = str(
793 data.get("trigger-information-action", "")
794 )
795 if plugin_ver >= "2.11.0" and plugin_ver < "2.14.0":
796 XML.SubElement(gtrig, "allowTriggeringUnreviewedPatches").text = str(
797 data.get("trigger-for-unreviewed-patches", False)
798 ).lower()
799 elif "trigger-for-unreviewed-patches" in data:
800 logger.warning(
801 "Gerrit Trigger property 'trigger-for-unreviewed-patches' is not "
802 "supported in this plugin version"
803 )
804 build_gerrit_triggers(gtrig, data, plugin_ver)
805 override = str(data.get("override-votes", False)).lower()
806 if override == "true":
807 votes = [
808 ("gerrit-build-started-verified-value", "gerritBuildStartedVerifiedValue"),
809 (
810 "gerrit-build-successful-verified-value",
811 "gerritBuildSuccessfulVerifiedValue",
812 ),
813 ("gerrit-build-failed-verified-value", "gerritBuildFailedVerifiedValue"),
814 (
815 "gerrit-build-unstable-verified-value",
816 "gerritBuildUnstableVerifiedValue",
817 ),
818 (
819 "gerrit-build-notbuilt-verified-value",
820 "gerritBuildNotBuiltVerifiedValue",
821 ),
822 (
823 "gerrit-build-started-codereview-value",
824 "gerritBuildStartedCodeReviewValue",
825 ),
826 (
827 "gerrit-build-successful-codereview-value",
828 "gerritBuildSuccessfulCodeReviewValue",
829 ),
830 (
831 "gerrit-build-failed-codereview-value",
832 "gerritBuildFailedCodeReviewValue",
833 ),
834 (
835 "gerrit-build-unstable-codereview-value",
836 "gerritBuildUnstableCodeReviewValue",
837 ),
838 (
839 "gerrit-build-notbuilt-codereview-value",
840 "gerritBuildNotBuiltCodeReviewValue",
841 ),
842 ]
843
844 if plugin_ver >= "2.31.0":
845 votes.append(
846 (
847 "gerrit-build-aborted-verified-value",
848 "gerritBuildAbortedVerifiedValue",
849 )
850 )
851 votes.append(
852 (
853 "gerrit-build-aborted-codereview-value",
854 "gerritBuildAbortedCodeReviewValue",
855 )
856 )
857
858 for yamlkey, xmlkey in votes:
859 if data.get(yamlkey) is not None:
860 # str(int(x)) makes input values like '+1' work
861 XML.SubElement(gtrig, xmlkey).text = str(int(data.get(yamlkey)))
862 message_mappings = [
863 ("start-message", "buildStartMessage", ""),
864 ("failure-message", "buildFailureMessage", ""),
865 ("successful-message", "buildSuccessfulMessage", ""),
866 ("unstable-message", "buildUnstableMessage", ""),
867 ("notbuilt-message", "buildNotBuiltMessage", ""),
868 ("failure-message-file", "buildUnsuccessfulFilepath", ""),
869 ("custom-url", "customUrl", ""),
870 ("server-name", "serverName", "__ANY__"),
871 ]
872 if plugin_ver >= "2.31.0":
873 message_mappings.append(("aborted-message", "buildAbortedMessage", ""))
874
875 helpers.convert_mapping_to_xml(gtrig, data, message_mappings, fail_required=True)
876
877
878 def dockerhub_notification(registry, xml_parent, data):
879 """yaml: dockerhub-notification
880 The job will get triggered when Docker Hub/Registry notifies
881 that Docker image(s) used in this job has been rebuilt.
882
883 Requires the Jenkins :jenkins-plugins:`CloudBees Docker Hub Notification
884 <dockerhub-notification>`.
885
886 :arg bool referenced-image: Trigger the job based on repositories
887 used by any compatible docker plugin in this job. (default true)
888 :arg list repositories: Specified repositories to trigger the job.
889 (default [])
890
891 Minimal Example:
892
893 .. literalinclude::
894 /../../tests/triggers/fixtures/dockerhub-notification-minimal.yaml
895 :language: yaml
896
897 Full Example:
898
899 .. literalinclude::
900 /../../tests/triggers/fixtures/dockerhub-notification-full.yaml
901 :language: yaml
902 """
903 dockerhub = XML.SubElement(
904 xml_parent, "org.jenkinsci.plugins." "registry.notification.DockerHubTrigger"
905 )
906 dockerhub.set("plugin", "dockerhub-notification")
907
908 option = XML.SubElement(dockerhub, "options", {"class": "vector"})
909
910 if data.get("referenced-image"):
911 XML.SubElement(
912 option,
913 "org.jenkinsci.plugins."
914 "registry.notification."
915 "opt.impl.TriggerForAllUsedInJob",
916 )
917 repos = data.get("repositories", [])
918 if repos:
919 specified_names = XML.SubElement(
920 option,
921 "org.jenkinsci.plugins.registry."
922 "notification.opt.impl."
923 "TriggerOnSpecifiedImageNames",
924 )
925
926 repo_tag = XML.SubElement(specified_names, "repoNames")
927 for repo in repos:
928 XML.SubElement(repo_tag, "string").text = repo
929
930
931 def pollscm(registry, xml_parent, data):
932 """yaml: pollscm
933 Poll the SCM to determine if there has been a change.
934
935 :Parameter: the polling interval (cron syntax)
936
937 .. deprecated:: 1.3.0. Please use :ref:`cron <cron>`.
938
939 .. _cron:
940
941 :arg str cron: the polling interval (cron syntax, required)
942 :arg bool ignore-post-commit-hooks: Ignore changes notified by SCM
943 post-commit hooks. The subversion-plugin supports this since
944 version 1.44. (default false)
945
946 Example:
947
948 .. literalinclude:: /../../tests/triggers/fixtures/pollscm002.yaml
949 :language: yaml
950 """
951
952 try:
953 cron = data["cron"]
954 ipch = str(data.get("ignore-post-commit-hooks", False)).lower()
955 except KeyError as e:
956 # ensure specific error on the attribute not being set is raised
957 # for new format
958 raise MissingAttributeError(e)
959 except TypeError:
960 # To keep backward compatibility
961 logger.warning(
962 "Your pollscm usage is deprecated, please use"
963 " the syntax described in the documentation"
964 " instead"
965 )
966 cron = data
967 ipch = "false"
968
969 if not cron and cron != "":
970 raise InvalidAttributeError("cron", cron)
971
972 scmtrig = XML.SubElement(xml_parent, "hudson.triggers.SCMTrigger")
973 XML.SubElement(scmtrig, "spec").text = cron
974 XML.SubElement(scmtrig, "ignorePostCommitHooks").text = ipch
975
976
977 def build_content_type(
978 xml_parent,
979 entries,
980 namespace,
981 collection_suffix,
982 entry_suffix,
983 prefix,
984 collection_name,
985 element_name,
986 ):
987 content_type = XML.SubElement(
988 xml_parent, "{0}.{1}{2}".format(namespace, prefix, collection_suffix)
989 )
990 if entries:
991 collection = XML.SubElement(content_type, collection_name)
992 for entry in entries:
993 content_entry = XML.SubElement(
994 collection, "{0}.{1}{2}".format(namespace, prefix, entry_suffix)
995 )
996 XML.SubElement(content_entry, element_name).text = entry
997
998
999 def pollurl(registry, xml_parent, data):
1000 """yaml: pollurl
1001 Trigger when the HTTP response from a URL changes.
1002 Requires the Jenkins :jenkins-plugins:`URLTrigger Plugin <urltrigger>`.
1003
1004 :arg str cron: cron syntax of when to run (default '')
1005 :arg str polling-node: Restrict where the polling should run.
1006 (optional)
1007 :arg list urls: List of URLs to monitor
1008
1009 :URL: * **url** (`str`) -- URL to monitor for changes (required)
1010 * **proxy** (`bool`) -- Activate the Jenkins proxy (default false)
1011 * **timeout** (`int`) -- Connect/read timeout in seconds
1012 (default 300)
1013 * **username** (`str`) -- User name for basic authentication
1014 (optional)
1015 * **password** (`str`) -- Password for basic authentication
1016 (optional)
1017 * **check-status** (`int`) -- Check for a specific HTTP status
1018 code (optional)
1019 * **check-etag** (`bool`) -- Check the HTTP ETag for changes
1020 (default false)
1021 * **check-date** (`bool`) -- Check the last modification date of
1022 the URL (default false)
1023 * **check-content** (`list`) -- List of content type changes to
1024 monitor
1025
1026 :Content Type: * **simple** (`bool`) -- Trigger on any change to
1027 the content of the URL (default false)
1028 * **json** (`list`) -- Trigger on any change to
1029 the listed JSON paths
1030 * **text** (`list`) -- Trigger on any change to
1031 the listed regular expressions
1032 * **xml** (`list`) -- Trigger on any change to
1033 the listed XPath expressions
1034
1035 Example:
1036
1037 .. literalinclude:: /../../tests/triggers/fixtures/pollurl001.yaml
1038 """
1039
1040 namespace = "org.jenkinsci.plugins.urltrigger."
1041 valid_content_types = {
1042 "simple": ["Simple", "", "", []],
1043 "json": ["JSON", "jsonPaths", "jsonPath", None],
1044 "text": ["TEXT", "regExElements", "regEx", None],
1045 "xml": ["XML", "xPaths", "xPath", None],
1046 }
1047 urltrig = XML.SubElement(xml_parent, namespace + "URLTrigger")
1048 node = data.get("polling-node")
1049 XML.SubElement(urltrig, "spec").text = data.get("cron", "")
1050 XML.SubElement(urltrig, "labelRestriction").text = str(bool(node)).lower()
1051 if node:
1052 XML.SubElement(urltrig, "triggerLabel").text = node
1053 entries = XML.SubElement(urltrig, "entries")
1054 urls = data.get("urls", [])
1055 if not urls:
1056 raise JenkinsJobsException("At least one url must be provided")
1057 mapping = [
1058 ("proxy", "proxyActivated", False),
1059 ("timeout", "timeout", 300),
1060 ("check-etag", "checkETag", False),
1061 ("check-date", "checkLastModificationDate", False),
1062 ]
1063 for url in urls:
1064 entry = XML.SubElement(entries, namespace + "URLTriggerEntry")
1065 XML.SubElement(entry, "url").text = url["url"]
1066 if "username" in url:
1067 XML.SubElement(entry, "username").text = url["username"]
1068 if "password" in url:
1069 XML.SubElement(entry, "password").text = url["password"]
1070 if "check-status" in url:
1071 XML.SubElement(entry, "checkStatus").text = "true"
1072 mapping.append(("check-status", "statusCode", ""))
1073 else:
1074 XML.SubElement(entry, "checkStatus").text = "false"
1075 XML.SubElement(entry, "statusCode").text = "200"
1076
1077 helpers.convert_mapping_to_xml(entry, url, mapping, fail_required=False)
1078 check_content = url.get("check-content", [])
1079 XML.SubElement(entry, "inspectingContent").text = str(
1080 bool(check_content)
1081 ).lower()
1082 content_types = XML.SubElement(entry, "contentTypes")
1083 for entry in check_content:
1084 type_name = next(iter(entry.keys()))
1085 if type_name not in valid_content_types:
1086 raise JenkinsJobsException(
1087 "check-content must be one of : %s"
1088 % ", ".join(valid_content_types.keys())
1089 )
1090
1091 content_type = valid_content_types.get(type_name)
1092 if entry[type_name]:
1093 sub_entries = content_type[3]
1094 if sub_entries is None:
1095 sub_entries = entry[type_name]
1096 build_content_type(
1097 content_types,
1098 sub_entries,
1099 namespace + "content",
1100 "ContentType",
1101 "ContentEntry",
1102 *content_type[0:3]
1103 )
1104
1105
1106 def jms_messaging(registry, xml_parent, data):
1107 """yaml: jms-messaging
1108 The JMS Messaging Plugin provides the following functionality:
1109 - A build trigger to submit jenkins jobs upon receipt
1110 of a matching message.
1111 - A builder that may be used to submit a message to the topic
1112 upon the completion of a job
1113 - A post-build action that may be used to submit a message to the topic
1114 upon the completion of a job
1115
1116 JMS Messaging provider types supported:
1117 - ActiveMQ
1118 - FedMsg
1119
1120 Requires the Jenkins :jenkins-plugins:`JMS Messaging Plugin
1121 <jms-messaging>`.
1122
1123 :arg bool no-squash: true = schedule a new job for every triggering message.
1124 (default false)
1125 Normally if a job is queued and another triggering message is received, a new job
1126 is not submitted and the job is "squashed" into the job already queued.
1127 Setting this option to 'True' forces a new job to be submitted for every triggering
1128 message that is received.
1129 :arg str override-topic: If you need to override the default topic.
1130 (default '')
1131 :arg str selector: The JSON or YAML formatted text that conforms to
1132 the schema for defining the various OpenShift resources. (default '')
1133 note: topic needs to be in double quotes
1134 ex. topic = "org.fedoraproject.prod.fedimg.image.upload"
1135 :arg str provider-name: Name of message provider setup in the
1136 global config. (default '')
1137 :arg list checks: List of checks to monitor. (default [])
1138 :arg str field: Check the body of messages for a field. (default '')
1139 :arg str expected-value: Expected value for the field. regex (default '')
1140
1141
1142 Full Example:
1143
1144 .. literalinclude::
1145 ../../tests/triggers/fixtures/jms-messaging001.yaml
1146 :language: yaml
1147
1148 Minimal Example:
1149
1150 .. literalinclude::
1151 ../../tests/triggers/fixtures/jms-messaging002.yaml
1152 :language: yaml
1153 """
1154 namespace = "com.redhat.jenkins.plugins.ci."
1155 jmsm = XML.SubElement(xml_parent, namespace + "CIBuildTrigger")
1156
1157 if "override-topic" in data:
1158 overrides = XML.SubElement(jmsm, "overrides")
1159 XML.SubElement(overrides, "topic").text = str(data["override-topic"])
1160
1161 mapping = [
1162 # option, xml name, default value
1163 ("spec", "spec", ""),
1164 ("no-squash", "noSquash", False),
1165 ("selector", "selector", ""),
1166 ("provider-name", "providerName", ""),
1167 ]
1168 helpers.convert_mapping_to_xml(jmsm, data, mapping, fail_required=True)
1169
1170 checks = data.get("checks", [])
1171 if len(checks) > 0:
1172 msgchecks = XML.SubElement(jmsm, "checks")
1173 for check in checks:
1174 msgcheck = XML.SubElement(
1175 msgchecks, namespace + "messaging.checks.MsgCheck"
1176 )
1177 mapping = [("field", "field", ""), ("expected-value", "expectedValue", "")]
1178 helpers.convert_mapping_to_xml(msgcheck, check, mapping, fail_required=True)
1179
1180
1181 def timed(registry, xml_parent, data):
1182 """yaml: timed
1183 Trigger builds at certain times.
1184
1185 :Parameter: when to run the job (cron syntax)
1186
1187 Example::
1188
1189 triggers:
1190 - timed: "@midnight"
1191 """
1192 scmtrig = XML.SubElement(xml_parent, "hudson.triggers.TimerTrigger")
1193 XML.SubElement(scmtrig, "spec").text = data
1194
1195
1196 def bitbucket(registry, xml_parent, data):
1197 """yaml: bitbucket
1198 Trigger a job when bitbucket repository is pushed to.
1199
1200 Requires the Jenkins :jenkins-plugins:`BitBucket Plugin
1201 <bitbucket>`.
1202
1203 Example:
1204
1205 .. literalinclude:: /../../tests/triggers/fixtures/bitbucket.yaml
1206 """
1207 bbtrig = XML.SubElement(
1208 xml_parent, "com.cloudbees.jenkins." "plugins.BitBucketTrigger"
1209 )
1210 XML.SubElement(bbtrig, "spec").text = ""
1211
1212
1213 def github(registry, xml_parent, data):
1214 """yaml: github
1215 Trigger a job when github repository is pushed to.
1216
1217 Requires the Jenkins :jenkins-plugins:`GitHub Plugin <github>`.
1218
1219 Example::
1220
1221 triggers:
1222 - github
1223 """
1224 ghtrig = XML.SubElement(xml_parent, "com.cloudbees.jenkins." "GitHubPushTrigger")
1225 XML.SubElement(ghtrig, "spec").text = ""
1226
1227
1228 def github_pull_request(registry, xml_parent, data):
1229 """yaml: github-pull-request
1230 Build pull requests in github and report results.
1231
1232 Requires the Jenkins :jenkins-plugins:`GitHub Pull Request Builder Plugin
1233 <ghprb>`.
1234
1235 :arg list admin-list: the users with admin rights (optional)
1236 :arg list white-list: users whose pull requests build (optional)
1237 :arg list org-list: orgs whose users should be white listed (optional)
1238 :arg bool allow-whitelist-orgs-as-admins: members of white listed orgs
1239 will have admin rights. (default false)
1240 :arg str cron: cron syntax of when to run (optional)
1241 :arg str trigger-phrase: when filled, commenting this phrase
1242 in the pull request will trigger a build (optional)
1243 :arg bool only-trigger-phrase: only commenting the trigger phrase
1244 in the pull request will trigger a build (default false)
1245 :arg str skip-build-phrase: when filled, adding this phrase to
1246 the pull request title or body will not trigger a build (optional)
1247 :arg list black-list-commit-author: When filled, pull request commits from this user(s)
1248 will not trigger a build (optional)
1249 :arg str black-list-labels: list of GitHub labels for which the build
1250 should not be triggered (optional)
1251 :arg str white-list-labels: list of GitHub labels for which the build
1252 should only be triggered. (Leave blank for 'any') (optional)
1253 :arg bool github-hooks: use github hook (default false)
1254 :arg bool permit-all: build every pull request automatically
1255 without asking (default false)
1256 :arg bool auto-close-on-fail: close failed pull request automatically
1257 (default false)
1258 :arg bool display-build-errors-on-downstream-builds: Display build errors on downstream builds
1259 (default false)
1260 :arg list white-list-target-branches: Adding branches to this whitelist
1261 allows you to selectively test pull requests destined for these
1262 branches only. Supports regular expressions (e.g. 'master',
1263 'feature-.*'). (optional)
1264 :arg list black-list-target-branches: Adding branches to this blacklist
1265 allows you to selectively prevent pull requests builds destined for
1266 these branches. Supports regular expressions (e.g. 'master',
1267 'feature-.*'). (optional)
1268 :arg str auth-id: the auth id to use (optional)
1269 :arg str build-desc-template: the template for build descriptions in
1270 jenkins (optional)
1271 :arg str status-context: the context to include on PR status comments
1272 (optional)
1273 :arg str triggered-status: the status message to set when the build has
1274 been triggered (optional)
1275 :arg str started-status: the status comment to set when the build has
1276 been started (optional)
1277 :arg str status-url: the status URL to set (optional)
1278 :arg bool status-add-test-results: add test result one-liner to status
1279 message (optional)
1280 :arg str success-status: the status message to set if the job succeeds
1281 (optional)
1282 :arg str failure-status: the status message to set if the job fails
1283 (optional)
1284 :arg str error-status: the status message to set if the job errors
1285 (optional)
1286 :arg str success-comment: comment to add to the PR on a successful job
1287 (optional)
1288 :arg str failure-comment: comment to add to the PR on a failed job
1289 (optional)
1290 :arg str error-comment: comment to add to the PR on an errored job
1291 (optional)
1292 :arg bool cancel-builds-on-update: cancel existing builds when a PR is
1293 updated (optional)
1294 :arg str comment-file: Extends the standard build comment message on
1295 github with a custom message file. (optional)
1296 :arg bool no-commit-status: Enables "Do not update commit status"
1297 :arg list included-regions: Each inclusion uses regular expression pattern
1298 matching, and must be separated by a new line. An empty list implies
1299 that everything is included. (optional)
1300 :arg list excluded-regions: Each exclusion uses regular expression pattern
1301 matching, and must be separated by a new line. Exclusions take
1302 precedence over inclusions, if there is an overlap between included
1303 and excluded regions. (optional)
1304
1305 Full Example:
1306
1307 .. literalinclude::
1308 /../../tests/triggers/fixtures/github-pull-request-full.yaml
1309 :language: yaml
1310
1311 Minimal Example:
1312
1313 .. literalinclude::
1314 /../../tests/triggers/fixtures/github-pull-request-minimal.yaml
1315 :language: yaml
1316 """
1317 ghprb = XML.SubElement(xml_parent, "org.jenkinsci.plugins.ghprb." "GhprbTrigger")
1318 mapping = [
1319 (
1320 "allow-whitelist-orgs-as-admins",
1321 "allowMembersOfWhitelistedOrgsAsAdmin",
1322 False,
1323 ),
1324 ("trigger-phrase", "triggerPhrase", ""),
1325 ("skip-build-phrase", "skipBuildPhrase", ""),
1326 ("only-trigger-phrase", "onlyTriggerPhrase", False),
1327 ("github-hooks", "useGitHubHooks", False),
1328 ("permit-all", "permitAll", False),
1329 ("auto-close-on-fail", "autoCloseFailedPullRequests", False),
1330 (
1331 "display-build-errors-on-downstream-builds",
1332 "displayBuildErrorsOnDownstreamBuilds",
1333 False,
1334 ),
1335 ]
1336 XML.SubElement(ghprb, "configVersion").text = "3"
1337 cron_string = data.get("cron", "") or ""
1338 XML.SubElement(ghprb, "spec").text = cron_string
1339 XML.SubElement(ghprb, "cron").text = cron_string
1340 admin_string = "\n".join(data.get("admin-list", []))
1341 XML.SubElement(ghprb, "adminlist").text = admin_string
1342 white_string = "\n".join(data.get("white-list", []))
1343 XML.SubElement(ghprb, "whitelist").text = white_string
1344 org_string = "\n".join(data.get("org-list", []))
1345 XML.SubElement(ghprb, "orgslist").text = org_string
1346 black_list_commit_author_string = " ".join(data.get("black-list-commit-author", ""))
1347 XML.SubElement(
1348 ghprb, "blackListCommitAuthor"
1349 ).text = black_list_commit_author_string
1350 white_list_labels_string = "\n".join(data.get("white-list-labels", []))
1351 XML.SubElement(ghprb, "whiteListLabels").text = white_list_labels_string
1352 black_list_labels_string = "\n".join(data.get("black-list-labels", []))
1353 XML.SubElement(ghprb, "blackListLabels").text = black_list_labels_string
1354 excluded_regions_string = "\n".join(data.get("excluded-regions", []))
1355 XML.SubElement(ghprb, "excludedRegions").text = excluded_regions_string
1356 included_regions_string = "\n".join(data.get("included-regions", []))
1357 XML.SubElement(ghprb, "includedRegions").text = included_regions_string
1358
1359 build_desc_template = data.get("build-desc-template", "")
1360 if build_desc_template:
1361 XML.SubElement(ghprb, "buildDescTemplate").text = str(build_desc_template)
1362 else:
1363 XML.SubElement(ghprb, "buildDescTemplate")
1364
1365 helpers.convert_mapping_to_xml(ghprb, data, mapping, fail_required=False)
1366 white_list_target_branches = data.get("white-list-target-branches", [])
1367 ghprb_wltb = XML.SubElement(ghprb, "whiteListTargetBranches")
1368 if white_list_target_branches:
1369 for branch in white_list_target_branches:
1370 be = XML.SubElement(
1371 ghprb_wltb, "org.jenkinsci.plugins." "ghprb.GhprbBranch"
1372 )
1373 XML.SubElement(be, "branch").text = str(branch)
1374
1375 black_list_target_branches = data.get("black-list-target-branches", [])
1376 ghprb_bltb = XML.SubElement(ghprb, "blackListTargetBranches")
1377 if black_list_target_branches:
1378 for branch in black_list_target_branches:
1379 be = XML.SubElement(
1380 ghprb_bltb, "org.jenkinsci.plugins." "ghprb.GhprbBranch"
1381 )
1382 XML.SubElement(be, "branch").text = str(branch)
1383
1384 auth_id = data.get("auth-id", "")
1385 if auth_id:
1386 XML.SubElement(ghprb, "gitHubAuthId").text = str(auth_id)
1387
1388 # PR status update fields
1389 status_context = data.get("status-context", "")
1390 triggered_status = data.get("triggered-status", "")
1391 started_status = data.get("started-status", "")
1392 status_url = data.get("status-url", "")
1393 status_add_test_results = data.get("status-add-test-results", False)
1394 success_status = data.get("success-status", "")
1395 failure_status = data.get("failure-status", "")
1396 error_status = data.get("error-status", "")
1397
1398 # is status handling is required?
1399 requires_status = (
1400 status_context
1401 or triggered_status
1402 or started_status
1403 or status_url
1404 or status_add_test_results
1405 or success_status
1406 or failure_status
1407 or error_status
1408 )
1409
1410 # is status message handling required?
1411 requires_status_message = success_status or failure_status or error_status
1412
1413 # is comment handling required?
1414 success_comment = data.get("success-comment", "")
1415 failure_comment = data.get("failure-comment", "")
1416 error_comment = data.get("error-comment", "")
1417 requires_job_comment = success_comment or failure_comment or error_comment
1418
1419 # When the value of cancel-builds-on-update comes from deep_formatter,
1420 # the value is of type 'str', otherwise the value is of type 'bool'
1421 cancel_builds_on_update = (
1422 str(data.get("cancel-builds-on-update", False)).lower() == "true"
1423 )
1424
1425 comment_file = data.get("comment-file", "")
1426 no_commit_status = data.get("no-commit-status", False)
1427
1428 # We want to have only one 'extensions' subelement, even if status
1429 # handling, comment handling and other extensions are enabled.
1430 if (
1431 requires_status
1432 or requires_job_comment
1433 or cancel_builds_on_update
1434 or comment_file
1435 or no_commit_status
1436 ):
1437 extensions = XML.SubElement(ghprb, "extensions")
1438
1439 # Both comment and status elements have this same type. Using a const is
1440 # much easier to read than repeating the tokens for this class each time
1441 # it's used
1442 comment_type = "org.jenkinsci.plugins.ghprb.extensions.comments."
1443 comment_type = comment_type + "GhprbBuildResultMessage"
1444
1445 if requires_status:
1446 simple_status = XML.SubElement(
1447 extensions,
1448 "org.jenkinsci.plugins" ".ghprb.extensions.status." "GhprbSimpleStatus",
1449 )
1450 commit_status_context_element = XML.SubElement(
1451 simple_status, "commitStatusContext"
1452 )
1453 triggered_status_element = XML.SubElement(simple_status, "triggeredStatus")
1454 started_status_element = XML.SubElement(simple_status, "startedStatus")
1455 status_url_element = XML.SubElement(simple_status, "statusUrl")
1456 if status_context:
1457 commit_status_context_element.text = str(status_context)
1458 if triggered_status:
1459 triggered_status_element.text = str(triggered_status)
1460 if started_status:
1461 started_status_element.text = str(started_status)
1462 if status_url:
1463 status_url_element.text = str(status_url)
1464
1465 XML.SubElement(simple_status, "addTestResults").text = str(
1466 status_add_test_results
1467 ).lower()
1468
1469 if requires_status_message:
1470 completed_elem = XML.SubElement(simple_status, "completedStatus")
1471 if success_status:
1472 success_elem = XML.SubElement(completed_elem, comment_type)
1473 XML.SubElement(success_elem, "message").text = str(success_status)
1474 XML.SubElement(success_elem, "result").text = "SUCCESS"
1475 if failure_status:
1476 failure_elem = XML.SubElement(completed_elem, comment_type)
1477 XML.SubElement(failure_elem, "message").text = str(failure_status)
1478 XML.SubElement(failure_elem, "result").text = "FAILURE"
1479 if error_status:
1480 error_elem = XML.SubElement(completed_elem, comment_type)
1481 XML.SubElement(error_elem, "message").text = str(error_status)
1482 XML.SubElement(error_elem, "result").text = "ERROR"
1483
1484 # job comment handling
1485 if requires_job_comment:
1486 build_status = XML.SubElement(
1487 extensions,
1488 "org.jenkinsci.plugins.ghprb.extensions" ".comments." "GhprbBuildStatus",
1489 )
1490 messages_elem = XML.SubElement(build_status, "messages")
1491 if success_comment:
1492 success_comment_elem = XML.SubElement(messages_elem, comment_type)
1493 XML.SubElement(success_comment_elem, "message").text = str(success_comment)
1494 XML.SubElement(success_comment_elem, "result").text = "SUCCESS"
1495 if failure_comment:
1496 failure_comment_elem = XML.SubElement(messages_elem, comment_type)
1497 XML.SubElement(failure_comment_elem, "message").text = str(failure_comment)
1498 XML.SubElement(failure_comment_elem, "result").text = "FAILURE"
1499 if error_comment:
1500 error_comment_elem = XML.SubElement(messages_elem, comment_type)
1501 XML.SubElement(error_comment_elem, "message").text = str(error_comment)
1502 XML.SubElement(error_comment_elem, "result").text = "ERROR"
1503
1504 if cancel_builds_on_update:
1505 XML.SubElement(
1506 extensions,
1507 "org.jenkinsci.plugins.ghprb.extensions." "build.GhprbCancelBuildsOnUpdate",
1508 )
1509
1510 if comment_file:
1511 comment_file_tag = XML.SubElement(
1512 extensions,
1513 "org.jenkinsci.plugins.ghprb.extensions." "comments.GhprbCommentFile",
1514 )
1515 comment_file_path_elem = XML.SubElement(comment_file_tag, "commentFilePath")
1516 comment_file_path_elem.text = str(comment_file)
1517
1518 if no_commit_status:
1519 XML.SubElement(
1520 extensions,
1521 "org.jenkinsci.plugins.ghprb.extensions." "status.GhprbNoCommitStatus",
1522 )
1523
1524
1525 def gitlab_merge_request(registry, xml_parent, data):
1526 """yaml: gitlab-merge-request
1527 Build merge requests in gitlab and report results.
1528
1529 Requires the Jenkins :jenkins-plugins:`Gitlab MergeRequest Builder Plugin
1530 <ghprb>`.
1531
1532 :arg str cron: Cron syntax of when to run (required)
1533 :arg str project-path: Gitlab-relative path to project (required)
1534 :arg str target-branch-regex: Allow execution of this job for certain
1535 branches only (default ''). Requires Gitlab MergeRequest Builder
1536 Plugin >= 2.0.0
1537 :arg str use-http-url: Use the HTTP(S) URL to fetch/clone repository
1538 (default false)
1539 :arg str assignee-filter: Only MRs with this assigned user will
1540 trigger the build automatically (default 'jenkins')
1541 :arg str tag-filter: Only MRs with this label will trigger the build
1542 automatically (default 'Build')
1543 :arg str trigger-comment: Force build if this comment is the last
1544 in merge reguest (default '')
1545 :arg str publish-build-progress-messages: Publish build progress
1546 messages (except build failed) (default true)
1547
1548 .. deprecated:: 2.0.0
1549
1550 :arg str auto-close-failed: On failure, auto close the request
1551 (default false)
1552 :arg str auto-merge-passed: On success, auto merge the request
1553 (default false)
1554
1555 Example (version < 2.0.0):
1556
1557 .. literalinclude:: \
1558 /../../tests/triggers/fixtures/gitlab-merge-request001.yaml
1559
1560 Example (version >= 2.0.0):
1561
1562 .. literalinclude:: \
1563 /../../tests/triggers/fixtures/gitlab-merge-request002.yaml
1564 """
1565 ghprb = XML.SubElement(
1566 xml_parent, "org.jenkinsci.plugins.gitlab." "GitlabBuildTrigger"
1567 )
1568
1569 plugin_ver = registry.get_plugin_version("Gitlab Merge Request Builder")
1570
1571 if plugin_ver >= "2.0.0":
1572 mapping = [
1573 ("cron", "spec", None),
1574 ("project-path", "projectPath", None),
1575 ("target-branch-regex", "targetBranchRegex", ""),
1576 ("use-http-url", "useHttpUrl", False),
1577 ("assignee-filter", "assigneeFilter", "jenkins"),
1578 ("tag-filter", "tagFilter", "Build"),
1579 ("trigger-comment", "triggerComment", ""),
1580 ("auto-close-failed", "autoCloseFailed", False),
1581 ("auto-merge-passed", "autoMergePassed", False),
1582 ]
1583 else:
1584 # The plugin version is < 2.0.0
1585
1586 # Because of a design limitation in the GitlabBuildTrigger Jenkins
1587 # plugin both 'spec' and '__cron' have to be set to the same value to
1588 # have them take effect. Also, cron and projectPath are prefixed with
1589 # underscores in the plugin, but spec is not.
1590 mapping = [
1591 ("cron", "spec", None),
1592 ("cron", "__cron", None),
1593 ("project-path", "__projectPath", None),
1594 ("use-http-url", "__useHttpUrl", False),
1595 ("assignee-filter", "__assigneeFilter", "jenkins"),
1596 ("tag-filter", "__tagFilter", "Build"),
1597 ("trigger-comment", "__triggerComment", ""),
1598 ("publish-build-progress-messages", "__publishBuildProgressMessages", True),
1599 ("auto-close-failed", "__autoCloseFailed", False),
1600 ("auto-merge-passed", "__autoMergePassed", False),
1601 ]
1602
1603 helpers.convert_mapping_to_xml(ghprb, data, mapping, True)
1604
1605
1606 def gitlab(registry, xml_parent, data):
1607 """yaml: gitlab
1608 Makes Jenkins act like a GitLab CI server.
1609
1610 Requires the Jenkins :jenkins-plugins:`GitLab Plugin <gitlab-plugin>`.
1611
1612 :arg bool trigger-push: Build on Push Events (default true)
1613 :arg bool trigger-merge-request: Build on Merge Request Events (default
1614 true)
1615 :arg bool trigger-accepted-merge-request: Build on Accepted Merge Request
1616 Events (>= 1.4.6) (default false)
1617 :arg bool trigger-closed-merge-request: Build on Closed Merge Request
1618 Events (>= 1.4.6) (default false)
1619 :arg str trigger-open-merge-request-push: Rebuild open Merge Requests
1620 on Push Events.
1621
1622 :trigger-open-merge-request-push values (< 1.1.26):
1623 * **true** (default)
1624 * **false**
1625 :trigger-open-merge-request-push values (>= 1.1.26):
1626 * **never** (default)
1627 * **source**
1628 * **both**
1629 :arg bool trigger-only-if-new-commits-pushed: Trigger a build on commits pushed
1630 only, but not trigger on another MR changes(label, edit, assign, etc)
1631 (>=1.5.17)(default false)
1632 :arg bool trigger-note: Build when comment is added with defined phrase
1633 (>= 1.2.4) (default true)
1634 :arg str note-regex: Phrase that triggers the build (>= 1.2.4) (default
1635 'Jenkins please retry a build')
1636 :arg bool ci-skip: Enable skipping builds of commits that contain
1637 [ci-skip] in the commit message (default true)
1638 :arg bool wip-skip: Enable skipping builds of WIP Merge Requests (>= 1.2.4)
1639 (default true)
1640 :arg bool set-build-description: Set build description to build cause
1641 (eg. Merge request or Git Push) (default true)
1642 :arg bool cancel-pending-builds-on-update: Cancel pending merge request
1643 builds on update (default false)
1644 :arg str pending-build-name: Set the pending merge request build name (optional)
1645 :arg bool add-note-merge-request: Add note with build status on
1646 merge requests (default true)
1647 :arg bool add-vote-merge-request: Vote added to note with build status
1648 on merge requests (>= 1.1.27) (default true)
1649 :arg bool accept-merge-request-on-success: Automatically accept the Merge
1650 Request if the build is successful (>= 1.1.27) (default false)
1651 :arg bool add-ci-message: Add CI build status (1.1.28 - 1.2.0) (default
1652 false)
1653 :arg bool allow-all-branches: Allow all branches (Ignoring Filtered
1654 Branches) (< 1.1.29) (default false)
1655 :arg str branch-filter-type: Filter branches that can trigger a build.
1656 Valid values and their additional attributes are described in the
1657 `branch filter type`_ table (>= 1.1.29) (default 'All').
1658 :arg list include-branches: Defined list of branches to include
1659 (default [])
1660 :arg list exclude-branches: Defined list of branches to exclude
1661 (default [])
1662 :arg str source-branch-regex: Regular expression to select branches
1663 :arg str target-branch-regex: Regular expression to select branches
1664 :arg str secret-token: Secret token for build trigger
1665 :arg str force-build-labels: Labels that launch a build if they are added
1666 (comma-separated)
1667 :arg dict merge-request-label-filter-config: If used allow merge requests
1668 filtering by labels
1669
1670 :Options: * **include** (`str`) Run for specified labels.
1671 * **exclude** (`str`) Do not run for specified labels.
1672
1673 .. _`branch filter type`:
1674
1675 ================== ====================================================
1676 Branch filter type Description
1677 ================== ====================================================
1678 All All branches are allowed to trigger this job.
1679 NameBasedFilter Filter branches by name.
1680 List source branches that are allowed to trigger a
1681 build from a Push event or a Merge Request event. If
1682 both fields are left empty, all branches are allowed
1683 to trigger this job. For Merge Request events only
1684 the target branch name is filtered out by the
1685 **include-branches** and **exclude-branches** lists.
1686
1687 RegexBasedFilter Filter branches by regex
1688 The target branch regex allows you to limit the
1689 execution of this job to certain branches. Any
1690 branch matching the specified pattern in
1691 **target-branch-regex** and **source-branch-regex** triggers the job. No
1692 filtering is performed if the field is left empty.
1693 ================== ====================================================
1694
1695 Example (version < 1.1.26):
1696
1697 .. literalinclude:: /../../tests/triggers/fixtures/gitlab001.yaml
1698 :language: yaml
1699
1700 Minimal example (version >= 1.1.26):
1701
1702 .. literalinclude:: /../../tests/triggers/fixtures/gitlab005.yaml
1703 :language: yaml
1704
1705 Full example (version >= 1.1.26):
1706
1707 .. literalinclude:: /../../tests/triggers/fixtures/gitlab004.yaml
1708 :language: yaml
1709 """
1710
1711 def _add_xml(elem, name, value):
1712 XML.SubElement(elem, name).text = value
1713
1714 gitlab = XML.SubElement(
1715 xml_parent, "com.dabsquared.gitlabjenkins.GitLabPushTrigger"
1716 )
1717
1718 plugin_ver = registry.get_plugin_version("GitLab Plugin")
1719
1720 valid_merge_request = ["never", "source", "both"]
1721
1722 if plugin_ver >= "1.1.26":
1723 mapping = [
1724 (
1725 "trigger-open-merge-request-push",
1726 "triggerOpenMergeRequestOnPush",
1727 "never",
1728 valid_merge_request,
1729 )
1730 ]
1731 helpers.convert_mapping_to_xml(gitlab, data, mapping, fail_required=True)
1732 else:
1733 mapping = [
1734 ("trigger-open-merge-request-push", "triggerOpenMergeRequestOnPush", True)
1735 ]
1736 helpers.convert_mapping_to_xml(gitlab, data, mapping, fail_required=True)
1737
1738 if plugin_ver < "1.2.0":
1739 if data.get("branch-filter-type", "") == "All":
1740 data["branch-filter-type"] = ""
1741 valid_filters = ["", "NameBasedFilter", "RegexBasedFilter"]
1742 mapping = [("branch-filter-type", "branchFilterName", "", valid_filters)]
1743 helpers.convert_mapping_to_xml(gitlab, data, mapping, fail_required=True)
1744 else:
1745 valid_filters = ["All", "NameBasedFilter", "RegexBasedFilter"]
1746 mapping = [("branch-filter-type", "branchFilterType", "All", valid_filters)]
1747 helpers.convert_mapping_to_xml(gitlab, data, mapping, fail_required=True)
1748
1749 XML.SubElement(gitlab, "spec").text = ""
1750 mapping = [
1751 ("trigger-push", "triggerOnPush", True),
1752 ("trigger-merge-request", "triggerOnMergeRequest", True),
1753 ("trigger-only-if-new-commits-pushed", "triggerOnlyIfNewCommitsPushed", False),
1754 ("trigger-accepted-merge-request", "triggerOnAcceptedMergeRequest", False),
1755 ("trigger-closed-merge-request", "triggerOnClosedMergeRequest", False),
1756 ("trigger-note", "triggerOnNoteRequest", True),
1757 ("note-regex", "noteRegex", "Jenkins please retry a build"),
1758 ("ci-skip", "ciSkip", True),
1759 ("wip-skip", "skipWorkInProgressMergeRequest", True),
1760 ("set-build-description", "setBuildDescription", True),
1761 ("cancel-pending-builds-on-update", "cancelPendingBuildsOnUpdate", False),
1762 ("add-note-merge-request", "addNoteOnMergeRequest", True),
1763 ("add-vote-merge-request", "addVoteOnMergeRequest", True),
1764 ("accept-merge-request-on-success", "acceptMergeRequestOnSuccess", False),
1765 ("add-ci-message", "addCiMessage", False),
1766 ("allow-all-branches", "allowAllBranches", False),
1767 ("source-branch-regex", "sourceBranchRegex", ""),
1768 ("target-branch-regex", "targetBranchRegex", ""),
1769 ("secret-token", "secretToken", ""),
1770 ("force-build-labels", "labelsThatForcesBuildIfAdded", ""),
1771 ]
1772 helpers.convert_mapping_to_xml(gitlab, data, mapping, fail_required=True)
1773
1774 list_mapping = (
1775 ("include-branches", "includeBranchesSpec", []),
1776 ("exclude-branches", "excludeBranchesSpec", []),
1777 )
1778 for yaml_name, xml_name, default_val in list_mapping:
1779 value = ", ".join(data.get(yaml_name, default_val))
1780 _add_xml(gitlab, xml_name, value)
1781
1782 optional_mapping = (("pending-build-name", "pendingBuildName", None),)
1783 helpers.convert_mapping_to_xml(gitlab, data, optional_mapping, fail_required=False)
1784
1785 if data.get("merge-request-label-filter-config"):
1786 merge_request_filter = XML.SubElement(gitlab, "mergeRequestLabelFilterConfig")
1787 merge_mapping = [
1788 ("include", "include", ""),
1789 ("exclude", "exclude", ""),
1790 ]
1791 helpers.convert_mapping_to_xml(
1792 merge_request_filter,
1793 data.get("merge-request-label-filter-config", ""),
1794 merge_mapping,
1795 fail_required=False,
1796 )
1797
1798
1799 def gogs(registry, xml_parent, data):
1800 """yaml: gogs
1801 Trigger a job when gogs repository is pushed to.
1802
1803 Requires the Jenkins :jenkins-plugins:`Gogs Plugin <gogs-webhook>`.
1804
1805 Example:
1806
1807 .. literalinclude::
1808 /../../tests/triggers/fixtures/gogs.yaml
1809 :language: yaml
1810 """
1811 gogstrig = XML.SubElement(xml_parent, "org.jenkinsci.plugins.gogs.GogsTrigger")
1812 XML.SubElement(gogstrig, "spec")
1813
1814
1815 def build_result(registry, xml_parent, data):
1816 """yaml: build-result
1817 Configure jobB to monitor jobA build result. A build is scheduled if there
1818 is a new build result that matches your criteria (unstable, failure, ...).
1819
1820 Requires the Jenkins :jenkins-plugins:`BuildResultTrigger Plugin
1821 <buildresult-trigger>`.
1822
1823 :arg list groups: List groups of jobs and results to monitor for
1824 :arg list jobs: The jobs to monitor (required)
1825 :arg list results: Build results to monitor for (default success)
1826 :arg bool combine: Combine all job information. A build will be
1827 scheduled only if all conditions are met (default false)
1828 :arg str cron: The cron syntax with which to poll the jobs for the
1829 supplied result (default '')
1830
1831 Full Example:
1832
1833 .. literalinclude::
1834 /../../tests/triggers/fixtures/build-result-full.yaml
1835 :language: yaml
1836
1837 Minimal Example:
1838
1839 .. literalinclude::
1840 /../../tests/triggers/fixtures/build-result-minimal.yaml
1841 :language: yaml
1842 """
1843 brt = XML.SubElement(
1844 xml_parent, "org.jenkinsci.plugins." "buildresulttrigger.BuildResultTrigger"
1845 )
1846 brt.set("plugin", "buildresult-trigger")
1847 mapping = [("cron", "spec", ""), ("combine", "combinedJobs", False)]
1848 helpers.convert_mapping_to_xml(brt, data, mapping, fail_required=True)
1849 jobs_info = XML.SubElement(brt, "jobsInfo")
1850 result_dict = {
1851 "success": "SUCCESS",
1852 "unstable": "UNSTABLE",
1853 "failure": "FAILURE",
1854 "not-built": "NOT_BUILT",
1855 "aborted": "ABORTED",
1856 }
1857 for group in data["groups"]:
1858 brti = XML.SubElement(
1859 jobs_info,
1860 "org.jenkinsci.plugins."
1861 "buildresulttrigger.model."
1862 "BuildResultTriggerInfo",
1863 )
1864 jobs_string = ",".join(group["jobs"])
1865 mapping = [("", "jobNames", jobs_string)]
1866 helpers.convert_mapping_to_xml(brti, group, mapping, fail_required=True)
1867 checked_results = XML.SubElement(brti, "checkedResults")
1868 for result in group.get("results", ["success"]):
1869 model_checked = XML.SubElement(
1870 checked_results,
1871 "org.jenkinsci." "plugins.buildresulttrigger.model." "CheckedResult",
1872 )
1873 mapping = [("", "checked", result, result_dict)]
1874 helpers.convert_mapping_to_xml(
1875 model_checked, result_dict, mapping, fail_required=True
1876 )
1877
1878
1879 def reverse(registry, xml_parent, data):
1880 """yaml: reverse
1881 This trigger can be configured in the UI using the checkbox with the
1882 following text: 'Build after other projects are built'.
1883
1884 Set up a trigger so that when some other projects finish building, a new
1885 build is scheduled for this project. This is convenient for running an
1886 extensive test after a build is complete, for example.
1887
1888 This configuration complements the "Build other projects" section in the
1889 "Post-build Actions" of an upstream project, but is preferable when you
1890 want to configure the downstream project.
1891
1892 :arg str jobs: List of jobs to watch. Can be either a comma separated
1893 list or a list.
1894 :arg str result: Build results to monitor for between the following
1895 options: success, unstable and failure. (default 'success').
1896
1897 Example:
1898
1899 .. literalinclude:: /../../tests/triggers/fixtures/reverse.yaml
1900
1901 Example List:
1902
1903 .. literalinclude:: /../../tests/triggers/fixtures/reverse-list.yaml
1904 """
1905 reserveBuildTrigger = XML.SubElement(
1906 xml_parent, "jenkins.triggers.ReverseBuildTrigger"
1907 )
1908
1909 supported_thresholds = ["SUCCESS", "UNSTABLE", "FAILURE"]
1910
1911 XML.SubElement(reserveBuildTrigger, "spec").text = ""
1912
1913 jobs = data.get("jobs")
1914 if isinstance(jobs, list):
1915 jobs = ",".join(jobs)
1916 XML.SubElement(reserveBuildTrigger, "upstreamProjects").text = jobs
1917
1918 threshold = XML.SubElement(reserveBuildTrigger, "threshold")
1919 result = str(data.get("result", "success")).upper()
1920 if result not in supported_thresholds:
1921 raise jenkins_jobs.errors.JenkinsJobsException(
1922 "Choice should be one of the following options: %s."
1923 % ", ".join(supported_thresholds)
1924 )
1925 XML.SubElement(threshold, "name").text = hudson_model.THRESHOLDS[result]["name"]
1926 XML.SubElement(threshold, "ordinal").text = hudson_model.THRESHOLDS[result][
1927 "ordinal"
1928 ]
1929 XML.SubElement(threshold, "color").text = hudson_model.THRESHOLDS[result]["color"]
1930 XML.SubElement(threshold, "completeBuild").text = str(
1931 hudson_model.THRESHOLDS[result]["complete"]
1932 ).lower()
1933
1934
1935 def monitor_folders(registry, xml_parent, data):
1936 """yaml: monitor-folders
1937 Configure Jenkins to monitor folders.
1938
1939 Requires the Jenkins :jenkins-plugins:`Filesystem Trigger Plugin
1940 <fstrigger>`.
1941
1942 :arg str path: Folder path to poll. (default '')
1943 :arg list includes: Fileset includes setting that specifies the list of
1944 includes files. Basedir of the fileset is relative to the workspace
1945 root. If no value is set, all files are used. (default '')
1946 :arg str excludes: The 'excludes' pattern. A file that matches this mask
1947 will not be polled even if it matches the mask specified in 'includes'
1948 section. (default '')
1949 :arg bool check-modification-date: Check last modification date.
1950 (default true)
1951 :arg bool check-content: Check content. (default true)
1952 :arg bool check-fewer: Check fewer files (default true)
1953 :arg str cron: cron syntax of when to run (default '')
1954
1955 Full Example:
1956
1957 .. literalinclude::
1958 /../../tests/triggers/fixtures/monitor-folders-full.yaml
1959 :language: yaml
1960
1961 Minimal Example:
1962
1963 .. literalinclude::
1964 /../../tests/triggers/fixtures/monitor-folders-minimal.yaml
1965 :language: yaml
1966 """
1967 ft = XML.SubElement(
1968 xml_parent, ("org.jenkinsci.plugins.fstrigger." "triggers.FolderContentTrigger")
1969 )
1970 ft.set("plugin", "fstrigger")
1971
1972 mappings = [("path", "path", ""), ("cron", "spec", "")]
1973 helpers.convert_mapping_to_xml(ft, data, mappings, fail_required=True)
1974
1975 includes = data.get("includes", "")
1976 XML.SubElement(ft, "includes").text = ",".join(includes)
1977 XML.SubElement(ft, "excludes").text = data.get("excludes", "")
1978 XML.SubElement(ft, "excludeCheckLastModificationDate").text = str(
1979 not data.get("check-modification-date", True)
1980 ).lower()
1981 XML.SubElement(ft, "excludeCheckContent").text = str(
1982 not data.get("check-content", True)
1983 ).lower()
1984 XML.SubElement(ft, "excludeCheckFewerOrMoreFiles").text = str(
1985 not data.get("check-fewer", True)
1986 ).lower()
1987
1988
1989 def monitor_files(registry, xml_parent, data):
1990 """yaml: monitor-files
1991 Configure Jenkins to monitor files.
1992 Requires the Jenkins :jenkins-plugins:`Filesystem Trigger Plugin
1993 <fstrigger>`.
1994
1995 :arg list files: List of files to monitor
1996
1997 :File:
1998 * **path** (`str`) -- File path to monitor. You can use a pattern
1999 that specifies a set of files if you don't know the real file
2000 path. (required)
2001 * **strategy** (`str`) -- Choose your strategy if there is more
2002 than one matching file. Can be one of Ignore file ('IGNORE') or
2003 Use the most recent ('LATEST'). (default 'LATEST')
2004 * **check-content** (`list`) -- List of content changes of the
2005 file to monitor
2006
2007 :Content Nature:
2008 * **simple** (`bool`) -- Trigger on change in content of
2009 the specified file (whatever the type file).
2010 (default false)
2011 * **jar** (`bool`) -- Trigger on change in content of the
2012 specified JAR file. (default false)
2013 * **tar** (`bool`) -- Trigger on change in content of the
2014 specified Tar file. (default false)
2015 * **zip** (`bool`) -- Trigger on change in content of the
2016 specified ZIP file. (default false)
2017 * **source-manifest** (`list`) -- Trigger on change to
2018 MANIFEST files.
2019
2020 :MANIFEST File:
2021 * **keys** (`list`) -- List of keys to inspect.
2022 (optional)
2023 * **all-keys** (`bool`) -- If true, take into
2024 account all keys. (default true)
2025
2026 * **jar-manifest** (`list`) -- Trigger on change to
2027 MANIFEST files (contained in jar files).
2028
2029 :MANIFEST File:
2030 * **keys** (`list`) -- List of keys to inspect.
2031 (optional)
2032 * **all-keys** (`bool`) -- If true, take into
2033 account all keys. (default true)
2034
2035 * **properties** (`list`) -- Monitor the contents of the
2036 properties file.
2037
2038 :Properties File:
2039 * **keys** (`list`) -- List of keys to inspect.
2040 (optional)
2041 * **all-keys** (`bool`) -- If true, take into
2042 account all keys. (default true)
2043
2044 * **xml** (`list str`) -- Trigger on change to the listed
2045 XPath expressions.
2046 * **text** (`list str`) -- Trigger on change to the listed
2047 regular expressions.
2048
2049 * **ignore-modificaton-date** (`bool`) -- If true, ignore the file
2050 modification date. Only valid when content changes of the file
2051 are being monitored. (default true)
2052 :arg str cron: cron syntax of when to run (default '')
2053
2054 Minimal Example:
2055
2056 .. literalinclude::
2057 /../../tests/triggers/fixtures/monitor-files-minimal.yaml
2058 :language: yaml
2059
2060 Full Example:
2061
2062 .. literalinclude::
2063 /../../tests/triggers/fixtures/monitor-files-full.yaml
2064 :language: yaml
2065 """
2066 ft_prefix = "org.jenkinsci.plugins.fstrigger.triggers."
2067 valid_strategies = ["LATEST", "IGNORE"]
2068 valid_content_types = {
2069 "simple": ["Simple", "", "", []],
2070 "jar": ["JAR", "", "", []],
2071 "tar": ["Tar", "", "", []],
2072 "zip": ["ZIP", "", "", []],
2073 "source-manifest": ["SourceManifest"],
2074 "jar-manifest": ["JARManifest"],
2075 "properties": ["Properties"],
2076 "xml": ["XML", "expressions", "expression", None],
2077 "text": ["Text", "regexElements", "regex", None],
2078 }
2079
2080 ft = XML.SubElement(xml_parent, ft_prefix + "FileNameTrigger")
2081 XML.SubElement(ft, "spec").text = str(data.get("cron", ""))
2082 files = data.get("files", [])
2083 if not files:
2084 raise JenkinsJobsException("At least one file must be provided")
2085
2086 files_tag = XML.SubElement(ft, "fileInfo")
2087 for file_info in files:
2088 file_tag = XML.SubElement(files_tag, ft_prefix + "FileNameTriggerInfo")
2089 check_content = file_info.get("check-content", [])
2090 files_mapping = [
2091 ("path", "filePathPattern", None),
2092 ("strategy", "strategy", "LATEST", valid_strategies),
2093 ("", "inspectingContentFile", bool(check_content)),
2094 ]
2095 helpers.convert_mapping_to_xml(
2096 file_tag, file_info, files_mapping, fail_required=True
2097 )
2098
2099 base_content_tag = XML.SubElement(file_tag, "contentFileTypes")
2100 for content in check_content:
2101 type_name = next(iter(content.keys()))
2102 if type_name not in valid_content_types:
2103 raise InvalidAttributeError(
2104 "check-content", type_name, valid_content_types.keys()
2105 )
2106 content_type = valid_content_types.get(type_name)
2107 if len(content_type) == 1:
2108 class_name = "{0}filecontent.{1}FileContent".format(
2109 ft_prefix, content_type[0]
2110 )
2111 content_data = content.get(type_name)
2112 if not content_data:
2113 raise JenkinsJobsException(
2114 "Need to specify something " "under " + type_name
2115 )
2116 for entry in content_data:
2117 content_tag = XML.SubElement(base_content_tag, class_name)
2118 keys = entry.get("keys", [])
2119 if keys:
2120 XML.SubElement(content_tag, "keys2Inspect").text = ",".join(
2121 keys
2122 )
2123 XML.SubElement(content_tag, "allKeys").text = str(
2124 entry.get("all-keys", True)
2125 ).lower()
2126 else:
2127 if content[type_name]:
2128 sub_entries = content_type[3]
2129 if sub_entries is None:
2130 sub_entries = content[type_name]
2131 build_content_type(
2132 base_content_tag,
2133 sub_entries,
2134 ft_prefix + "filecontent",
2135 "FileContent",
2136 "FileContentEntry",
2137 *content_type[0:3]
2138 )
2139 if bool(check_content):
2140 XML.SubElement(file_tag, "doNotCheckLastModificationDate").text = str(
2141 file_info.get("ignore-modificaton-date", True)
2142 ).lower()
2143
2144
2145 def ivy(registry, xml_parent, data):
2146 """yaml: ivy
2147 Poll with an Ivy script.
2148
2149 Requires the Jenkins :jenkins-plugins:`IvyTrigger Plugin
2150 <ivytrigger>`.
2151
2152 :arg str path: Path of the ivy file. (optional)
2153 :arg str settings-path: Ivy Settings Path. (optional)
2154 :arg list properties-file: List of properties file path. Properties
2155 will be injected as variables in the ivy settings file. (optional)
2156 :arg str properties-content: Properties content. Properties will be
2157 injected as variables in the ivy settings file. (optional)
2158 :arg bool debug: Active debug mode on artifacts resolution. (default false)
2159 :arg download-artifacts: Download artifacts for dependencies to see if they
2160 have changed. (default true)
2161 :arg bool enable-concurrent: Enable Concurrent Build. (default false)
2162 :arg str label: Restrict where the polling should run. (default '')
2163 :arg str cron: cron syntax of when to run (default '')
2164
2165 Example:
2166
2167 .. literalinclude:: /../../tests/triggers/fixtures/ivy.yaml
2168 """
2169 it = XML.SubElement(xml_parent, "org.jenkinsci.plugins.ivytrigger.IvyTrigger")
2170 mapping = [
2171 ("path", "ivyPath", None),
2172 ("settings-path", "ivySettingsPath", None),
2173 ("properties-content", "propertiesContent", None),
2174 ("debug", "debug", False),
2175 ("download-artifacts", "downloadArtifacts", True),
2176 ("enable-concurrent", "enableConcurrentBuild", False),
2177 ("cron", "spec", ""),
2178 ]
2179 helpers.convert_mapping_to_xml(it, data, mapping, fail_required=False)
2180
2181 properties_file_path = data.get("properties-file", [])
2182 XML.SubElement(it, "propertiesFilePath").text = ";".join(properties_file_path)
2183
2184 label = data.get("label")
2185 XML.SubElement(it, "labelRestriction").text = str(bool(label)).lower()
2186 if label:
2187 XML.SubElement(it, "triggerLabel").text = label
2188
2189
2190 def script(registry, xml_parent, data):
2191 """yaml: script
2192 Triggers the job using shell or batch script.
2193
2194 Requires the Jenkins :jenkins-plugins:`ScriptTrigger Plugin <scripttrigger>`.
2195
2196 :arg str label: Restrict where the polling should run. (default '')
2197 :arg str script: A shell or batch script. (default '')
2198 :arg str script-file-path: A shell or batch script path. (default '')
2199 :arg str cron: cron syntax of when to run (default '')
2200 :arg bool enable-concurrent: Enables triggering concurrent builds.
2201 (default false)
2202 :arg int exit-code: If the exit code of the script execution returns this
2203 expected exit code, a build is scheduled. (default 0)
2204
2205 Full Example:
2206
2207 .. literalinclude:: /../../tests/triggers/fixtures/script-full.yaml
2208 :language: yaml
2209
2210 Minimal Example:
2211
2212 .. literalinclude:: /../../tests/triggers/fixtures/script-minimal.yaml
2213 :language: yaml
2214 """
2215 st = XML.SubElement(xml_parent, "org.jenkinsci.plugins.scripttrigger.ScriptTrigger")
2216 st.set("plugin", "scripttrigger")
2217 label = data.get("label")
2218 mappings = [
2219 ("script", "script", ""),
2220 ("script-file-path", "scriptFilePath", ""),
2221 ("cron", "spec", ""),
2222 ("enable-concurrent", "enableConcurrentBuild", False),
2223 ("exit-code", "exitCode", 0),
2224 ("", "labelRestriction", bool(label)),
2225 ("", "triggerLabel", label),
2226 ]
2227 helpers.convert_mapping_to_xml(st, data, mappings, fail_required=False)
2228
2229
2230 def groovy_script(registry, xml_parent, data):
2231 """yaml: groovy-script
2232 Triggers the job using a groovy script.
2233
2234 Requires the Jenkins :jenkins-plugins:`ScriptTrigger Plugin
2235 <scripttrigger>`.
2236
2237 :arg bool system-script: If true, run the groovy script as a system script,
2238 the script will have access to the same variables as the Groovy Console.
2239 If false, run the groovy script on the executor node, the script will not
2240 have access to the hudson or job model. (default false)
2241 :arg str script: Content of the groovy script. If the script result is
2242 evaluated to true, a build is scheduled. (default '')
2243 :arg str script-file-path: Groovy script path. (default '')
2244 :arg str property-file-path: Property file path. All properties will be set
2245 as parameters for the triggered build. (default '')
2246 :arg bool enable-concurrent: Enable concurrent build. (default false)
2247 :arg str label: Restrict where the polling should run. (default '')
2248 :arg str cron: cron syntax of when to run (default '')
2249
2250 Full Example:
2251
2252 .. literalinclude:: /../../tests/triggers/fixtures/groovy-script-full.yaml
2253 :language: yaml
2254
2255 Minimal Example:
2256
2257 .. literalinclude::
2258 /../../tests/triggers/fixtures/groovy-script-minimal.yaml
2259 :language: yaml
2260 """
2261 gst = XML.SubElement(
2262 xml_parent, "org.jenkinsci.plugins.scripttrigger.groovy.GroovyScriptTrigger"
2263 )
2264 gst.set("plugin", "scripttrigger")
2265
2266 label = data.get("label")
2267 mappings = [
2268 ("system-script", "groovySystemScript", False),
2269 ("script", "groovyExpression", ""),
2270 ("script-file-path", "groovyFilePath", ""),
2271 ("property-file-path", "propertiesFilePath", ""),
2272 ("enable-concurrent", "enableConcurrentBuild", False),
2273 ("cron", "spec", ""),
2274 ("", "labelRestriction", bool(label)),
2275 ("", "triggerLabel", label),
2276 ]
2277 helpers.convert_mapping_to_xml(gst, data, mappings, fail_required=False)
2278
2279
2280 def rabbitmq(registry, xml_parent, data):
2281 """yaml: rabbitmq
2282 This plugin triggers build using remote build message in RabbitMQ queue.
2283
2284 Requires the Jenkins :jenkins-plugins:`RabbitMQ Build Trigger Plugin
2285 <rabbitmq-build-trigger>`.
2286
2287 :arg str token: the build token expected in the message queue (required)
2288 :arg list filters: list of filters to apply (optional)
2289
2290 :Filter:
2291 * **field** (`str`) - Some field in message (required)
2292 * **value** (`str`) - value of specified field (required)
2293
2294 Example:
2295
2296 .. literalinclude:: /../../tests/triggers/fixtures/rabbitmq.yaml
2297 :language: yaml
2298
2299 Example with filters:
2300
2301 .. literalinclude:: /../../tests/triggers/fixtures/rabbitmq-filters.yaml
2302 :language: yaml
2303 """
2304
2305 rabbitmq_prefix = "org.jenkinsci.plugins.rabbitmqbuildtrigger."
2306 rabbitmq = XML.SubElement(xml_parent, rabbitmq_prefix + "RemoteBuildTrigger")
2307 filters = data.get("filters", [])
2308 filter_mapping = [("field", "field", None), ("value", "value", None)]
2309 if filters:
2310 filters_tag = XML.SubElement(rabbitmq, "filters")
2311 for filter_data in filters:
2312 filter_tag = XML.SubElement(filters_tag, rabbitmq_prefix + "Filter")
2313 helpers.convert_mapping_to_xml(
2314 filter_tag, filter_data, filter_mapping, fail_required=True
2315 )
2316 mapping = [("", "spec", ""), ("token", "remoteBuildToken", None)]
2317 helpers.convert_mapping_to_xml(rabbitmq, data, mapping, fail_required=True)
2318
2319
2320 def parameterized_timer(parser, xml_parent, data):
2321 """yaml: parameterized-timer
2322 Trigger builds with parameters at certain times.
2323 Requires the Jenkins :jenkins-plugins:`Parameterized Scheduler Plugin
2324 <parameterized-scheduler>`.
2325
2326 :arg str cron: cron syntax of when to run and with which parameters
2327 (required)
2328
2329 Example:
2330
2331 .. literalinclude::
2332 /../../tests/triggers/fixtures/parameterized-timer001.yaml
2333 :language: yaml
2334 """
2335
2336 param_timer = XML.SubElement(
2337 xml_parent,
2338 "org.jenkinsci.plugins.parameterizedscheduler." "ParameterizedTimerTrigger",
2339 )
2340 mapping = [("", "spec", ""), ("cron", "parameterizedSpecification", None)]
2341 helpers.convert_mapping_to_xml(param_timer, data, mapping, fail_required=True)
2342
2343
2344 def jira_changelog(registry, xml_parent, data):
2345 """yaml: jira-changelog
2346 Sets up a trigger that listens to JIRA issue changes.
2347
2348 Requires the Jenkins :jenkins-plugins:`JIRA Trigger Plugin
2349 <jira-trigger>`.
2350
2351 :arg str jql-filter: Must match updated issues to trigger a build.
2352 (default '')
2353 :arg list changelog-matchers:
2354
2355 :Custom Field Matcher:
2356 * **custom-field-name** (`str`) -- The custom field
2357 name that has been changed during the issue update.
2358 (default '')
2359 * **compare-new-value** (`bool`) -- Compare the
2360 new value of the updated field. (default false)
2361 * **new-value** (`str`) -- The new value of the updated field.
2362 (default '')
2363 * **compare-old-value** (`bool`) -- Compare the
2364 old value of the updated field. (default false)
2365 * **old-value** (`str`) -- The value
2366 before the field is updated. (default '')
2367
2368 :JIRA Field Matcher:
2369 * **jira-field-ID** (`str`) -- The JIRA Field ID that
2370 has been changed during the issue update. (default '')
2371 * **compare-new-value** (`bool`) -- Compare the new value
2372 of the updated field. (default false)
2373 * **new-value** (`str`) -- The new value of the updated field.
2374 (default '')
2375 * **compare-old-value** (`bool`) -- Compare the old value
2376 of the updated field. (default false)
2377 * **old-value** (`str`) -- The value before
2378 the field is updated. (default '')
2379
2380 :arg list parameter-mapping:
2381
2382 :Issue Attribute Path:
2383 * **jenkins-parameter** (`str`) -- Jenkins parameter name
2384 (default '')
2385 * **issue-attribute-path** (`str`) -- Attribute path (default '')
2386
2387 Minimal Example:
2388
2389 .. literalinclude::
2390 /../../tests/triggers/fixtures/jira-changelog-minimal.yaml
2391 :language: yaml
2392
2393 Full Example:
2394
2395 .. literalinclude::
2396 /../../tests/triggers/fixtures/jira-changelog-full.yaml
2397 :language: yaml
2398 """
2399 jcht = XML.SubElement(
2400 xml_parent, "com.ceilfors.jenkins.plugins." "jiratrigger.JiraChangelogTrigger"
2401 )
2402 jcht.set("plugin", "jira-trigger")
2403
2404 mapping = [("jql-filter", "jqlFilter", "")]
2405 helpers.convert_mapping_to_xml(jcht, data, mapping, fail_required=True)
2406
2407 changelog = XML.SubElement(jcht, "changelogMatchers")
2408 mappings = [
2409 ("field", "field", ""),
2410 ("new-value", "newValue", ""),
2411 ("old-value", "oldValue", ""),
2412 ("compare-new-value", "comparingNewValue", False),
2413 ("compare-old-value", "comparingOldValue", False),
2414 ]
2415 for matcher in data.get("changelog-matchers", []):
2416
2417 fieldtype = matcher.get("field-type")
2418 if fieldtype == "CUSTOM":
2419 parent_tag = XML.SubElement(
2420 changelog,
2421 "com.ceilfors.jenkins."
2422 "plugins.jiratrigger.changelog."
2423 "CustomFieldChangelogMatcher",
2424 )
2425 XML.SubElement(parent_tag, "fieldType").text = "CUSTOM"
2426
2427 elif fieldtype == "JIRA":
2428 parent_tag = XML.SubElement(
2429 changelog,
2430 "com.ceilfors.jenkins."
2431 "plugins.jiratrigger.changelog."
2432 "JiraFieldChangelogMatcher",
2433 )
2434 XML.SubElement(parent_tag, "fieldType").text = "JIRA"
2435
2436 helpers.convert_mapping_to_xml(
2437 parent_tag, matcher, mappings, fail_required=True
2438 )
2439
2440 param = XML.SubElement(jcht, "parameterMappings")
2441 parameter_mappings = [
2442 ("jenkins-parameter", "jenkinsParameter", ""),
2443 ("issue-attribute-path", "issueAttributePath", ""),
2444 ]
2445 for parameter in data.get("parameter-mapping", []):
2446 parent = XML.SubElement(
2447 param,
2448 "com.ceilfors.jenkins.plugins."
2449 "jiratrigger.parameter."
2450 "IssueAttributePathParameterMapping",
2451 )
2452 helpers.convert_mapping_to_xml(
2453 parent, parameter, parameter_mappings, fail_required=True
2454 )
2455
2456
2457 def jira_comment_trigger(registry, xml_parent, data):
2458 """yaml: jira-comment-trigger
2459 Trigger builds when a comment is added to JIRA.
2460
2461 Requires the Jenkins :jenkins-plugins:`JIRA Trigger Plugin
2462 <jira-trigger>`.
2463
2464 :arg str jql-filter: Must match updated issues to trigger a build.
2465 (default '')
2466 :arg str comment-pattern: Triggers build only when the comment added to
2467 JIRA matches pattern (default '(?i)build this please')
2468 :arg list parameter-mapping:
2469
2470 :Issue Attribute Path:
2471 * **jenkins-parameter** (`str`) -- Jenkins parameter name
2472 (default '')
2473 * **issue-attribute-path** (`str`) -- Attribute path (default '')
2474
2475 Minimal Example:
2476
2477 .. literalinclude::
2478 /../../tests/triggers/fixtures/jira-comment-trigger-minimal.yaml
2479 :language: yaml
2480
2481 Full Example:
2482
2483 .. literalinclude::
2484 /../../tests/triggers/fixtures/jira-comment-trigger-full.yaml
2485 :language: yaml
2486 """
2487 jct = XML.SubElement(
2488 xml_parent, "com.ceilfors.jenkins.plugins." "jiratrigger.JiraCommentTrigger"
2489 )
2490 jct.set("plugin", "jira-trigger")
2491 mapping = [
2492 ("jql-filter", "jqlFilter", ""),
2493 ("comment-pattern", "commentPattern", "(?i)build this please"),
2494 ]
2495 helpers.convert_mapping_to_xml(jct, data, mapping, fail_required=True)
2496
2497 param = XML.SubElement(jct, "parameterMappings")
2498 for parameter in data.get("parameter-mapping", []):
2499 parent = XML.SubElement(
2500 param,
2501 "com.ceilfors.jenkins.plugins."
2502 "jiratrigger.parameter."
2503 "IssueAttributePathParameterMapping",
2504 )
2505 parameter_mappings = [
2506 ("jenkins-parameter", "jenkinsParameter", ""),
2507 ("issue-attribute-path", "issueAttributePath", ""),
2508 ]
2509 helpers.convert_mapping_to_xml(
2510 parent, parameter, parameter_mappings, fail_required=True
2511 )
2512
2513
2514 def stash_pull_request(registry, xml_parent, data):
2515 """yaml: stash-pull-request
2516 Trigger builds via Stash/Bitbucket Server Pull Requests.
2517
2518 Requires the Jenkins :jenkins-plugins:`Stash Pull Request Builder Plugin
2519 <stash-pullrequest-builder>`.
2520
2521 :arg str cron: cron syntax of when to run (required)
2522 :arg str stash-host: The HTTP or HTTPS URL of the Stash host (NOT ssh).
2523 e.g.: https://example.com (required)
2524 :arg str credentials-id: Jenkins credential set to use. (required)
2525 :arg str project: Abbreviated project code. e.g.: PRJ or ~user (required)
2526 :arg str repository: Stash Repository Name. e.g.: Repo (required)
2527 :arg str ci-skip-phrases: CI Skip Phrases. (default 'NO TEST')
2528 :arg str ci-build-phrases: CI Build Phrases. (default 'test this please')
2529 :arg str target-branches: Target branches to filter. (default '')
2530 :arg bool ignore-ssl: Ignore SSL certificates for Stash host.
2531 (default false)
2532 :arg bool check-destination-commit: Rebuild if destination branch
2533 changes. (default false)
2534 :arg bool check-mergable: Build only if PR is mergeable. (default false)
2535 :arg bool merge-on-success: Merge PR if build is successful.
2536 (default false)
2537 :arg bool check-not-conflicted: Build only if Stash reports no conflicts.
2538 (default false)
2539 :arg bool only-build-on-comment: Only build when asked (with test
2540 phrase). (default false)
2541 :arg bool delete-previous-build-finish-comments: Keep PR comment only for
2542 most recent Build. (default false)
2543 :arg bool cancel-outdated-jobs: Cancel outdated jobs. (default false)
2544
2545 Minimal Example:
2546
2547 .. literalinclude::
2548 /../../tests/triggers/fixtures/stash-pull-request-minimal.yaml
2549 :language: yaml
2550
2551 Full Example:
2552
2553 .. literalinclude::
2554 /../../tests/triggers/fixtures/stash-pull-request-full.yaml
2555 :language: yaml
2556 """
2557
2558 pr_trigger = XML.SubElement(
2559 xml_parent, "stashpullrequestbuilder.stashpullrequestbuilder.StashBuildTrigger"
2560 )
2561 pr_trigger.set("plugin", "stash-pullrequest-builder")
2562
2563 mappings = [
2564 ("cron", "spec", None), # Spec needs to be set to the same as cron
2565 ("cron", "cron", None),
2566 ("stash-host", "stashHost", None),
2567 ("credentials-id", "credentialsId", None),
2568 ("project", "projectCode", None),
2569 ("repository", "repositoryName", None),
2570 ("ci-skip-phrases", "ciSkipPhrases", "NO TEST"),
2571 ("ci-build-phrases", "ciBuildPhrases", "test this please"),
2572 ("target-branches", "targetBranchesToBuild", ""),
2573 ("ignore-ssl", "ignoreSsl", False),
2574 ("check-destination-commit", "checkDestinationCommit", False),
2575 ("check-mergable", "checkMergeable", False),
2576 ("merge-on-success", "mergeOnSuccess", False),
2577 ("check-not-conflicted", "checkNotConflicted", True),
2578 ("only-build-on-comment", "onlyBuildOnComment", False),
2579 (
2580 "delete-previous-build-finish-comments",
2581 "deletePreviousBuildFinishComments",
2582 False,
2583 ),
2584 ("cancel-outdated-jobs", "cancelOutdatedJobsEnabled", False),
2585 ]
2586 helpers.convert_mapping_to_xml(pr_trigger, data, mappings, fail_required=True)
2587
2588
2589 def generic_webhook_trigger(registry, xml_parent, data):
2590 """yaml: generic-webhook-trigger
2591 Generic webhook trigger. Trigger when a set of parameters are submitted.
2592
2593 Requires the Jenkins :jenkins-plugins:`Generic Webhook Trigger
2594 <generic-webhook-trigger>`.
2595
2596
2597 :arg str token: A token to use to trigger the job. (default '')
2598 :arg str token-credential-id: A token credential id to use to trigger the job. (default '')
2599 :arg bool print-post-content: Print post content in job log.
2600 :arg bool print-contrib-var: Print contributed variables in job log.
2601 :arg bool silent-response: Avoid responding with information about
2602 triggered jobs.
2603 :arg str cause: This will be displayed in any triggered job.
2604 :arg str regex-filter-expression: Regular expression to test on the
2605 evaluated text specified in regex-filter-text
2606 :arg str regex-filter-text: Text to test for the given
2607 regexp-filter-expression.
2608
2609 :arg list post-content-params: Parameters to use from posted JSON/XML
2610
2611 :post-content-params: * **type** (`str`) -- JSONPath or XPath
2612 * **key** (`str`) -- Variable name
2613 * **value** (`str`) -- Expression to evaluate in POST content.
2614 Use JSONPath for JSON or XPath for XML.
2615 * **regex-filter** (`str`) -- Anything in the evaluated value,
2616 matching this regular expression, will be removed. (optional)
2617 * **default-value** (`str`) -- This value will be used if
2618 expression does not match anything. (optional)
2619
2620 :arg list request-params: Parameters to use passed in as request arguments
2621
2622 :request-params: * **key** (`str`) -- Name of request parameter
2623 * **regex-filter** (`str`) -- Anything in the evaluated value,
2624 matching this regular expression, will be removed. (optional)
2625 :arg list header-params: Parameters to use passed in as headers
2626
2627 :header-params: * **key** (`str`) -- Name of request header in
2628 lowercase. Resulting variable name has '_' instead of '-'
2629 characters.
2630 * **regex-filter** (`str`) -- Anything in the evaluated value,
2631 matching this regular expression, will be removed. (optional)
2632
2633 Example:
2634
2635 .. literalinclude::
2636 /../../tests/triggers/fixtures/generic-webhook-trigger-full.yaml
2637 """
2638
2639 namespace = "org.jenkinsci.plugins.gwt."
2640 gwtrig = XML.SubElement(xml_parent, namespace + "GenericTrigger")
2641 gwtrig.set("plugin", "generic-webhook-trigger")
2642 XML.SubElement(gwtrig, "spec")
2643
2644 # Generic Varibles (Post content parameters in UI)
2645 try:
2646 if data.get("post-content-params"):
2647 gen_vars = XML.SubElement(gwtrig, "genericVariables")
2648 mappings = [
2649 ("type", "expressionType", "", ["JSONPath", "XPath"]),
2650 ("key", "key", ""),
2651 ("value", "value", ""),
2652 ("regex-filter", "regexpFilter", ""),
2653 ("default-value", "defaultValue", ""),
2654 ]
2655
2656 for gen_var_list in data.get("post-content-params"):
2657 gen_var_tag = XML.SubElement(gen_vars, namespace + "GenericVariable")
2658 helpers.convert_mapping_to_xml(
2659 gen_var_tag, gen_var_list, mappings, fail_required=True
2660 )
2661 except AttributeError:
2662 pass
2663
2664 # This is dropped here in the middle as that's how the jenkins config is
2665 # done. It probably doesn't need to be, but since this is the first
2666 # swing..
2667 mapping = [
2668 ("regex-filter-text", "regexpFilterText", ""),
2669 ("regex-filter-expression", "regexpFilterExpression", ""),
2670 ]
2671 helpers.convert_mapping_to_xml(gwtrig, data, mapping, fail_required=False)
2672
2673 # Generic Request Variables (Request parameters in UI)
2674 try:
2675 if data.get("request-params"):
2676 gen_req_vars = XML.SubElement(gwtrig, "genericRequestVariables")
2677 mappings = [("key", "key", ""), ("regex-filter", "regexpFilter", "")]
2678
2679 for gen_req_list in data.get("request-params"):
2680 gen_req_tag = XML.SubElement(
2681 gen_req_vars, namespace + "GenericRequestVariable"
2682 )
2683 helpers.convert_mapping_to_xml(
2684 gen_req_tag, gen_req_list, mappings, fail_required=False
2685 )
2686 except AttributeError:
2687 pass
2688
2689 try:
2690 if data.get("header-params"):
2691 gen_header_vars = XML.SubElement(gwtrig, "genericHeaderVariables")
2692 mappings = [("key", "key", ""), ("regex-filter", "regexpFilter", "")]
2693 for gen_header_list in data.get("header-params"):
2694 gen_header_tag = XML.SubElement(
2695 gen_header_vars, namespace + "GenericHeaderVariable"
2696 )
2697 helpers.convert_mapping_to_xml(
2698 gen_header_tag, gen_header_list, mappings, fail_required=False
2699 )
2700 except AttributeError:
2701 pass
2702
2703 mapping = [
2704 ("print-post-content", "printPostContent", False),
2705 ("print-contrib-var", "printContributedVariables", False),
2706 ("cause", "causeString", ""),
2707 ("token", "token", ""),
2708 ("token-credential-id", "tokenCredentialId", ""),
2709 ("silent-response", "silentResponse", False),
2710 ]
2711 # This should cover all the top level
2712 helpers.convert_mapping_to_xml(gwtrig, data, mapping, fail_required=False)
2713
2714
2715 def artifactory(registry, xml_parent, data):
2716 """yaml: artifactory
2717 Artifactory trigger. Trigger if files are added or modified in configured
2718 path(s) to watch on chosen Artifactory server.
2719
2720 Requires the Jenkins :jenkins-plugins:`Artifactory Plugin <Artifactory>`.
2721
2722 :arg str artifactory-server: Artifactory server where the configured
2723 path(s) are monitored from. Available Artifactory servers must be
2724 configured on Jenkins Global Configuration in advance. (default '')
2725 :arg str schedule: cron syntax of when to poll. (default '')
2726 :arg str paths: Paths in Artifactory to poll for changes. Multiple
2727 paths can be configured by the ';' separator. (default '')
2728
2729 Example with Single Path to Monitor:
2730
2731 .. literalinclude::
2732 /../../tests/triggers/fixtures/artifactory-trigger-single-path.yaml
2733 :language: yaml
2734
2735 Example with Multiple Paths to Monitor:
2736
2737 .. literalinclude::
2738 /../../tests/triggers/fixtures/artifactory-trigger-multi-path.yaml
2739 :language: yaml
2740 """
2741
2742 artifactory = XML.SubElement(
2743 xml_parent, "org.jfrog.hudson.trigger.ArtifactoryTrigger"
2744 )
2745 artifactory.set("plugin", "artifactory")
2746 mapping = [
2747 ("schedule", "spec", ""),
2748 ("paths", "paths", ""),
2749 ("", "branches", ""),
2750 ("", "lastModified", ""),
2751 ]
2752 helpers.convert_mapping_to_xml(artifactory, data, mapping, fail_required=True)
2753
2754 details = XML.SubElement(artifactory, "details")
2755 details_mapping = [
2756 ("artifactory-server", "artifactoryName", None),
2757 ("", "stagingPlugin", ""),
2758 ]
2759 helpers.convert_mapping_to_xml(details, data, details_mapping, fail_required=True)
2760
2761
2762 class Triggers(jenkins_jobs.modules.base.Base):
2763 sequence = 50
2764
2765 component_type = "trigger"
2766 component_list_type = "triggers"
2767
2768 def gen_xml(self, xml_parent, data):
2769 triggers = data.get("triggers", [])
2770 if not triggers:
2771 return
2772
2773 if data.get("project-type", "freestyle") != "pipeline":
2774 xml_triggers = XML.SubElement(xml_parent, "triggers", {"class": "vector"})
2775 else:
2776 properties = xml_parent.find("properties")
2777 if properties is None:
2778 properties = XML.SubElement(xml_parent, "properties")
2779 pipeline_trig_prop = XML.SubElement(
2780 properties,
2781 "org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty",
2782 )
2783 xml_triggers = XML.SubElement(pipeline_trig_prop, "triggers")
2784
2785 self.dispatch_component_list("trigger", triggers, xml_triggers)