Debian Codegraph @

jenkins_jobs/modules/project_multibranch.py

raw
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2015 Joost van der Griendt <[email protected]>
3 # Copyright (C) 2018 Sorin Sbarnea <[email protected]>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14 # License for the specific language governing permissions and limitations
15 # under the License.
16
17
18 """
19 The Multibranch Pipeline project module handles creating Jenkins workflow
20 projects.
21 You may specify ``multibranch`` in the ``project-type`` attribute of
22 the :ref:`Job` definition.
23
24 Multibranch Pipeline implementantion in JJB is marked as **experimental**
25 which means that there is no guarantee that its behavior (or configuration)
26 will not change, even between minor releases.
27
28 Plugins required:
29
30 * :jenkins-plugins:`Workflow Plugin <workflow-aggregator>`.
31 * :jenkins-plugins:`Pipeline Multibranch Defaults Plugin
32 <pipeline-multibranch-defaults>` (optional)
33 * :jenkins-plugins:`Basic Branch Build Strategies Plugin
34 <basic-branch-build-strategies>` (optional)
35
36 :Job Parameters:
37
38 * **scm** (`list`): The SCM definition.
39
40 * **bitbucket** (`dict`): Refer to
41 :func:`~bitbucket_scm <bitbucket_scm>` for documentation.
42
43 * **gerrit** (`dict`): Refer to
44 :func:`~gerrit_scm <gerrit_scm>` for documentation.
45
46 * **git** (`dict`): Refer to
47 :func:`~git_scm <git_scm>` for documentation.
48
49 * **github** (`dict`): Refer to
50 :func:`~github_scm <github_scm>` for documentation.
51
52 * **periodic-folder-trigger** (`str`): How often to scan for new branches
53 or pull/change requests. Valid values: 1m, 2m, 5m, 10m, 15m, 20m, 25m,
54 30m, 1h, 2h, 4h, 8h, 12h, 1d, 2d, 1w, 2w, 4w. (default none)
55 * **prune-dead-branches** (`bool`): If dead branches upon check should
56 result in their job being dropped. (default true)
57 * **number-to-keep** (`int`): How many builds should be kept.
58 (default '-1, all')
59 * **days-to-keep** (`int`): For how many days should a build be kept.
60 (default '-1, forever')
61 * **abort-builds** (`bool`): Abort all pending or ongoing builds for removed
62 SCM heads (i.e. deleted branches). (default false)
63 * **script-path** (`str`): Path to Jenkinsfile, relative to workspace.
64 (default 'Jenkinsfile')
65 * **script-id** (`str`): Script id from the global Jenkins script store
66 provided by the config-file provider plugin. Mutually exclusive with
67 **script-path** option.
68 * **sandbox** (`bool`): This option is strongly recommended if the
69 Jenkinsfile is using load to evaluate a groovy source file from an
70 SCM repository. Usable only with **script-id** option. (default 'false')
71
72 Job examples:
73
74 .. literalinclude:: /../../tests/multibranch/fixtures/multibranch_defaults_id_mode.yaml
75
76 .. literalinclude:: /../../tests/multibranch/fixtures/multibranch_defaults_path_mode.yaml
77
78 .. literalinclude:: /../../tests/multibranch/fixtures/multi_scm_full.yaml
79
80 """
81 import collections
82 import logging
83 import xml.etree.ElementTree as XML
84 import jenkins_jobs.modules.base
85 import jenkins_jobs.modules.helpers as helpers
86 import six
87
88 from jenkins_jobs.modules.scm import git_extensions
89 from jenkins_jobs.errors import InvalidAttributeError, MissingAttributeError
90 from jenkins_jobs.errors import Context, JenkinsJobsException
91 from jenkins_jobs.xml_config import remove_ignorable_whitespace
92
93 logger = logging.getLogger(str(__name__))
94
95
96 class WorkflowMultiBranch(jenkins_jobs.modules.base.Base):
97 sequence = 0
98 multibranch_path = "org.jenkinsci.plugins.workflow.multibranch"
99 multibranch_defaults_path = "org.jenkinsci.pipeline.workflow.multibranch"
100 jenkins_class = "".join([multibranch_path, ".WorkflowMultiBranchProject"])
101 jenkins_factory = {
102 "script_path": {
103 "class": "".join([multibranch_path, ".WorkflowBranchProjectFactory"])
104 },
105 "script_id": {
106 "class": "".join(
107 [
108 multibranch_defaults_path,
109 ".defaults.PipelineBranchDefaultsProjectFactory",
110 ]
111 ),
112 "plugin": "pipeline-multibranch-defaults",
113 },
114 }
115
116 @staticmethod
117 def _factory_opts_check(data):
118
119 sandbox = data.get("sandbox", None)
120 script_id = data.get("script-id", None)
121 script_path = data.get("script-path", None)
122
123 if script_id and script_path:
124 error_msg = "script-id and script-path are mutually exclusive options"
125 raise JenkinsJobsException(error_msg)
126 elif not script_id and sandbox:
127 error_msg = (
128 "Sandbox mode is applicable only for multibranch with defaults"
129 "project type used with script-id option"
130 )
131 raise JenkinsJobsException(error_msg)
132
133 def root_xml(self, data):
134 xml_parent = XML.Element(self.jenkins_class)
135 xml_parent.attrib["plugin"] = "workflow-multibranch"
136 XML.SubElement(xml_parent, "properties")
137
138 #########
139 # Views #
140 #########
141
142 views = XML.SubElement(xml_parent, "views")
143 all_view = XML.SubElement(views, "hudson.model.AllView")
144 all_view_mapping = [
145 ("", "name", "All"),
146 ("", "filterExecutors", False),
147 ("", "filterQueue", False),
148 ]
149 helpers.convert_mapping_to_xml(
150 all_view, {}, all_view_mapping, fail_required=True
151 )
152
153 XML.SubElement(
154 all_view, "properties", {"class": "hudson.model.View$PropertyList"}
155 )
156
157 XML.SubElement(
158 all_view, "owner", {"class": self.jenkins_class, "reference": "../../.."}
159 )
160
161 XML.SubElement(
162 xml_parent, "viewsTabBar", {"class": "hudson.views.DefaultViewsTabBar"}
163 )
164
165 ################
166 # Folder Views #
167 ################
168
169 folderViews = XML.SubElement(
170 xml_parent,
171 "folderViews",
172 {
173 "class": "jenkins.branch.MultiBranchProjectViewHolder",
174 "plugin": "branch-api",
175 },
176 )
177
178 XML.SubElement(
179 folderViews, "owner", {"class": self.jenkins_class, "reference": "../.."}
180 )
181
182 ##################
183 # Health Metrics #
184 ##################
185
186 hm = XML.SubElement(xml_parent, "healthMetrics")
187 hm_path = "com.cloudbees.hudson.plugins.folder.health" ".WorstChildHealthMetric"
188 hm_plugin = XML.SubElement(hm, hm_path, {"plugin": "cloudbees-folder"})
189 XML.SubElement(hm_plugin, "nonRecursive").text = "false"
190
191 ########
192 # Icon #
193 ########
194
195 icon = XML.SubElement(
196 xml_parent,
197 "icon",
198 {
199 "class": "jenkins.branch.MetadataActionFolderIcon",
200 "plugin": "branch-api",
201 },
202 )
203 XML.SubElement(
204 icon, "owner", {"class": self.jenkins_class, "reference": "../.."}
205 )
206
207 ########################
208 # Orphan Item Strategy #
209 ########################
210
211 ois_default_strategy = (
212 "com.cloudbees.hudson.plugins."
213 "folder.computed.DefaultOrphanedItemStrategy"
214 )
215 ois = XML.SubElement(
216 xml_parent,
217 "orphanedItemStrategy",
218 {"class": ois_default_strategy, "plugin": "cloudbees-folder"},
219 )
220
221 ois_mapping = [
222 ("prune-dead-branches", "pruneDeadBranches", True, [True, False]),
223 ("days-to-keep", "daysToKeep", -1),
224 ("number-to-keep", "numToKeep", -1),
225 ("abort-builds", "abortBuilds", False, [True, False]),
226 ]
227 helpers.convert_mapping_to_xml(ois, data, ois_mapping)
228
229 ###########################
230 # Periodic Folder Trigger #
231 ###########################
232
233 triggers = XML.SubElement(xml_parent, "triggers")
234
235 # Valid options for the periodic trigger interval.
236 pft_map = collections.OrderedDict(
237 [
238 ("1m", ("* * * * *", "60000")),
239 ("2m", ("*/2 * * * *", "120000")),
240 ("5m", ("*/5 * * * *", "300000")),
241 ("10m", ("H/6 * * * *", "600000")),
242 ("15m", ("H/6 * * * *", "900000")),
243 ("20m", ("H/3 * * * *", "1200000")),
244 ("25m", ("H/3 * * * *", "1500000")),
245 ("30m", ("H/2 * * * *", "1800000")),
246 ("1h", ("H * * * *", "3600000")),
247 ("2h", ("H * * * *", "7200000")),
248 ("4h", ("H * * * *", "14400000")),
249 ("8h", ("H * * * *", "28800000")),
250 ("12h", ("H H * * *", "43200000")),
251 ("1d", ("H H * * *", "86400000")),
252 ("2d", ("H H * * *", "172800000")),
253 ("1w", ("H H * * *", "604800000")),
254 ("2w", ("H H * * *", "1209600000")),
255 ("4w", ("H H * * *", "2419200000")),
256 ]
257 )
258
259 pft_val = data.get("periodic-folder-trigger")
260 if pft_val:
261 if not pft_map.get(pft_val):
262 raise InvalidAttributeError(
263 "periodic-folder-trigger", pft_val, pft_map.keys()
264 )
265
266 pft_path = (
267 "com.cloudbees.hudson.plugins.folder.computed." "PeriodicFolderTrigger"
268 )
269 pft = XML.SubElement(triggers, pft_path, {"plugin": "cloudbees-folder"})
270 XML.SubElement(pft, "spec").text = pft_map[pft_val][0]
271 XML.SubElement(pft, "interval").text = pft_map[pft_val][1]
272
273 ###########
274 # Sources #
275 ###########
276
277 sources = XML.SubElement(
278 xml_parent,
279 "sources",
280 {
281 "class": "jenkins.branch.MultiBranchProject$BranchSourceList",
282 "plugin": "branch-api",
283 },
284 )
285 sources_data = XML.SubElement(sources, "data")
286 XML.SubElement(
287 sources, "owner", {"class": self.jenkins_class, "reference": "../.."}
288 )
289
290 valid_scm = ["bitbucket", "gerrit", "git", "github"]
291 for scm_data in data.get("scm", None):
292 for scm in scm_data:
293 bs = XML.SubElement(sources_data, "jenkins.branch.BranchSource")
294
295 if scm == "bitbucket":
296 bitbucket_scm(bs, scm_data[scm])
297
298 elif scm == "gerrit":
299 gerrit_scm(bs, scm_data[scm])
300
301 elif scm == "git":
302 git_scm(bs, scm_data[scm])
303
304 elif scm == "github":
305 github_scm(bs, scm_data[scm])
306
307 else:
308 raise InvalidAttributeError("scm", scm_data, valid_scm)
309
310 ###########
311 # Factory #
312 ###########
313
314 self._factory_opts_check(data)
315
316 if data.get("script-id"):
317 mode = "script_id"
318 fopts_map = (
319 ("script-id", "scriptId", None),
320 ("sandbox", "useSandbox", None),
321 )
322 else:
323 mode = "script_path"
324 fopts_map = (("script-path", "scriptPath", "Jenkinsfile"),)
325
326 factory = XML.SubElement(xml_parent, "factory", self.jenkins_factory[mode])
327 XML.SubElement(
328 factory, "owner", {"class": self.jenkins_class, "reference": "../.."}
329 )
330
331 # multibranch default
332
333 helpers.convert_mapping_to_xml(factory, data, fopts_map, fail_required=False)
334
335 return xml_parent
336
337
338 class WorkflowMultiBranchDefaults(WorkflowMultiBranch):
339 multibranch_path = "org.jenkinsci.plugins.workflow.multibranch"
340 multibranch_defaults_path = "org.jenkinsci.plugins.pipeline.multibranch"
341 jenkins_class = "".join(
342 [multibranch_defaults_path, ".defaults.PipelineMultiBranchDefaultsProject"]
343 )
344 jenkins_factory = {
345 "script_path": {
346 "class": "".join([multibranch_path, ".WorkflowBranchProjectFactory"]),
347 "plugin": "workflow-multibranch",
348 },
349 "script_id": {
350 "class": "".join(
351 [
352 multibranch_defaults_path,
353 ".defaults.PipelineBranchDefaultsProjectFactory",
354 ]
355 )
356 },
357 }
358
359
360 def bitbucket_scm(xml_parent, data):
361 r"""Configure BitBucket scm
362
363 Requires the :jenkins-plugins:`Bitbucket Branch Source Plugin
364 <cloudbees-bitbucket-branch-source>`.
365
366 :arg str credentials-id: The credential to use to scan BitBucket.
367 (required)
368 :arg str repo-owner: Specify the name of the Bitbucket Team or Bitbucket
369 User Account. (required)
370 :arg str repo: The BitBucket repo. (required)
371
372 :arg bool discover-tags: Discovers tags on the repository.
373 (default false)
374 :arg bool lfs: Git LFS pull after checkout.
375 (default false)
376 :arg str server-url: The address of the bitbucket server. (optional)
377 :arg str head-filter-regex: A regular expression for filtering
378 discovered source branches. Requires the :jenkins-plugins:`SCM API
379 Plugin <scm-api>`.
380 :arg list head-pr-filter-behaviors: Definition of Filter Branch PR behaviors.
381 Requires the :jenkins-plugins:`SCM Filter Branch PR Plugin
382 <scm-filter-branch-pr>`.
383 Refer to :func:`~add_filter_branch_pr_behaviors <add_filter_branch_pr_behaviors>`.
384 :arg str discover-branch: Discovers branches on the repository.
385 Valid options: ex-pr, only-pr, all.
386 Value is not specified by default.
387 :arg str discover-pr-origin: Discovers pull requests where the origin
388 repository is the same as the target repository.
389 Valid options: mergeOnly, headOnly, mergeAndHead.
390 Value is not specified by default.
391 :arg str discover-pr-forks-strategy: Fork strategy. Valid options:
392 merge-current, current, both, false. (default 'merge-current')
393 :arg str discover-pr-forks-trust: Discovers pull requests where the origin
394 repository is a fork of the target repository.
395 Valid options: contributors, everyone, permission or nobody.
396 (default 'contributors')
397 :arg list build-strategies: Provides control over whether to build a branch
398 (or branch like things such as change requests and tags) whenever it is
399 discovered initially or a change from the previous revision has been
400 detected. (optional)
401 Refer to :func:`~build_strategies <build_strategies>`.
402 :arg dict property-strategies: Provides control over how to build a branch
403 (like to disable SCM triggering or to override the pipeline durability)
404 (optional)
405 Refer to :func:`~property_strategies <property_strategies>`.
406 :arg bool local-branch: Check out to matching local branch
407 If given, checkout the revision to build as HEAD on this branch.
408 If selected, then the branch name is computed from the remote branch
409 without the origin. In that case, a remote branch origin/master will
410 be checked out to a local branch named master, and a remote branch
411 origin/develop/new-feature will be checked out to a local branch
412 named develop/newfeature.
413 Requires the :jenkins-plugins:`Git Plugin <git>`.
414 :arg list(str) refspecs: Which refspecs to look for.
415 :arg dict checkout-over-ssh: Checkout repo over ssh.
416
417 * **credentials** ('str'): Credentials to use for
418 checkout of the repo over ssh.
419
420 :arg dict filter-by-name-wildcard: Enable filter by name with wildcards.
421 Requires the :jenkins-plugins:`SCM API Plugin <scm-api>`.
422
423 * **includes** ('str'): Space-separated list
424 of name patterns to consider. You may use * as a wildcard;
425 for example: `master release*`
426 * **excludes** ('str'): Name patterns to
427 ignore even if matched by the includes list.
428 For example: `release*`
429
430 :extensions:
431
432 * **clean** (`dict`)
433 * **after** (`dict`) - Clean the workspace after checkout
434 * **remove-stale-nested-repos** (`bool`) - Deletes untracked
435 submodules and any other subdirectories which contain .git directories
436 (default false)
437 * **before** (`dict`) - Clean the workspace before checkout
438 * **remove-stale-nested-repos** (`bool`) - Deletes untracked
439 submodules and any other subdirectories which contain .git directories
440 (default false)
441 * **prune** (`bool`) - Prune remote branches (default false)
442 * **shallow-clone** (`bool`) - Perform shallow clone (default false)
443 * **sparse-checkout** (dict)
444 * **paths** (list) - List of paths to sparse checkout. (optional)
445 * **depth** (`int`) - Set shallow clone depth (default 1)
446 * **do-not-fetch-tags** (`bool`) - Perform a clone without tags
447 (default false)
448 * **submodule** (`dict`)
449 * **disable** (`bool`) - By disabling support for submodules you
450 can still keep using basic git plugin functionality and just have
451 Jenkins to ignore submodules completely as if they didn't exist.
452 * **recursive** (`bool`) - Retrieve all submodules recursively
453 (uses '--recursive' option which requires git>=1.6.5)
454 * **tracking** (`bool`) - Retrieve the tip of the configured
455 branch in .gitmodules (Uses '\-\-remote' option which requires
456 git>=1.8.2)
457 * **parent-credentials** (`bool`) - Use credentials from default
458 remote of parent repository (default false).
459 * **reference-repo** (`str`) - Path of the reference repo to use
460 during clone (optional)
461 * **timeout** (`int`) - Specify a timeout (in minutes) for
462 submodules operations (default 10).
463 * **timeout** (`str`) - Timeout for git commands in minutes (optional)
464 * **use-author** (`bool`): Use author rather than committer in Jenkin's
465 build changeset (default false)
466 * **wipe-workspace** (`bool`) - Wipe out workspace before build
467 (default true)
468 * **lfs-pull** (`bool`) - Call git lfs pull after checkout
469 (default false)
470
471
472 Minimal Example:
473
474 .. literalinclude::
475 /../../tests/multibranch/fixtures/scm_bitbucket_minimal.yaml
476
477 Full Example:
478
479 .. literalinclude::
480 /../../tests/multibranch/fixtures/scm_bitbucket_full.yaml
481 """
482 source = XML.SubElement(
483 xml_parent,
484 "source",
485 {
486 "class": "com.cloudbees.jenkins.plugins.bitbucket.BitbucketSCMSource",
487 "plugin": "cloudbees-bitbucket-branch-source",
488 },
489 )
490 source_mapping = [
491 ("", "id", "-".join(["bb", data.get("repo-owner", ""), data.get("repo", "")])),
492 ("repo-owner", "repoOwner", None),
493 ("repo", "repository", None),
494 ]
495 helpers.convert_mapping_to_xml(source, data, source_mapping, fail_required=True)
496
497 mapping_optional = [
498 ("credentials-id", "credentialsId", None),
499 ("server-url", "serverUrl", None),
500 ]
501 helpers.convert_mapping_to_xml(source, data, mapping_optional, fail_required=False)
502
503 traits = XML.SubElement(source, "traits")
504
505 if data.get("refspecs"):
506 refspec_trait = XML.SubElement(
507 traits,
508 "jenkins.plugins.git.traits.RefSpecsSCMSourceTrait",
509 {"plugin": "git"},
510 )
511 templates = XML.SubElement(refspec_trait, "templates")
512 refspecs = data.get("refspecs")
513 for refspec in refspecs:
514 e = XML.SubElement(
515 templates,
516 (
517 "jenkins.plugins.git.traits"
518 ".RefSpecsSCMSourceTrait_-RefSpecTemplate"
519 ),
520 )
521 XML.SubElement(e, "value").text = refspec
522
523 if data.get("discover-tags", False):
524 XML.SubElement(
525 traits, "com.cloudbees.jenkins.plugins.bitbucket.TagDiscoveryTrait"
526 )
527
528 if data.get("lfs", False):
529 gitlfspull = XML.SubElement(
530 traits, "jenkins.plugins.git.traits.GitLFSPullTrait", {"plugin": "git"}
531 )
532 XML.SubElement(
533 gitlfspull,
534 "extension",
535 {"class": "hudson.plugins.git.extensions.impl.GitLFSPull"},
536 )
537
538 if data.get("head-filter-regex", None):
539 rshf = XML.SubElement(traits, "jenkins.scm.impl.trait.RegexSCMHeadFilterTrait")
540 XML.SubElement(rshf, "regex").text = data.get("head-filter-regex")
541
542 if data.get("head-pr-filter-behaviors", None):
543 add_filter_branch_pr_behaviors(traits, data.get("head-pr-filter-behaviors"))
544
545 if data.get("discover-pr-origin", None):
546 dpro = XML.SubElement(
547 traits,
548 "com.cloudbees.jenkins.plugins.bitbucket"
549 ".OriginPullRequestDiscoveryTrait",
550 )
551 dpro_strategies = {"mergeOnly": "1", "headOnly": "2", "mergeAndHead": "3"}
552 dpro_mapping = [("discover-pr-origin", "strategyId", None, dpro_strategies)]
553 helpers.convert_mapping_to_xml(dpro, data, dpro_mapping, fail_required=True)
554
555 if data.get("discover-pr-forks-strategy"):
556 dprf = XML.SubElement(
557 traits,
558 "com.cloudbees.jenkins.plugins.bitbucket" ".ForkPullRequestDiscoveryTrait",
559 )
560 dprf_strategy = {"merge-current": "1", "current": "2", "both": "3"}
561 dprf_mapping = [
562 ("discover-pr-forks-strategy", "strategyId", "merge-current", dprf_strategy)
563 ]
564 helpers.convert_mapping_to_xml(dprf, data, dprf_mapping, fail_required=True)
565
566 trust = data.get("discover-pr-forks-trust", "contributors")
567 trust_map = {
568 "contributors": "".join(
569 [
570 "com.cloudbees.jenkins.plugins.bitbucket"
571 ".ForkPullRequestDiscoveryTrait$TrustContributors"
572 ]
573 ),
574 "everyone": "".join(
575 [
576 "com.cloudbees.jenkins.plugins.bitbucket"
577 ".ForkPullRequestDiscoveryTrait$TrustEveryone"
578 ]
579 ),
580 "permission": "".join(
581 [
582 "com.cloudbees.jenkins.plugins.bitbucket"
583 ".ForkPullRequestDiscoveryTrait$TrustPermission"
584 ]
585 ),
586 "nobody": "".join(
587 [
588 "com.cloudbees.jenkins.plugins.bitbucket"
589 ".ForkPullRequestDiscoveryTrait$TrustNobody"
590 ]
591 ),
592 }
593 if trust not in trust_map:
594 raise InvalidAttributeError(
595 "discover-pr-forks-trust", trust, trust_map.keys()
596 )
597 XML.SubElement(dprf, "trust").attrib["class"] = trust_map[trust]
598
599 if data.get("discover-branch", None):
600 dbr = XML.SubElement(
601 traits, "com.cloudbees.jenkins.plugins.bitbucket.BranchDiscoveryTrait"
602 )
603 dbr_strategies = {"ex-pr": "1", "only-pr": "2", "all": "3"}
604 dbr_mapping = [("discover-branch", "strategyId", None, dbr_strategies)]
605 helpers.convert_mapping_to_xml(dbr, data, dbr_mapping, fail_required=True)
606
607 if data.get("property-strategies", None):
608 property_strategies(xml_parent, data)
609
610 if data.get("build-strategies", None):
611 build_strategies(xml_parent, data)
612
613 if data.get("local-branch", False):
614 lbr = XML.SubElement(
615 traits, "jenkins.plugins.git.traits.LocalBranchTrait", {"plugin": "git"}
616 )
617 lbr_extension = XML.SubElement(
618 lbr,
619 "extension",
620 {"class": "hudson.plugins.git.extensions.impl.LocalBranch"},
621 )
622 XML.SubElement(lbr_extension, "localBranch").text = "**"
623
624 if data.get("checkout-over-ssh", None):
625 cossh = XML.SubElement(
626 traits, "com.cloudbees.jenkins.plugins.bitbucket.SSHCheckoutTrait"
627 )
628 cossh_credentials = [("credentials", "credentialsId", "")]
629 helpers.convert_mapping_to_xml(
630 cossh, data.get("checkout-over-ssh"), cossh_credentials, fail_required=True
631 )
632
633 add_filter_by_name_wildcard_behaviors(traits, data)
634
635 # handle the default git extensions like:
636 # - clean
637 # - shallow-clone
638 # - timeout
639 # - do-not-fetch-tags
640 # - submodule
641 # - prune
642 # - wipe-workspace
643 # - use-author
644 # - lfs-pull
645 git_extensions(traits, data)
646
647
648 def gerrit_scm(xml_parent, data):
649 r"""Configure Gerrit SCM
650
651 Requires the :jenkins-plugins:`Gerrit Code Review Plugin
652 <gerrit-code-review>`.
653
654 :arg str url: The git url. (required)
655 :arg str credentials-id: The credential to use to connect to the GIT URL.
656 :arg bool ignore-on-push-notifications: If a job should not trigger upon
657 push notifications. (default false)
658 :arg list(str) refspecs: Which refspecs to look for.
659 (default ``['+refs/changes/*:refs/remotes/@{remote}/*',
660 '+refs/heads/*:refs/remotes/@{remote}/*']``)
661 :arg str includes: Comma-separated list of branches to be included.
662 (default '*')
663 :arg str excludes: Comma-separated list of branches to be excluded.
664 (default '')
665 :arg str head-filter-regex: A regular expression for filtering
666 discovered source branches. Requires the :jenkins-plugins:`SCM API
667 Plugin <scm-api>`.
668 :arg list build-strategies: Provides control over whether to build a branch
669 (or branch like things such as change requests and tags) whenever it is
670 discovered initially or a change from the previous revision has been
671 detected. (optional)
672 Refer to :func:`~build_strategies <build_strategies>`.
673 :arg dict property-strategies: Provides control over how to build a branch
674 (like to disable SCM triggering or to override the pipeline durability)
675 (optional)
676 Refer to :func:`~property_strategies <property_strategies>`.
677 :arg dict filter-checks: Enable the filtering by pending checks, allowing to
678 discover the changes that need validation only. This feature is using
679 the gerrit checks plugin.
680 (optional)
681 query-operator: Name of the query operator, supported values are:
682 'SCHEME' or 'ID'.
683 query-string: Value of the query operator.
684 :arg dict change-discovery: Configure the query string in 'Discover open changes'.
685 The default 'p:<project> status:open -age:24w' will be added prior to the
686 query-string specified here.
687 (optional)
688 query-string: Value of the query operator.
689
690 :extensions:
691
692 * **clean** (`dict`)
693 * **after** (`dict`) - Clean the workspace after checkout
694 * **remove-stale-nested-repos** (`bool`) - Deletes untracked
695 submodules and any other subdirectories which contain .git directories
696 (default false)
697 * **before** (`dict`) - Clean the workspace before checkout
698 * **remove-stale-nested-repos** (`bool`) - Deletes untracked
699 submodules and any other subdirectories which contain .git directories
700 (default false)
701 * **prune** (`bool`) - Prune remote branches (default false)
702 * **shallow-clone** (`bool`) - Perform shallow clone (default false)
703 * **sparse-checkout** (dict)
704 * **paths** (list) - List of paths to sparse checkout. (optional)
705 * **depth** (`int`) - Set shallow clone depth (default 1)
706 * **do-not-fetch-tags** (`bool`) - Perform a clone without tags
707 (default false)
708 * **submodule** (`dict`)
709 * **disable** (`bool`) - By disabling support for submodules you
710 can still keep using basic git plugin functionality and just have
711 Jenkins to ignore submodules completely as if they didn't exist.
712 * **recursive** (`bool`) - Retrieve all submodules recursively
713 (uses '--recursive' option which requires git>=1.6.5)
714 * **tracking** (`bool`) - Retrieve the tip of the configured
715 branch in .gitmodules (Uses '\-\-remote' option which requires
716 git>=1.8.2)
717 * **parent-credentials** (`bool`) - Use credentials from default
718 remote of parent repository (default false).
719 * **reference-repo** (`str`) - Path of the reference repo to use
720 during clone (optional)
721 * **timeout** (`int`) - Specify a timeout (in minutes) for
722 submodules operations (default 10).
723 * **timeout** (`str`) - Timeout for git commands in minutes (optional)
724 * **use-author** (`bool`): Use author rather than committer in Jenkin's
725 build changeset (default false)
726 * **wipe-workspace** (`bool`) - Wipe out workspace before build
727 (default true)
728 * **lfs-pull** (`bool`) - Call git lfs pull after checkout
729 (default false)
730
731 Minimal Example:
732
733 .. literalinclude::
734 /../../tests/multibranch/fixtures/scm_gerrit_minimal.yaml
735
736 Full Example:
737
738 .. literalinclude::
739 /../../tests/multibranch/fixtures/scm_gerrit_full.yaml
740 """
741 source = XML.SubElement(
742 xml_parent,
743 "source",
744 {
745 "class": "jenkins.plugins.gerrit.GerritSCMSource",
746 "plugin": "gerrit-code-review",
747 },
748 )
749 source_mapping = [
750 ("", "id", "-".join(["gr", data.get("url", "")])),
751 ("url", "remote", None),
752 ("credentials-id", "credentialsId", ""),
753 ("includes", "includes", "*"),
754 ("excludes", "excludes", ""),
755 ("ignore-on-push-notifications", "ignoreOnPushNotifications", True),
756 ]
757 helpers.convert_mapping_to_xml(source, data, source_mapping, fail_required=True)
758
759 source_mapping_optional = [("api-uri", "apiUri", None)]
760 helpers.convert_mapping_to_xml(
761 source, data, source_mapping_optional, fail_required=False
762 )
763
764 # Traits
765 traits = XML.SubElement(source, "traits")
766 change_discovery_trait = XML.SubElement(
767 traits, "jenkins.plugins.gerrit.traits.ChangeDiscoveryTrait"
768 )
769 change_discovery = data.get("change-discovery", None)
770 if change_discovery:
771 change_discovery_mapping = [("query-string", "queryString", None)]
772 helpers.convert_mapping_to_xml(
773 change_discovery_trait,
774 change_discovery,
775 change_discovery_mapping,
776 fail_required=True,
777 )
778
779 # Refspec Trait
780 refspec_trait = XML.SubElement(
781 traits, "jenkins.plugins.git.traits.RefSpecsSCMSourceTrait", {"plugin": "git"}
782 )
783 templates = XML.SubElement(refspec_trait, "templates")
784 refspecs = data.get(
785 "refspecs",
786 [
787 "+refs/changes/*:refs/remotes/@{remote}/*",
788 "+refs/heads/*:refs/remotes/@{remote}/*",
789 ],
790 )
791 # convert single string to list
792 if isinstance(refspecs, six.string_types):
793 refspecs = [refspecs]
794 for x in refspecs:
795 e = XML.SubElement(
796 templates,
797 ("jenkins.plugins.git.traits" ".RefSpecsSCMSourceTrait_-RefSpecTemplate"),
798 )
799 XML.SubElement(e, "value").text = x
800
801 if data.get("property-strategies", None):
802 property_strategies(xml_parent, data)
803
804 if data.get("build-strategies", None):
805 build_strategies(xml_parent, data)
806
807 if data.get("head-filter-regex", None):
808 rshf = XML.SubElement(traits, "jenkins.scm.impl.trait.RegexSCMHeadFilterTrait")
809 XML.SubElement(rshf, "regex").text = data.get("head-filter-regex")
810
811 # FilterChecks Trait
812 checks = data.get("filter-checks", None)
813 if checks:
814 checks_trait = XML.SubElement(
815 traits, "jenkins.plugins.gerrit.traits.FilterChecksTrait"
816 )
817 checks_source_mapping = [
818 ("query-operator", "queryOperator", None),
819 ("query-string", "queryString", None),
820 ]
821 helpers.convert_mapping_to_xml(
822 checks_trait, checks, checks_source_mapping, fail_required=True
823 )
824
825 # handle the default git extensions like:
826 # - clean
827 # - shallow-clone
828 # - timeout
829 # - do-not-fetch-tags
830 # - submodule
831 # - prune
832 # - wipe-workspace
833 # - use-author
834 # - lfs-pull
835 git_extensions(traits, data)
836
837
838 def git_scm(xml_parent, data):
839 r"""Configure Git SCM
840
841 Requires the :jenkins-plugins:`Git Plugin <git>`.
842
843 :arg str url: The git repo url. (required)
844 :arg str credentials-id: The credential to use to connect to the GIT repo.
845 (default '')
846
847 :arg bool discover-branches: Discovers branches on the repository.
848 (default true)
849 :arg bool discover-tags: Discovers tags on the repository.
850 (default false)
851 :arg bool ignore-on-push-notifications: If a job should not trigger upon
852 push notifications. (default false)
853 :arg str head-filter-regex: A regular expression for filtering
854 discovered source branches. Requires the :jenkins-plugins:`SCM API
855 Plugin <scm-api>`.
856 :arg list head-pr-filter-behaviors: Definition of Filter Branch PR behaviors.
857 Requires the :jenkins-plugins:`SCM Filter Branch PR Plugin
858 <scm-filter-branch-pr>`.
859 Refer to :func:`~add_filter_branch_pr_behaviors <add_filter_branch_pr_behaviors>`.
860 :arg list build-strategies: Provides control over whether to build a branch
861 (or branch like things such as change requests and tags) whenever it is
862 discovered initially or a change from the previous revision has been
863 detected. (optional)
864 Refer to :func:`~build_strategies <build_strategies>`.
865 :arg dict property-strategies: Provides control over how to build a branch
866 (like to disable SCM triggering or to override the pipeline durability)
867 (optional)
868 Refer to :func:`~property_strategies <property_strategies>`.
869
870 :extensions:
871
872 * **clean** (`dict`)
873 * **after** (`dict`) - Clean the workspace after checkout
874 * **remove-stale-nested-repos** (`bool`) - Deletes untracked
875 submodules and any other subdirectories which contain .git directories
876 (default false)
877 * **before** (`dict`) - Clean the workspace before checkout
878 * **remove-stale-nested-repos** (`bool`) - Deletes untracked
879 submodules and any other subdirectories which contain .git directories
880 (default false)
881 * **prune** (`bool`) - Prune remote branches (default false)
882 * **shallow-clone** (`bool`) - Perform shallow clone (default false)
883 * **sparse-checkout** (dict)
884 * **paths** (list) - List of paths to sparse checkout. (optional)
885 * **depth** (`int`) - Set shallow clone depth (default 1)
886 * **do-not-fetch-tags** (`bool`) - Perform a clone without tags
887 (default false)
888 * **submodule** (`dict`)
889 * **disable** (`bool`) - By disabling support for submodules you
890 can still keep using basic git plugin functionality and just have
891 Jenkins to ignore submodules completely as if they didn't exist.
892 * **recursive** (`bool`) - Retrieve all submodules recursively
893 (uses '--recursive' option which requires git>=1.6.5)
894 * **tracking** (`bool`) - Retrieve the tip of the configured
895 branch in .gitmodules (Uses '\-\-remote' option which requires
896 git>=1.8.2)
897 * **parent-credentials** (`bool`) - Use credentials from default
898 remote of parent repository (default false).
899 * **reference-repo** (`str`) - Path of the reference repo to use
900 during clone (optional)
901 * **timeout** (`int`) - Specify a timeout (in minutes) for
902 submodules operations (default 10).
903 * **timeout** (`str`) - Timeout for git commands in minutes (optional)
904 * **use-author** (`bool`): Use author rather than committer in Jenkin's
905 build changeset (default false)
906 * **wipe-workspace** (`bool`) - Wipe out workspace before build
907 (default true)
908 * **lfs-pull** (`bool`) - Call git lfs pull after checkout
909 (default false)
910
911 Minimal Example:
912
913 .. literalinclude:: /../../tests/multibranch/fixtures/scm_git_minimal.yaml
914
915 Full Example:
916
917 .. literalinclude:: /../../tests/multibranch/fixtures/scm_git_full.yaml
918 """
919 source = XML.SubElement(
920 xml_parent,
921 "source",
922 {"class": "jenkins.plugins.git.GitSCMSource", "plugin": "git"},
923 )
924 source_mapping = [
925 ("", "id", "-".join(["gt", data.get("url", "")])),
926 ("url", "remote", None),
927 ("credentials-id", "credentialsId", ""),
928 ]
929 helpers.convert_mapping_to_xml(source, data, source_mapping, fail_required=True)
930
931 ##########
932 # Traits #
933 ##########
934
935 traits_path = "jenkins.plugins.git.traits"
936 traits = XML.SubElement(source, "traits")
937
938 if data.get("discover-branches", True):
939 XML.SubElement(traits, "".join([traits_path, ".BranchDiscoveryTrait"]))
940
941 if data.get("discover-tags", False):
942 XML.SubElement(traits, "".join([traits_path, ".TagDiscoveryTrait"]))
943
944 if data.get("ignore-on-push-notifications", False):
945 XML.SubElement(traits, "".join([traits_path, ".IgnoreOnPushNotificationTrait"]))
946
947 if data.get("head-filter-regex", None):
948 rshf = XML.SubElement(traits, "jenkins.scm.impl.trait.RegexSCMHeadFilterTrait")
949 XML.SubElement(rshf, "regex").text = data.get("head-filter-regex")
950
951 if data.get("head-pr-filter-behaviors", None):
952 add_filter_branch_pr_behaviors(traits, data.get("head-pr-filter-behaviors"))
953
954 if data.get("property-strategies", None):
955 property_strategies(xml_parent, data)
956
957 if data.get("build-strategies", None):
958 build_strategies(xml_parent, data)
959
960 # handle the default git extensions like:
961 # - clean
962 # - shallow-clone
963 # - timeout
964 # - do-not-fetch-tags
965 # - submodule
966 # - prune
967 # - wipe-workspace
968 # - use-author
969 # - lfs-pull
970 git_extensions(traits, data)
971
972
973 def github_scm(xml_parent, data):
974 r"""Configure GitHub SCM
975
976 Requires the :jenkins-plugins:`GitHub Branch Source Plugin
977 <github-branch-source>`.
978
979 :arg str api-uri: The GitHub API uri for hosted / on-site GitHub. Must
980 first be configured in Global Configuration. (default GitHub)
981 :arg bool ssh-checkout: Checkout over SSH.
982
983 * **credentials** ('str'): Credentials to use for
984 checkout of the repo over ssh.
985
986 :arg str credentials-id: Credentials used to scan branches and pull
987 requests, check out sources and mark commit statuses. (optional)
988 :arg str repo-owner: Specify the name of the GitHub Organization or
989 GitHub User Account. (required)
990 :arg str repo: The GitHub repo. (required)
991
992 :arg str branch-discovery: Discovers branches on the repository.
993 Valid options: no-pr, only-pr, all, false. (default 'no-pr')
994 :arg str discover-pr-forks-strategy: Fork strategy. Valid options:
995 merge-current, current, both, false. (default 'merge-current')
996 :arg str discover-pr-forks-trust: Discovers pull requests where the origin
997 repository is a fork of the target repository.
998 Valid options: contributors, everyone, permission or nobody.
999 (default 'contributors')
1000 :arg str discover-pr-origin: Discovers pull requests where the origin
1001 repository is the same as the target repository.
1002 Valid options: merge-current, current, both, false. (default 'merge-current')
1003 :arg bool discover-tags: Discovers tags on the repository.
1004 (default false)
1005 :arg list head-pr-filter-behaviors: Definition of Filter Branch PR behaviors.
1006 Requires the :jenkins-plugins:`SCM Filter Branch PR Plugin
1007 <scm-filter-branch-pr>`.
1008 Refer to :func:`~add_filter_branch_pr_behaviors <add_filter_branch_pr_behaviors>`.
1009 :arg list build-strategies: Provides control over whether to build a branch
1010 (or branch like things such as change requests and tags) whenever it is
1011 discovered initially or a change from the previous revision has been
1012 detected. (optional)
1013 Refer to :func:`~build_strategies <build_strategies>`.
1014 :arg dict notification-context: Change the default GitHub check notification
1015 context from "continuous-integration/jenkins/SUFFIX" to a custom label / suffix.
1016 (set a label and suffix to true or false, optional)
1017 Requires the :jenkins-plugins:`Github Custom Notification Context SCM
1018 Behaviour <github-scm-trait-notification-context>`.
1019 Refer to :func:`~add_notification_context_trait <add_notification_context_trait>`.
1020 :arg dict property-strategies: Provides control over how to build a branch
1021 (like to disable SCM triggering or to override the pipeline durability)
1022 (optional)
1023 Refer to :func:`~property_strategies <property_strategies>`.
1024 :arg dict filter-by-name-wildcard: Enable filter by name with wildcards.
1025 Requires the :jenkins-plugins:`SCM API Plugin <scm-api>`.
1026
1027 * **includes** ('str'): Space-separated list
1028 of name patterns to consider. You may use * as a wildcard;
1029 for example: `master release*`
1030 * **excludes** ('str'): Name patterns to
1031 ignore even if matched by the includes list.
1032 For example: `release*`
1033
1034 :extensions:
1035
1036 * **clean** (`dict`)
1037 * **after** (`dict`) - Clean the workspace after checkout
1038 * **remove-stale-nested-repos** (`bool`) - Deletes untracked
1039 submodules and any other subdirectories which contain .git directories
1040 (default false)
1041 * **before** (`dict`) - Clean the workspace before checkout
1042 * **remove-stale-nested-repos** (`bool`) - Deletes untracked
1043 submodules and any other subdirectories which contain .git directories
1044 (default false)
1045 * **prune** (`bool`) - Prune remote branches (default false)
1046 * **shallow-clone** (`bool`) - Perform shallow clone (default false)
1047 * **sparse-checkout** (dict)
1048 * **paths** (list) - List of paths to sparse checkout. (optional)
1049 * **depth** (`int`) - Set shallow clone depth (default 1)
1050 * **do-not-fetch-tags** (`bool`) - Perform a clone without tags
1051 (default false)
1052 * **disable-pr-notifications** (`bool`) - Disable default github status
1053 notifications on pull requests (default false) (Requires the
1054 :jenkins-plugins:`GitHub Branch Source Plugin
1055 <disable-github-multibranch-status>`.)
1056 * **refspecs** (`list(str)`): Which refspecs to fetch.
1057 * **submodule** (`dict`)
1058 * **disable** (`bool`) - By disabling support for submodules you
1059 can still keep using basic git plugin functionality and just have
1060 Jenkins to ignore submodules completely as if they didn't exist.
1061 * **recursive** (`bool`) - Retrieve all submodules recursively
1062 (uses '--recursive' option which requires git>=1.6.5)
1063 * **tracking** (`bool`) - Retrieve the tip of the configured
1064 branch in .gitmodules (Uses '\-\-remote' option which requires
1065 git>=1.8.2)
1066 * **parent-credentials** (`bool`) - Use credentials from default
1067 remote of parent repository (default false).
1068 * **reference-repo** (`str`) - Path of the reference repo to use
1069 during clone (optional)
1070 * **timeout** (`int`) - Specify a timeout (in minutes) for
1071 submodules operations (default 10).
1072 * **timeout** (`str`) - Timeout for git commands in minutes (optional)
1073 * **use-author** (`bool`): Use author rather than committer in Jenkin's
1074 build changeset (default false)
1075 * **wipe-workspace** (`bool`) - Wipe out workspace before build
1076 (default true)
1077 * **lfs-pull** (`bool`) - Call git lfs pull after checkout
1078 (default false)
1079
1080 Minimal Example:
1081
1082 .. literalinclude::
1083 /../../tests/multibranch/fixtures/scm_github_minimal.yaml
1084
1085 Full Example:
1086
1087 .. literalinclude::
1088 /../../tests/multibranch/fixtures/scm_github_full.yaml
1089 """
1090 github_path = "org.jenkinsci.plugins.github_branch_source"
1091 github_path_dscore = "org.jenkinsci.plugins.github__branch__source"
1092
1093 source = XML.SubElement(
1094 xml_parent,
1095 "source",
1096 {
1097 "class": "".join([github_path, ".GitHubSCMSource"]),
1098 "plugin": "github-branch-source",
1099 },
1100 )
1101 mapping = [
1102 ("", "id", "-".join(["gh", data.get("repo-owner", ""), data.get("repo", "")])),
1103 ("repo-owner", "repoOwner", None),
1104 ("repo", "repository", None),
1105 ]
1106 helpers.convert_mapping_to_xml(source, data, mapping, fail_required=True)
1107
1108 mapping_optional = [
1109 ("api-uri", "apiUri", None),
1110 ("credentials-id", "credentialsId", None),
1111 ]
1112 helpers.convert_mapping_to_xml(source, data, mapping_optional, fail_required=False)
1113
1114 traits = XML.SubElement(source, "traits")
1115
1116 # no-pr value is assumed if branch-discovery not mentioned.
1117 if data.get("branch-discovery", "no-pr"):
1118 bd = XML.SubElement(
1119 traits, "".join([github_path_dscore, ".BranchDiscoveryTrait"])
1120 )
1121 bd_strategy = {"no-pr": "1", "only-pr": "2", "all": "3"}
1122 bd_mapping = [("branch-discovery", "strategyId", "no-pr", bd_strategy)]
1123 helpers.convert_mapping_to_xml(bd, data, bd_mapping, fail_required=True)
1124
1125 if data.get("ssh-checkout", None):
1126 cossh = XML.SubElement(
1127 traits, "".join([github_path_dscore, ".SSHCheckoutTrait"])
1128 )
1129 if not isinstance(data.get("ssh-checkout"), bool):
1130 cossh_credentials = [("credentials", "credentialsId", "")]
1131 helpers.convert_mapping_to_xml(
1132 cossh, data.get("ssh-checkout"), cossh_credentials, fail_required=True
1133 )
1134
1135 if data.get("discover-tags", False):
1136 XML.SubElement(traits, "".join([github_path_dscore, ".TagDiscoveryTrait"]))
1137
1138 if data.get("discover-pr-forks-strategy", "merged-current"):
1139 dprf = XML.SubElement(
1140 traits, "".join([github_path_dscore, ".ForkPullRequestDiscoveryTrait"])
1141 )
1142 dprf_strategy = {"merge-current": "1", "current": "2", "both": "3"}
1143 dprf_mapping = [
1144 ("discover-pr-forks-strategy", "strategyId", "merge-current", dprf_strategy)
1145 ]
1146 helpers.convert_mapping_to_xml(dprf, data, dprf_mapping, fail_required=True)
1147
1148 trust = data.get("discover-pr-forks-trust", "contributors")
1149 trust_map = {
1150 "contributors": "".join(
1151 [github_path, ".ForkPullRequestDiscoveryTrait$TrustContributors"]
1152 ),
1153 "everyone": "".join(
1154 [github_path, ".ForkPullRequestDiscoveryTrait$TrustEveryone"]
1155 ),
1156 "permission": "".join(
1157 [github_path, ".ForkPullRequestDiscoveryTrait$TrustPermission"]
1158 ),
1159 "nobody": "".join(
1160 [github_path, ".ForkPullRequestDiscoveryTrait$TrustNobody"]
1161 ),
1162 }
1163 if trust not in trust_map:
1164 raise InvalidAttributeError(
1165 "discover-pr-forks-trust", trust, trust_map.keys()
1166 )
1167 XML.SubElement(dprf, "trust").attrib["class"] = trust_map[trust]
1168
1169 dpro_strategy = data.get("discover-pr-origin", "merge-current")
1170 if dpro_strategy:
1171 dpro = XML.SubElement(
1172 traits, "".join([github_path_dscore, ".OriginPullRequestDiscoveryTrait"])
1173 )
1174 dpro_strategy_map = {"merge-current": "1", "current": "2", "both": "3"}
1175 if dpro_strategy not in dpro_strategy_map:
1176 raise InvalidAttributeError(
1177 "discover-pr-origin", dpro_strategy, dpro_strategy_map.keys()
1178 )
1179 dpro_mapping = [
1180 ("discover-pr-origin", "strategyId", "merge-current", dpro_strategy_map)
1181 ]
1182 helpers.convert_mapping_to_xml(dpro, data, dpro_mapping, fail_required=True)
1183
1184 if data.get("head-filter-regex", None):
1185 rshf = XML.SubElement(traits, "jenkins.scm.impl.trait.RegexSCMHeadFilterTrait")
1186 XML.SubElement(rshf, "regex").text = data.get("head-filter-regex")
1187
1188 if data.get("head-pr-filter-behaviors", None):
1189 add_filter_branch_pr_behaviors(traits, data.get("head-pr-filter-behaviors"))
1190
1191 if data.get("property-strategies", None):
1192 property_strategies(xml_parent, data)
1193
1194 if data.get("build-strategies", None):
1195 build_strategies(xml_parent, data)
1196
1197 add_github_checks_traits(traits, data)
1198 add_notification_context_trait(traits, data)
1199 add_filter_by_name_wildcard_behaviors(traits, data)
1200
1201 # handle the default git extensions like:
1202 # - clean
1203 # - shallow-clone
1204 # - timeout
1205 # - do-not-fetch-tags
1206 # - submodule
1207 # - prune
1208 # - wipe-workspace
1209 # - use-author
1210 # - lfs-pull
1211 git_extensions(traits, data)
1212
1213 if data.get("refspecs"):
1214 refspec_trait = XML.SubElement(
1215 traits,
1216 "jenkins.plugins.git.traits.RefSpecsSCMSourceTrait",
1217 {"plugin": "git"},
1218 )
1219 templates = XML.SubElement(refspec_trait, "templates")
1220 refspecs = data.get("refspecs")
1221 for refspec in refspecs:
1222 e = XML.SubElement(
1223 templates,
1224 (
1225 "jenkins.plugins.git.traits"
1226 ".RefSpecsSCMSourceTrait_-RefSpecTemplate"
1227 ),
1228 )
1229 XML.SubElement(e, "value").text = refspec
1230
1231 # github-only extensions
1232 disable_github_status_path_dscore = (
1233 "com.adobe.jenkins.disable__github__multibranch__status"
1234 )
1235 if data.get("disable-pr-notifications", False):
1236 XML.SubElement(
1237 traits,
1238 "".join([disable_github_status_path_dscore, ".DisableStatusUpdateTrait"]),
1239 {"plugin": "disable-github-multibranch-status"},
1240 )
1241
1242
1243 def build_strategies(xml_parent, data):
1244 """Configure Basic Branch Build Strategies.
1245
1246 Requires the :jenkins-plugins:`Basic Branch Build Strategies Plugin
1247 <basic-branch-build-strategies>`.
1248
1249 Other build strategies can be configured via raw XML injection.
1250
1251 :arg list build-strategies: Definition of build strategies.
1252
1253 * **all-strategies-match** (dict): All sub strategies must match for
1254 this strategy to match.
1255 * **strategies** (list): Sub strategies
1256 * **any-strategies-match** (dict): Builds whenever any of the sub
1257 strategies match.
1258 * **strategies** (list): Sub strategies
1259 * **tags** (dict): Builds tags
1260 * **ignore-tags-newer-than** (int) The number of days since the tag
1261 was created before it is eligible for automatic building.
1262 (optional, default -1)
1263 * **ignore-tags-older-than** (int) The number of days since the tag
1264 was created after which it is no longer eligible for automatic
1265 building. (optional, default -1)
1266 * **change-request** (dict): Builds change requests / pull requests
1267 * **ignore-target-only-changes** (bool) Ignore rebuilding merge
1268 branches when only the target branch changed.
1269 (optional, default false)
1270 * **regular-branches** (bool): Builds regular branches whenever a
1271 change is detected. (optional, default None)
1272 * **skip-initial-build** (bool): Skip initial build on first branch
1273 indexing. (optional, default None)
1274 * **named-branches** (list): Builds named branches whenever a change
1275 is detected.
1276
1277 * **exact-name** (dict) Matches the name verbatim.
1278 * **name** (str) The name to match. (optional)
1279 * **case-sensitive** (bool) Check this box if the name should
1280 be matched case sensitively. (default false)
1281 * **regex-name** (dict) Matches the name against a regular
1282 expression.
1283
1284 * **regex** (str) A Java regular expression to restrict the
1285 names. Names that do not match the supplied regular
1286 expression will be ignored. (default `^.*$`)
1287 * **case-sensitive** (bool) Check this box if the name should
1288 be matched case sensitively. (default false)
1289 * **wildcards-name** (dict) Matches the name against an
1290 include/exclude set of wildcards.
1291
1292 * **includes** (str) Space-separated list of name patterns to
1293 consider. You may use `*` as a wildcard;
1294 for example: `master release*` (default `*`)
1295 * **excludes** (str) Name patterns to ignore even if matched
1296 by the includes list. For example: release (optional)
1297 * **raw** (dict): Injects raw BuildStrategy XML to use other build
1298 strategy plugins.
1299
1300 """
1301
1302 basic_build_strategies = "jenkins.branch.buildstrategies.basic"
1303 if data.get("build-strategies", None):
1304 bbs_data = data.get("build-strategies", None)
1305 bbs = XML.SubElement(xml_parent, "buildStrategies")
1306 else:
1307 bbs_data = data.get("strategies", None)
1308 bbs = XML.SubElement(xml_parent, "strategies")
1309 for bbs_list in bbs_data:
1310 if "all-strategies-match" in bbs_list:
1311 all_elem = XML.SubElement(
1312 bbs,
1313 "".join([basic_build_strategies, ".AllBranchBuildStrategyImpl"]),
1314 {"plugin": "basic-branch-build-strategies"},
1315 )
1316 build_strategies(all_elem, bbs_list["all-strategies-match"])
1317
1318 if "any-strategies-match" in bbs_list:
1319 any_elem = XML.SubElement(
1320 bbs,
1321 "".join([basic_build_strategies, ".AnyBranchBuildStrategyImpl"]),
1322 {"plugin": "basic-branch-build-strategies"},
1323 )
1324 build_strategies(any_elem, bbs_list["any-strategies-match"])
1325
1326 if "tags" in bbs_list:
1327 tags = bbs_list["tags"]
1328 tags_elem = XML.SubElement(
1329 bbs,
1330 "".join([basic_build_strategies, ".TagBuildStrategyImpl"]),
1331 {"plugin": "basic-branch-build-strategies"},
1332 )
1333
1334 newer_than = -1
1335 if "ignore-tags-newer-than" in tags and tags["ignore-tags-newer-than"] >= 0:
1336 newer_than = str(tags["ignore-tags-newer-than"] * 86400000)
1337 XML.SubElement(tags_elem, "atLeastMillis").text = str(newer_than)
1338
1339 older_than = -1
1340 if "ignore-tags-older-than" in tags and tags["ignore-tags-older-than"] >= 0:
1341 older_than = str(tags["ignore-tags-older-than"] * 86400000)
1342 XML.SubElement(tags_elem, "atMostMillis").text = str(older_than)
1343
1344 if bbs_list.get("regular-branches", False):
1345 XML.SubElement(
1346 bbs,
1347 "".join([basic_build_strategies, ".BranchBuildStrategyImpl"]),
1348 {"plugin": "basic-branch-build-strategies"},
1349 )
1350
1351 if bbs_list.get("skip-initial-build", False):
1352 XML.SubElement(
1353 bbs,
1354 "".join(
1355 [basic_build_strategies, ".SkipInitialBuildOnFirstBranchIndexing"]
1356 ),
1357 {"plugin": "basic-branch-build-strategies"},
1358 )
1359
1360 if "change-request" in bbs_list:
1361 cr = bbs_list["change-request"]
1362 cr_elem = XML.SubElement(
1363 bbs,
1364 "".join([basic_build_strategies, ".ChangeRequestBuildStrategyImpl"]),
1365 {"plugin": "basic-branch-build-strategies"},
1366 )
1367 itoc = cr.get("ignore-target-only-changes", False)
1368 XML.SubElement(cr_elem, "ignoreTargetOnlyChanges").text = str(itoc).lower()
1369
1370 if "named-branches" in bbs_list:
1371 named_branch_elem = XML.SubElement(
1372 bbs,
1373 "".join([basic_build_strategies, ".NamedBranchBuildStrategyImpl"]),
1374 {"plugin": "basic-branch-build-strategies"},
1375 )
1376
1377 filters = XML.SubElement(named_branch_elem, "filters")
1378
1379 for nb in bbs_list["named-branches"]:
1380 if "exact-name" in nb:
1381 exact_name_elem = XML.SubElement(
1382 filters,
1383 "".join(
1384 [
1385 basic_build_strategies,
1386 ".NamedBranchBuildStrategyImpl",
1387 "_-ExactNameFilter",
1388 ]
1389 ),
1390 )
1391 exact_name_mapping = [
1392 ("name", "name", ""),
1393 ("case-sensitive", "caseSensitive", False),
1394 ]
1395 helpers.convert_mapping_to_xml(
1396 exact_name_elem,
1397 nb["exact-name"],
1398 exact_name_mapping,
1399 fail_required=False,
1400 )
1401
1402 if "regex-name" in nb:
1403 regex_name_elem = XML.SubElement(
1404 filters,
1405 "".join(
1406 [
1407 basic_build_strategies,
1408 ".NamedBranchBuildStrategyImpl",
1409 "_-RegexNameFilter",
1410 ]
1411 ),
1412 )
1413 regex_name_mapping = [
1414 ("regex", "regex", "^.*$"),
1415 ("case-sensitive", "caseSensitive", False),
1416 ]
1417 helpers.convert_mapping_to_xml(
1418 regex_name_elem,
1419 nb["regex-name"],
1420 regex_name_mapping,
1421 fail_required=False,
1422 )
1423
1424 if "wildcards-name" in nb:
1425 wildcards_name_elem = XML.SubElement(
1426 filters,
1427 "".join(
1428 [
1429 basic_build_strategies,
1430 ".NamedBranchBuildStrategyImpl",
1431 "_-WildcardsNameFilter",
1432 ]
1433 ),
1434 )
1435 wildcards_name_mapping = [
1436 ("includes", "includes", "*"),
1437 ("excludes", "excludes", ""),
1438 ]
1439 helpers.convert_mapping_to_xml(
1440 wildcards_name_elem,
1441 nb["wildcards-name"],
1442 wildcards_name_mapping,
1443 fail_required=False,
1444 )
1445
1446 if "raw" in bbs_list:
1447 raw_xml = XML.fromstring(bbs_list["raw"].get("xml"))
1448 remove_ignorable_whitespace(raw_xml)
1449 XML.SubElement(bbs, None).append(raw_xml)
1450
1451
1452 def property_strategies(xml_parent, data):
1453 """Configure Basic Branch Property Strategies.
1454
1455 Requires the :jenkins-plugins:`Branch API Plugin <branch-api>`.
1456
1457 :arg dict property-strategies: Definition of property strategies. Either
1458 `named-branches` or `all-branches` may be specified, but not both.
1459
1460 * **all-branches** (list): A list of property strategy definitions
1461 for use with all branches.
1462
1463 * **suppress-scm-triggering** (dict):
1464 Suppresses automatic SCM triggering (optional).
1465
1466 * **branch-regex** (str):
1467 Regex matching branch names.
1468 Only these branches will be affected by the selected
1469 suppression strategy. Default ``^$``.
1470 * **suppress-strategy** (str):
1471 Select what to suppress for branches matching the regex.
1472 Valid values: ``suppress-nothing`` (default),
1473 ``suppress-branch-indexing``, or ``suppress-webhooks``.
1474
1475 .. note::
1476 Using ``suppress-scm-triggering: true`` is deprecated
1477 since Branch API 2.1045.v4ec3ed07b_e4f.
1478 * **pipeline-branch-durability-override** (str): Set a custom
1479 branch speed/durability level. Valid values:
1480 performance-optimized, survivable-nonatomic, or
1481 max-survivability (optional)
1482 Requires the :jenkins-plugins:`Pipeline Multibranch Plugin
1483 <workflow-multibranch>`
1484 * **trigger-build-on-pr-comment** (str or dict): The comment body to
1485 trigger a new build for a PR job when it is received. This
1486 is compiled as a case-insensitive regular expression, so
1487 use ``".*"`` to trigger a build on any comment whatsoever.
1488 (optional)
1489 If dictionary syntax is used, the option requires 2 fields:
1490 ``comment`` with the comment body and ``allow-untrusted-users``
1491 (bool) causing the plugin to skip checking if the comment author
1492 is a collaborator of the GitHub project.
1493 Requires the :jenkins-plugins:`GitHub PR Comment Build Plugin
1494 <github-pr-comment-build>`
1495 * **trigger-build-on-pr-review** (bool or dict): This property will
1496 cause a job for a pull request ``(PR-*)`` to be triggered
1497 immediately when a review is made on the PR in GitHub.
1498 This has no effect on jobs that are not for pull requests.
1499 (optional)
1500 If dictionary syntax is used, the option requires
1501 ``allow-untrusted-users`` (bool) causing the plugin to skip
1502 checking if the review author is a collaborator of the GitHub
1503 project.
1504 Requires the :jenkins-plugins:`GitHub PR Comment Build Plugin
1505 <github-pr-comment-build>`
1506 * **trigger-build-on-pr-update** (bool or dict): This property will
1507 cause a job for a pull request ``(PR-*)`` to be triggered
1508 immediately when the PR title or description is edited in
1509 GitHub. This has no effect on jobs that are not for pull
1510 requests. (optional)
1511 If dictionary syntax is used, the option requires
1512 ``allow-untrusted-users`` (bool) causing the plugin to skip
1513 checking if the update author is a collaborator of the GitHub
1514 project.
1515 Requires the :jenkins-plugins:`GitHub PR Comment Build Plugin
1516 <github-pr-comment-build>`
1517 * **named-branches** (dict): Named branches get different properties.
1518 Comprised of a list of defaults and a list of property strategy
1519 exceptions for use with specific branches.
1520
1521 * **defaults** (list): A list of property strategy definitions
1522 to be applied by default to all branches, unless overridden
1523 by an entry in `exceptions`
1524
1525 * **suppress-scm-triggering** (dict):
1526 Suppresses automatic SCM triggering (optional).
1527
1528 * **branch-regex** (str):
1529 Regex matching branch names.
1530 Only these branches will be affected by the selected
1531 suppression strategy. Default ``^$``.
1532 * **suppress-strategy** (str):
1533 Select what to suppress for branches matching the regex.
1534 Valid values: ``suppress-nothing`` (default),
1535 ``suppress-branch-indexing``, or ``suppress-webhooks``.
1536
1537 .. note::
1538 Using ``suppress-scm-triggering: true`` is deprecated
1539 since Branch API 2.1045.v4ec3ed07b_e4f.
1540 * **pipeline-branch-durability-override** (str): Set a custom
1541 branch speed/durability level. Valid values:
1542 performance-optimized, survivable-nonatomic, or
1543 max-survivability (optional)
1544 Requires the :jenkins-plugins:`Pipeline Multibranch Plugin
1545 <workflow-multibranch>`
1546 * **trigger-build-on-pr-comment** (str or dict): The comment body to
1547 trigger a new build for a PR job when it is received. This
1548 is compiled as a case-insensitive regular expression, so
1549 use ``".*"`` to trigger a build on any comment whatsoever.
1550 (optional)
1551 If dictionary syntax is used, the option accepts 2 fields:
1552 ``comment`` (str, required) with the comment body and
1553 ``allow-untrusted-users`` (bool, optional) causing the plugin
1554 to skip checking if the comment author is a collaborator of
1555 the GitHub project.
1556 Requires the :jenkins-plugins:`GitHub PR Comment Build Plugin
1557 <github-pr-comment-build>`
1558 * **trigger-build-on-pr-review** (bool or dict): This property will
1559 cause a job for a pull request ``(PR-*)`` to be triggered
1560 immediately when a review is made on the PR in GitHub.
1561 This has no effect on jobs that are not for pull requests.
1562 (optional)
1563 If dictionary syntax is used, the option requires
1564 ``allow-untrusted-users`` (bool) causing the plugin to skip
1565 checking if the review author is a collaborator of the GitHub
1566 project.
1567 Requires the :jenkins-plugins:`GitHub PR Comment Build Plugin
1568 <github-pr-comment-build>`
1569 * **trigger-build-on-pr-update** (bool or dict): This property will
1570 cause a job for a pull request ``(PR-*)`` to be triggered
1571 immediately when the PR title or description is edited in
1572 GitHub. This has no effect on jobs that are not for pull
1573 requests. (optional)
1574 If dictionary syntax is used, the option requires
1575 ``allow-untrusted-users`` (bool) causing the plugin to skip
1576 checking if the update author is a collaborator of the GitHub
1577 project.
1578 Requires the :jenkins-plugins:`GitHub PR Comment Build Plugin
1579 <github-pr-comment-build>`
1580
1581 * **exceptions** (list): A list of branch names and the property
1582 strategies to be used on that branch, instead of any listed
1583 in `defaults`.
1584
1585 * **exception** (dict): Defines exception
1586 * **branch-name** (str): Name of the branch to which these
1587 properties will be applied.
1588 * **properties** (list): A list of properties to apply to
1589 this branch.
1590
1591 * **suppress-scm-triggering** (dict):
1592 Suppresses automatic SCM triggering (optional).
1593
1594 * **branch-regex** (str):
1595 Regex matching branch names.
1596 Only these branches will be affected by the selected
1597 suppression strategy. Default ``^$``.
1598 * **suppress-strategy** (str):
1599 Select what to suppress for branches matching the regex.
1600 Valid values: ``suppress-nothing`` (default),
1601 ``suppress-branch-indexing``, or ``suppress-webhooks``.
1602
1603 .. note::
1604 Using ``suppress-scm-triggering: true`` is deprecated
1605 since Branch API 2.1045.v4ec3ed07b_e4f.
1606
1607 * **pipeline-branch-durability-override** (str): Set a
1608 custom branch speed/durability level. Valid values:
1609 performance-optimized, survivable-nonatomic, or
1610 max-survivability (optional)
1611 Requires the :jenkins-plugins:`Pipeline
1612 Multibranch Plugin <workflow-multibranch>`
1613 """
1614
1615 valid_prop_strats = ["all-branches", "named-branches"]
1616
1617 basic_property_strategies = "jenkins.branch"
1618
1619 prop_strats = data.get("property-strategies", None)
1620
1621 if prop_strats:
1622
1623 for prop_strat in prop_strats:
1624 if prop_strat not in valid_prop_strats:
1625 raise InvalidAttributeError(
1626 "property-strategies", prop_strat, valid_prop_strats
1627 )
1628 if len(prop_strats) > 1:
1629 raise JenkinsJobsException("Only one property strategy may be specified")
1630
1631 all_branches = prop_strats.get("all-branches", None)
1632 named_branches = prop_strats.get("named-branches", None)
1633
1634 if all_branches:
1635
1636 strat_elem = XML.SubElement(
1637 xml_parent,
1638 "strategy",
1639 {
1640 "class": "".join(
1641 [basic_property_strategies, ".DefaultBranchPropertyStrategy"]
1642 )
1643 },
1644 )
1645 props_elem = XML.SubElement(
1646 strat_elem, "properties", {"class": "java.util.Arrays$ArrayList"}
1647 )
1648 props_elem = XML.SubElement(
1649 props_elem,
1650 "a",
1651 {
1652 "class": "".join(
1653 [basic_property_strategies, ".BranchProperty-array"]
1654 )
1655 },
1656 )
1657
1658 apply_property_strategies(props_elem, all_branches)
1659
1660 elif named_branches:
1661
1662 strat_elem = XML.SubElement(
1663 xml_parent,
1664 "strategy",
1665 {
1666 "class": "".join(
1667 [
1668 basic_property_strategies,
1669 ".NamedExceptionsBranchPropertyStrategy",
1670 ]
1671 )
1672 },
1673 )
1674
1675 nbs_defaults = named_branches.get("defaults", None)
1676 if nbs_defaults:
1677
1678 props_elem = XML.SubElement(
1679 strat_elem,
1680 "defaultProperties",
1681 {"class": "java.util.Arrays$ArrayList"},
1682 )
1683 props_elem = XML.SubElement(
1684 props_elem,
1685 "a",
1686 {
1687 "class": "".join(
1688 [basic_property_strategies, ".BranchProperty-array"]
1689 )
1690 },
1691 )
1692
1693 apply_property_strategies(props_elem, nbs_defaults)
1694
1695 nbs_exceptions = named_branches.get("exceptions", None)
1696 if nbs_exceptions:
1697
1698 props_elem = XML.SubElement(
1699 strat_elem,
1700 "namedExceptions",
1701 {"class": "java.util.Arrays$ArrayList"},
1702 )
1703 props_elem = XML.SubElement(
1704 props_elem,
1705 "a",
1706 {
1707 "class": "".join(
1708 [
1709 basic_property_strategies,
1710 ".NamedExceptionsBranchPropertyStrategy$Named-array",
1711 ]
1712 )
1713 },
1714 )
1715
1716 for named_exception in nbs_exceptions:
1717 named_exception = named_exception.get("exception", None)
1718 if not named_exception:
1719 continue
1720
1721 exc_elem = XML.SubElement(
1722 props_elem,
1723 "".join(
1724 [
1725 basic_property_strategies,
1726 ".NamedExceptionsBranchPropertyStrategy_-Named",
1727 ]
1728 ),
1729 )
1730
1731 ne_branch_name = named_exception.get("branch-name", None)
1732 if ne_branch_name is not None:
1733 XML.SubElement(exc_elem, "name").text = ne_branch_name
1734
1735 ne_properties = named_exception.get("properties", None)
1736 if ne_properties:
1737 exc_elem = XML.SubElement(
1738 exc_elem, "props", {"class": "java.util.Arrays$ArrayList"}
1739 )
1740 exc_elem = XML.SubElement(
1741 exc_elem,
1742 "a",
1743 {
1744 "class": "".join(
1745 [basic_property_strategies, ".BranchProperty-array"]
1746 )
1747 },
1748 )
1749 apply_property_strategies(exc_elem, ne_properties)
1750
1751
1752 def apply_property_strategies(props_elem, props_list):
1753 # there are 3 locations at which property strategies can be defined:
1754 # globally (all-branches), defaults (named-branches), exceptions
1755 # (also named-branches)
1756
1757 basic_property_strategies = "jenkins.branch"
1758 workflow_multibranch = "org.jenkinsci.plugins.workflow.multibranch"
1759 pr_comment_build = "com.adobe.jenkins.github__pr__comment__build"
1760 # Valid options for the pipeline branch durability override.
1761 pbdo_map = collections.OrderedDict(
1762 [
1763 ("max-survivability", "MAX_SURVIVABILITY"),
1764 ("performance-optimized", "PERFORMANCE_OPTIMIZED"),
1765 ("survivable-nonatomic", "SURVIVABLE_NONATOMIC"),
1766 ]
1767 )
1768
1769 pcb_bool_opts = collections.OrderedDict(
1770 [
1771 ("trigger-build-on-pr-review", ".TriggerPRReviewBranchProperty"),
1772 ("trigger-build-on-pr-update", ".TriggerPRUpdateBranchProperty"),
1773 ]
1774 )
1775
1776 # valid options for suppress SCM trigger property
1777 # strategy name says what's blocked
1778 sst_map = collections.OrderedDict(
1779 [
1780 ("suppress-nothing", "NONE"),
1781 ("suppress-webhooks", "EVENTS"),
1782 ("suppress-branch-indexing", "INDEXING"),
1783 ]
1784 )
1785
1786 for dbs_list in props_list:
1787
1788 sst_val = dbs_list.get("suppress-scm-triggering", False)
1789 if sst_val:
1790 sst_elem = XML.SubElement(
1791 props_elem,
1792 "".join([basic_property_strategies, ".NoTriggerBranchProperty"]),
1793 )
1794
1795 if isinstance(sst_val, dict):
1796 if "branch-regex" not in sst_val:
1797 raise MissingAttributeError("suppress-scm-triggering[branch-regex]")
1798 if "suppression-strategy" not in sst_val:
1799 raise MissingAttributeError(
1800 "suppress-scm-triggering[suppression-strategy]"
1801 )
1802
1803 sst_ss_val = sst_val["suppression-strategy"]
1804 if not sst_map.get(sst_ss_val):
1805 raise InvalidAttributeError(
1806 "suppression-strategy", sst_ss_val, sst_map.keys()
1807 )
1808 XML.SubElement(sst_elem, "triggeredBranchesRegex").text = sst_val[
1809 "branch-regex"
1810 ]
1811 XML.SubElement(sst_elem, "strategy").text = sst_map[sst_ss_val]
1812
1813 elif isinstance(sst_val, bool):
1814 # no sub-elements in this case
1815 pass
1816 else:
1817 raise InvalidAttributeError("suppress-scm-triggering", sst_val)
1818
1819 pbdo_val = dbs_list.get("pipeline-branch-durability-override", None)
1820 if pbdo_val:
1821 if not pbdo_map.get(pbdo_val):
1822 raise InvalidAttributeError(
1823 "pipeline-branch-durability-override", pbdo_val, pbdo_map.keys()
1824 )
1825 pbdo_elem = XML.SubElement(
1826 props_elem,
1827 "".join([workflow_multibranch, ".DurabilityHintBranchProperty"]),
1828 {"plugin": "workflow-multibranch"},
1829 )
1830 XML.SubElement(pbdo_elem, "hint").text = pbdo_map.get(pbdo_val)
1831
1832 tbopc_val = dbs_list.get("trigger-build-on-pr-comment", None)
1833 if tbopc_val:
1834 tbopc_elem = XML.SubElement(
1835 props_elem,
1836 "".join([pr_comment_build, ".TriggerPRCommentBranchProperty"]),
1837 {"plugin": "github-pr-comment-build"},
1838 )
1839 if isinstance(tbopc_val, dict):
1840 if "comment" not in tbopc_val:
1841 raise MissingAttributeError(
1842 "trigger-build-on-pr-comment[comment]",
1843 pos=dbs_list.key_pos.get("trigger-build-on-pr-comment"),
1844 )
1845 XML.SubElement(tbopc_elem, "commentBody").text = tbopc_val["comment"]
1846 if tbopc_val.get("allow-untrusted-users", False):
1847 XML.SubElement(tbopc_elem, "allowUntrusted").text = "true"
1848 elif isinstance(tbopc_val, str):
1849 XML.SubElement(tbopc_elem, "commentBody").text = tbopc_val
1850 else:
1851 attr = "trigger-build-on-pr-comment"
1852 ctx = [Context(f"For attribute {attr!r}", dbs_list.key_pos.get(attr))]
1853 raise InvalidAttributeError(
1854 attr,
1855 tbopc_val,
1856 pos=dbs_list.value_pos.get(attr),
1857 ctx=ctx,
1858 )
1859 for opt in pcb_bool_opts:
1860 opt_value = dbs_list.get(opt, None)
1861 if opt_value:
1862 opt_elem = XML.SubElement(
1863 props_elem,
1864 "".join([pr_comment_build, pcb_bool_opts.get(opt)]),
1865 {"plugin": "github-pr-comment-build"},
1866 )
1867 if isinstance(opt_value, dict):
1868 if opt_value.get("allow-untrusted-users", False):
1869 XML.SubElement(opt_elem, "allowUntrusted").text = "true"
1870 elif isinstance(opt_value, bool):
1871 # no sub-elements in this case
1872 pass
1873 else:
1874 ctx = Context(f"For attribute {opt!r}", dbs_list.key_pos.get(opt))
1875 raise InvalidAttributeError(
1876 opt, opt_value, pos=dbs_list.value_pos.get(opt), ctx=[ctx]
1877 )
1878
1879
1880 def add_filter_branch_pr_behaviors(traits, data):
1881 """Configure Filter Branch PR behaviors
1882
1883 Requires the :jenkins-plugins:`SCM Filter Branch PR Plugin
1884 <scm-filter-branch-pr>`.
1885
1886 :arg list head-pr-filter-behaviors: Definition of filters.
1887
1888 * **head-pr-destined-regex** (dict): Filter by name incl. PR destined to
1889 this branch with regexp
1890
1891 * **branch-regexp** (str) Regular expression to filter branches and
1892 PRs (optional, default ".*")
1893 * **tag-regexp** (str) Regular expression to filter tags
1894 (optional, default "(?!.*)")
1895
1896 * **head-pr-destined-wildcard** (dict): Filter by name incl. PR
1897 destined to this branch with wildcard
1898
1899 * **branch-includes** (str) Wildcard expression to include branches
1900 and PRs (optional, default "*")
1901 * **tag-includes** (str) Wildcard expression to include tags
1902 (optional, default "")
1903 * **branch-excludes** (str) Wildcard expression to exclude branches
1904 and PRs (optional, default "")
1905 * **tag-excludes** (str) Wildcard expression to exclude tags
1906 (optional, default "*")
1907
1908 * **head-pr-originated-regex** (dict): Filter by name incl. PR destined
1909 to this branch with regexp
1910
1911 * **branch-regexp** (str) Regular expression to filter branches
1912 and PRs (optional, default ".*")
1913 * **tag-regexp** (str) Regular expression to filter tags
1914 (optional, default "(?!.*)")
1915
1916 * **head-pr-originated-wildcard** (dict): Filter by name incl. PR
1917 destined to this branch with wildcard
1918
1919 * **branch-includes** (str) Wildcard expression to include branches
1920 and PRs (optional, default "*")
1921 * **tag-includes** (str) Wildcard expression to include tags
1922 (optional, default "")
1923 * **branch-excludes** (str) Wildcard expression to exclude branches
1924 and PRs (optional, default "")
1925 * **tag-excludes** (str) Wildcard expression to exclude tags
1926 (optional, default "*")
1927 """
1928
1929 regexp_mapping = [
1930 ("branch-regexp", "regex", ".*"),
1931 ("tag-regexp", "tagRegex", "(?!.*)"),
1932 ]
1933 wildcard_mapping = [
1934 ("branch-includes", "includes", "*"),
1935 ("branch-excludes", "excludes", ""),
1936 ("tag-includes", "tagIncludes", ""),
1937 ("tag-excludes", "tagExcludes", "*"),
1938 ]
1939
1940 if data.get("head-pr-destined-regex"):
1941 rshf = XML.SubElement(
1942 traits,
1943 "net.gleske.scmfilter.impl.trait.RegexSCMHeadFilterTrait",
1944 {"plugin": "scm-filter-branch-pr"},
1945 )
1946 helpers.convert_mapping_to_xml(
1947 rshf, data.get("head-pr-destined-regex"), regexp_mapping, fail_required=True
1948 )
1949
1950 if data.get("head-pr-destined-wildcard"):
1951 wshf = XML.SubElement(
1952 traits,
1953 "net.gleske.scmfilter.impl.trait.WildcardSCMHeadFilterTrait",
1954 {"plugin": "scm-filter-branch-pr"},
1955 )
1956 helpers.convert_mapping_to_xml(
1957 wshf,
1958 data.get("head-pr-destined-wildcard"),
1959 wildcard_mapping,
1960 fail_required=True,
1961 )
1962
1963 if data.get("head-pr-originated-regex"):
1964 rsof = XML.SubElement(
1965 traits,
1966 "net.gleske.scmfilter.impl.trait.RegexSCMOriginFilterTrait",
1967 {"plugin": "scm-filter-branch-pr"},
1968 )
1969 helpers.convert_mapping_to_xml(
1970 rsof,
1971 data.get("head-pr-originated-regex"),
1972 regexp_mapping,
1973 fail_required=True,
1974 )
1975
1976 if data.get("head-pr-originated-wildcard"):
1977 wsof = XML.SubElement(
1978 traits,
1979 "net.gleske.scmfilter.impl.trait.WildcardSCMOriginFilterTrait",
1980 {"plugin": "scm-filter-branch-pr"},
1981 )
1982 helpers.convert_mapping_to_xml(
1983 wsof,
1984 data.get("head-pr-originated-wildcard"),
1985 wildcard_mapping,
1986 fail_required=True,
1987 )
1988
1989
1990 def add_filter_by_name_wildcard_behaviors(traits, data):
1991 """Configure branch filtering behaviors.
1992
1993 :arg dict filter-by-name-wildcard: Enable filter by name with wildcards.
1994 Requires the :jenkins-plugins:`SCM API Plugin <scm-api>`.
1995
1996 * **includes** ('str'): Space-separated list
1997 of name patterns to consider. You may use * as a wildcard;
1998 for example: `master release*`
1999 * **excludes** ('str'): Name patterns to
2000 ignore even if matched by the includes list.
2001 For example: `release*`
2002 """
2003 if data.get("filter-by-name-wildcard", None):
2004 wscmf_name = XML.SubElement(
2005 traits,
2006 "jenkins.scm.impl.trait.WildcardSCMHeadFilterTrait",
2007 {"plugin": "scm-api"},
2008 )
2009 wscmf_name_mapping = [
2010 ("includes", "includes", ""),
2011 ("excludes", "excludes", ""),
2012 ]
2013 helpers.convert_mapping_to_xml(
2014 wscmf_name,
2015 data.get("filter-by-name-wildcard", ""),
2016 wscmf_name_mapping,
2017 fail_required=True,
2018 )
2019
2020
2021 def add_notification_context_trait(traits, data):
2022 """Change the default GitHub check notification context from
2023 "continuous-integration/jenkins/SUFFIX" to a custom label / suffix.
2024 (set a label and suffix to true or false, optional)
2025
2026 Requires the :jenkins-plugins:`Github Custom Notification Context SCM
2027 Behaviour <github-scm-trait-notification-context>`.
2028
2029 :arg dict notification-context: Definition of notification-context. A
2030 `label` must be specified. `suffix` may be specified with true /
2031 false, default being true.
2032
2033 * **label** (str): The text of the context label for Github status
2034 notifications.
2035 * **suffix** (bool): Appends the relevant suffix to the context label
2036 based on the build type. '/pr-merge', '/pr-head' or '/branch'
2037 (optional, default true)
2038 """
2039 if data.get("notification-context", None):
2040 nc_trait = XML.SubElement(
2041 traits,
2042 "org.jenkinsci.plugins.githubScmTraitNotificationContext."
2043 "NotificationContextTrait",
2044 )
2045 nc = data.get("notification-context")
2046 nc_trait_label = XML.SubElement(nc_trait, "contextLabel")
2047 nc_trait_suffix = XML.SubElement(nc_trait, "typeSuffix")
2048 if isinstance(nc, str):
2049 nc_trait_label.text = nc
2050 nc_trait_suffix.text = "true"
2051 else:
2052 nc_trait_label.text = nc.get("label")
2053 nc_suffix = nc.get("suffix", None)
2054 if nc_suffix is None:
2055 nc_trait_suffix.text = "true"
2056 elif type(nc_suffix) is bool:
2057 nc_trait_suffix.text = str(nc_suffix).lower()
2058 else:
2059 nc_trait_suffix.text = nc_suffix
2060
2061
2062 def add_github_checks_traits(traits, data):
2063 """Enable and configure the usage of GitHub Checks API
2064
2065 Requires the :jenkins-plugins:`Github Checks <github-checks>` plugin.
2066
2067 :arg dict status-checks:
2068
2069 * **name** (str): The text of the context label for GitHub Checks entry
2070 * **skip** (bool): Skips publishing Checks (optional, default false)
2071 * **skip-branch-source-notifications** (bool): Disables the default
2072 option of publishing statuses through Status API
2073 (optional, default false)
2074 * **publish-unstable-as-neutral** (bool): Publishes UNSTABLE builds
2075 as neutral (not failed) checks
2076 (optional, default false)
2077 * **suppress-log-output** (bool): Suppresses sending build logs to GitHub
2078 (optional, default false)
2079 * **suppress-progress-updates** (bool): Suppresses updating build progress
2080 (optional, default false)
2081 * **verbose-logs** (bool): Enables sending build console logs to GitHub
2082 (optional, default false)
2083 """
2084 if data.get("status-checks", None):
2085 status_checks_section = data["status-checks"]
2086 if status_checks_section.get("verbose-logs", None):
2087 sct = XML.SubElement(
2088 traits,
2089 "io.jenkins.plugins.checks.github.config.GitHubSCMSourceChecksTrait",
2090 {"plugin": "github-checks"},
2091 )
2092 sct_mapping = [("verbose-logs", "verboseConsoleLog", "false")]
2093 helpers.convert_mapping_to_xml(
2094 sct, status_checks_section, sct_mapping, fail_required=True
2095 )
2096
2097 status_check_trait = XML.SubElement(
2098 traits,
2099 "io.jenkins.plugins.checks.github.status.GitHubSCMSourceStatusChecksTrait",
2100 {"plugin": "github-checks"},
2101 )
2102 status_check_trait_mapping = [
2103 ("skip", "skip", "false"),
2104 ("skip-branch-source-notifications", "skipNotifications", "false"),
2105 ("publish-unstable-as-neutral", "unstableBuildNeutral", "false"),
2106 ("name", "name", "Jenkins"),
2107 ("suppress-log-output", "suppressLogs", "false"),
2108 ("suppress-progress-updates", "skipProgressUpdates", "false"),
2109 ]
2110 helpers.convert_mapping_to_xml(
2111 status_check_trait,
2112 status_checks_section,
2113 status_check_trait_mapping,
2114 fail_required=True,
2115 )