Debian Codegraph @

jenkins_jobs/modules/builders.py

raw
1 # Copyright 2012 Hewlett-Packard Development Company, L.P.
2 # Copyright 2012 Varnish Software AS
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16
17 """
18 Builders define actions that the Jenkins job should execute. Examples
19 include shell scripts or maven targets. The ``builders`` attribute in
20 the :ref:`Job` definition accepts a list of builders to invoke. They
21 may be components defined below, locally defined macros (using the top
22 level definition of ``builder:``, or locally defined components found
23 via the ``jenkins_jobs.builders`` entry point.
24
25 **Component**: builders
26 :Macro: builder
27 :Entry Point: jenkins_jobs.builders
28
29 Example::
30
31 job:
32 name: test_job
33
34 builders:
35 - shell: "make test"
36
37 """
38
39 import logging
40 import xml.etree.ElementTree as XML
41
42 import six
43
44 from jenkins_jobs.errors import is_sequence
45 from jenkins_jobs.errors import InvalidAttributeError
46 from jenkins_jobs.errors import JenkinsJobsException
47 from jenkins_jobs.errors import MissingAttributeError
48 import jenkins_jobs.modules.base
49 import jenkins_jobs.modules.helpers as helpers
50 from jenkins_jobs.modules import hudson_model
51 from jenkins_jobs.modules.publishers import ssh
52 from jenkins_jobs.modules.publishers import cifs
53
54 logger = logging.getLogger(__name__)
55
56
57 def shell(registry, xml_parent, data):
58 """yaml: shell
59 Execute a shell command.
60
61 There are two ways of configuring the builder, with a plain string to
62 execute:
63
64 :arg str parameter: the shell command to execute
65
66 Or with a mapping that allows other parameters to be passed:
67
68 :arg str command: the shell command to execute
69 :arg int unstable-return:
70 the shell exit code to interpret as an unstable build result
71
72 Example:
73
74 .. literalinclude:: /../../tests/builders/fixtures/shell.yaml
75 :language: yaml
76
77 .. literalinclude::
78 /../../tests/builders/fixtures/shell-unstable-return.yaml
79 :language: yaml
80 """
81 shell = XML.SubElement(xml_parent, "hudson.tasks.Shell")
82 if isinstance(data, six.string_types):
83 XML.SubElement(shell, "command").text = data
84 else:
85 mappings = [
86 ("command", "command", None),
87 ("unstable-return", "unstableReturn", 0),
88 ]
89 helpers.convert_mapping_to_xml(shell, data, mappings, fail_required=True)
90
91
92 def python(registry, xml_parent, data):
93 """yaml: python
94 Execute a python command. Requires the Jenkins :jenkins-plugins:`Python plugin
95 <python>`.
96
97 :arg str parameter: the python command to execute
98
99 Example:
100
101 .. literalinclude:: /../../tests/builders/fixtures/python.yaml
102 :language: yaml
103
104 """
105 python = XML.SubElement(xml_parent, "hudson.plugins.python.Python")
106 XML.SubElement(python, "command").text = data
107
108
109 def copyartifact(registry, xml_parent, data):
110 """yaml: copyartifact
111
112 Copy artifact from another project. Requires the :jenkins-plugins:`Copy
113 Artifact plugin <copyartifact>`.
114
115 Please note using the multijob-build for which-build argument requires
116 the :jenkins-plugins:`Multijob plugin <jenkins-multijob-plugin>`
117
118 :arg str project: Project to copy from
119 :arg str filter: what files to copy
120 :arg str target: Target base directory for copy, blank means use workspace
121 :arg bool flatten: Flatten directories (default false)
122 :arg bool optional: If the artifact is missing (for any reason) and
123 optional is true, the build won't fail because of this builder
124 (default false)
125 :arg bool do-not-fingerprint: Disable automatic fingerprinting of copied
126 artifacts (default false)
127 :arg str which-build: which build to get artifacts from
128 (optional, default last-successful)
129
130 :which-build values:
131 * **last-successful**
132 * **last-completed**
133 * **specific-build**
134 * **last-saved**
135 * **upstream-build**
136 * **permalink**
137 * **workspace-latest**
138 * **build-param**
139 * **downstream-build**
140 * **multijob-build**
141
142 :arg str build-number: specifies the build number to get when
143 when specific-build is specified as which-build
144 :arg str permalink: specifies the permalink to get when
145 permalink is specified as which-build
146
147 :permalink values:
148 * **last**
149 * **last-stable**
150 * **last-successful**
151 * **last-failed**
152 * **last-unstable**
153 * **last-unsuccessful**
154
155 :arg bool stable: specifies to get only last stable build when
156 last-successful is specified as which-build
157 :arg bool fallback-to-last-successful: specifies to fallback to
158 last successful build when upstream-build is specified as which-build
159 :arg str param: specifies to use a build parameter to get the build when
160 build-param is specified as which-build
161 :arg str upstream-project-name: specifies the project name of downstream
162 when downstream-build is specified as which-build
163 :arg str upstream-build-number: specifies the number of the build to
164 find its downstream build when downstream-build is specified as
165 which-build
166 :arg str parameter-filters: Filter matching jobs based on these
167 parameters (optional)
168 :arg str exclude: Specify paths or patterns of artifacts to
169 exclude, even if specified in "Artifacts to copy". (default '')
170 :arg str result-var-suffix: The build number of the selected build
171 will be recorded into the variable named
172 COPYARTIFACT_BUILD_NUMBER_(SUFFIX)
173 for later build steps to reference. (default '')
174
175 Example:
176
177 .. literalinclude:: ../../tests/builders/fixtures/copy-artifact001.yaml
178 :language: yaml
179
180 Multijob Example:
181
182 .. literalinclude:: ../../tests/builders/fixtures/copy-artifact004.yaml
183 :language: yaml
184 """
185 t = XML.SubElement(xml_parent, "hudson.plugins.copyartifact.CopyArtifact")
186 mappings = [
187 # Warning: this only works with copy artifact version 1.26+,
188 # for copy artifact version 1.25- the 'projectName' element needs
189 # to be used instead of 'project'
190 ("project", "project", None),
191 ("filter", "filter", ""),
192 ("target", "target", ""),
193 ("flatten", "flatten", False),
194 ("optional", "optional", False),
195 ("do-not-fingerprint", "doNotFingerprintArtifacts", False),
196 ("parameter-filters", "parameters", ""),
197 ("exclude", "exclude", ""),
198 ("result-var-suffix", "resultVariableSuffix", ""),
199 ]
200 helpers.convert_mapping_to_xml(t, data, mappings, fail_required=True)
201 helpers.copyartifact_build_selector(t, data)
202
203
204 def change_assembly_version(registry, xml_parent, data):
205 """yaml: change-assembly-version
206 Change the assembly version.
207 Requires the Jenkins :jenkins-plugins:`Change Assembly Version
208 <change-assembly-version-plugin>`.
209
210 :arg str version: Set the new version number for replace (default 1.0.0)
211 :arg str assemblyFile: The file name to search (default AssemblyInfo.cs)
212
213 Minimal Example:
214
215 .. literalinclude::
216 /../../tests/builders/fixtures/changeassemblyversion-minimal.yaml
217 :language: yaml
218
219 Full Example:
220
221 .. literalinclude::
222 /../../tests/builders/fixtures/changeassemblyversion-full.yaml
223 :language: yaml
224 """
225
226 cav_builder_tag = (
227 "org.jenkinsci.plugins.changeassemblyversion." "ChangeAssemblyVersion"
228 )
229 cav = XML.SubElement(xml_parent, cav_builder_tag)
230 mappings = [
231 ("version", "task", "1.0.0"),
232 ("assembly-file", "assemblyFile", "AssemblyInfo.cs"),
233 ]
234 helpers.convert_mapping_to_xml(cav, data, mappings, fail_required=True)
235
236
237 def fingerprint(registry, xml_parent, data):
238 """yaml: fingerprint
239 Adds the ability to generate fingerprints as build steps instead of waiting
240 for a build to complete.
241
242 Requires the Jenkins :jenkins-plugins:`Fingerprint Plugin
243 <create-fingerprint>`.
244
245 :arg str targets: Files to fingerprint (default '')
246
247 Full Example:
248
249 .. literalinclude::
250 /../../tests/builders/fixtures/fingerprint-full.yaml
251 :language: yaml
252
253 Minimal Example:
254
255 .. literalinclude::
256 /../../tests/builders/fixtures/fingerprint-minimal.yaml
257 :language: yaml
258 """
259
260 fingerprint = XML.SubElement(
261 xml_parent, "hudson.plugins.createfingerprint.CreateFingerprint"
262 )
263 fingerprint.set("plugin", "create-fingerprint")
264
265 mapping = [("targets", "targets", "")]
266 helpers.convert_mapping_to_xml(fingerprint, data, mapping, fail_required=True)
267
268
269 def ant(registry, xml_parent, data):
270 """yaml: ant
271 Execute an ant target. Requires the Jenkins :jenkins-plugins:`Ant Plugin
272 <ant>`.
273
274 To setup this builder you can either reference the list of targets
275 or use named parameters. Below is a description of both forms:
276
277 *1) Listing targets:*
278
279 After the ant directive, simply pass as argument a space separated list
280 of targets to build.
281
282 :Parameter: space separated list of Ant targets
283
284 Example to call two Ant targets:
285
286 .. literalinclude:: ../../tests/builders/fixtures/ant001.yaml
287 :language: yaml
288
289 The build file would be whatever the Jenkins Ant Plugin is set to use
290 per default (i.e build.xml in the workspace root).
291
292 *2) Using named parameters:*
293
294 :arg str targets: the space separated list of ANT targets.
295 :arg str buildfile: the path to the ANT build file.
296 :arg list properties: Passed to ant script using -Dkey=value (optional)
297 :arg str ant-name: the name of the ant installation,
298 (default 'default') (optional)
299 :arg str java-opts: java options for ant, can have multiples,
300 must be in quotes (optional)
301
302
303 Example specifying the build file too and several targets:
304
305 .. literalinclude:: ../../tests/builders/fixtures/ant002.yaml
306 :language: yaml
307 """
308 ant = XML.SubElement(xml_parent, "hudson.tasks.Ant")
309
310 if type(data) is str:
311 # Support for short form: -ant: "target"
312 data = {"targets": data}
313
314 mapping = [
315 ("targets", "targets", None),
316 ("buildfile", "buildFile", None),
317 ("ant-name", "antName", "default"),
318 ]
319 helpers.convert_mapping_to_xml(ant, data, mapping, fail_required=False)
320
321 mapping = []
322 for setting, value in sorted(data.items()):
323 if setting == "properties":
324 properties = value
325 prop_string = ""
326 for prop, val in properties.items():
327 prop_string += "%s=%s\n" % (prop, val)
328 mapping.append(("", "properties", prop_string))
329 if setting == "java-opts":
330 jopt_string = "\n".join(value)
331 mapping.append(("", "antOpts", jopt_string))
332
333 helpers.convert_mapping_to_xml(ant, data, mapping, fail_required=True)
334
335
336 def trigger_remote(registry, xml_parent, data):
337 """yaml: trigger-remote
338 Trigger build of job on remote Jenkins instance.
339
340 Requires the Jenkins :jenkins-plugins:`Parameterized Remote Trigger Plugin
341 <Parameterized-Remote-Trigger>`
342
343 Please note that this plugin requires system configuration on the Jenkins
344 Master that is unavailable from individual job views; specifically, one
345 must add remote jenkins servers whose 'Display Name' field are what make up
346 valid fields on the `remote-jenkins-name` attribute below.
347
348 :arg str remote-jenkins-name: the remote Jenkins server (required)
349 :arg str job: the Jenkins project to trigger on the remote Jenkins server
350 (required)
351 :arg bool should-not-fail-build: if true, remote job failure will not lead
352 current job to fail (default false)
353 :arg bool prevent-remote-build-queue: if true, wait to trigger remote
354 builds until no other builds (default false)
355 :arg bool block: whether to wait for the trigger jobs to finish or not
356 (default true)
357 :arg str poll-interval: polling interval in seconds for checking statues of
358 triggered remote job, only necessary if current job is configured to
359 block (default 10)
360 :arg str connection-retry-limit: number of connection attempts to remote
361 Jenkins server before giving up. (default 5)
362 :arg bool enhanced-logging: if this option is enabled,
363 the console output of the remote job is also logged. (default false)
364 :arg str predefined-parameters: predefined parameters to send to the remote
365 job when triggering it (optional)
366 :arg str property-file: file in workspace of current job containing
367 additional parameters to be set on remote job
368 (optional)
369
370 Example:
371
372 .. literalinclude::
373 /../../tests/builders/fixtures/trigger-remote/trigger-remote001.yaml
374 :language: yaml
375 """
376 triggerr = XML.SubElement(
377 xml_parent,
378 "org.jenkinsci.plugins."
379 "ParameterizedRemoteTrigger."
380 "RemoteBuildConfiguration",
381 )
382
383 mappings = [
384 ("remote-jenkins-name", "remoteJenkinsName", None),
385 ("token", "token", ""),
386 ("job", "job", None),
387 ("should-not-fail-build", "shouldNotFailBuild", False),
388 ("poll-interval", "pollInterval", 10),
389 ("connection-retry-limit", "connectionRetryLimit", 5),
390 ("enhanced-logging", "enhancedLogging", False),
391 ("prevent-remote-build-queue", "preventRemoteBuildQueue", False),
392 ("block", "blockBuildUntilComplete", True),
393 ]
394 helpers.convert_mapping_to_xml(triggerr, data, mappings, fail_required=True)
395
396 mappings = []
397 if "predefined-parameters" in data:
398 parameters = data.get("predefined-parameters", "")
399 XML.SubElement(triggerr, "parameters").text = parameters
400 params_list = parameters.split("\n")
401
402 parameter_list = XML.SubElement(triggerr, "parameterList")
403 for param in params_list:
404 if param == "":
405 continue
406 tmp = XML.SubElement(parameter_list, "string")
407 tmp.text = param
408
409 if "property-file" in data and data["property-file"] != "":
410 mappings.append(("", "loadParamsFromFile", "true"))
411 mappings.append(("property-file", "parameterFile", None))
412 else:
413 mappings.append(("", "loadParamsFromFile", "false"))
414
415 mappings.append(("", "overrideAuth", "false"))
416
417 helpers.convert_mapping_to_xml(triggerr, data, mappings, fail_required=True)
418
419
420 def trigger_builds(registry, xml_parent, data):
421 """yaml: trigger-builds
422 Trigger builds of other jobs.
423
424 Requires the Jenkins :jenkins-plugins:`Parameterized Trigger Plugin
425 <parameterized-trigger>`.
426
427 :arg list project: the Jenkins project to trigger
428 :arg str predefined-parameters: key/value pairs to be passed to the job
429 (optional)
430 :arg list bool-parameters:
431
432 :Bool:
433 * **name** (`str`) -- Parameter name
434 * **value** (`bool`) -- Value to set (default false)
435
436 :arg str property-file:
437 Pass properties from file to the other job (optional)
438 :arg bool property-file-fail-on-missing:
439 Don't trigger if any files are missing (default true)
440 :arg bool current-parameters: Whether to include the parameters passed
441 to the current build to the triggered job (default false)
442 :arg str node-label-name: Define a name for the NodeLabel parameter to be
443 set. Used in conjunction with node-label. Requires NodeLabel Parameter
444 Plugin (optional)
445 :arg str node-label: Label of the nodes where build should be triggered.
446 Used in conjunction with node-label-name. Requires NodeLabel Parameter
447 Plugin (optional)
448 :arg str restrict-matrix-project: Filter that restricts the subset
449 of the combinations that the triggered job will run (optional)
450 :arg bool svn-revision: Whether to pass the svn revision to the triggered
451 job (optional)
452 :arg dict git-revision: Passes git revision to the triggered job
453 (optional).
454
455 * **combine-queued-commits** (bool): Whether to combine queued git
456 hashes or not (default false)
457 :arg bool block: whether to wait for the triggered jobs to finish or not
458 (default false)
459 :arg dict block-thresholds: Fail builds and/or mark as failed or unstable
460 based on thresholds. Only apply if block parameter is true (optional)
461
462 :block-thresholds:
463 * **build-step-failure-threshold** (`str`) - build step failure
464 threshold, valid values are 'never', 'SUCCESS', 'UNSTABLE', or
465 'FAILURE'. (default 'FAILURE')
466 * **unstable-threshold** (`str`) - unstable threshold, valid
467 values are 'never', 'SUCCESS', 'UNSTABLE', or 'FAILURE'.
468 (default 'UNSTABLE')
469 * **failure-threshold** (`str`) - overall failure threshold, valid
470 values are 'never', 'SUCCESS', 'UNSTABLE', or 'FAILURE'.
471 (default 'FAILURE')
472
473 :arg bool same-node: Use the same node for the triggered builds that was
474 used for this build (optional)
475 :arg list parameter-factories: list of parameter factories
476
477 :Factory:
478 * **factory** (`str`) **filebuild** -- For every property file,
479 invoke one build
480 * **file-pattern** (`str`) -- File wildcard pattern
481 * **no-files-found-action** (`str`) -- Action to perform when
482 no files found. Valid values 'FAIL', 'SKIP', or 'NOPARMS'.
483 (default 'SKIP')
484
485 :Factory:
486 * **factory** (`str`) **binaryfile** -- For every matching
487 file, invoke one build
488 * **file-pattern** (`str`) -- Artifact ID of the artifact
489 * **no-files-found-action** (`str`) -- Action to perform when
490 no files found. Valid values 'FAIL', 'SKIP', or 'NOPARMS'.
491 (default 'SKIP')
492
493 :Factory:
494 * **factory** (`str`) **counterbuild** -- Invoke i=0...N builds
495 * **from** (`int`) -- Artifact ID of the artifact
496 * **to** (`int`) -- Version of the artifact
497 * **step** (`int`) -- Classifier of the artifact
498 * **parameters** (`str`) -- KEY=value pairs, one per line
499 (default '')
500 * **validation-fail** (`str`) -- Action to perform when
501 stepping validation fails. Valid values 'FAIL', 'SKIP', or
502 'NOPARMS'. (default 'FAIL')
503
504 :Factory:
505 * **factory** (`str`) **allnodesforlabel** -- Trigger a build
506 on all nodes having specific label. Requires NodeLabel
507 Parameter Plugin (optional)
508 * **name** (`str`) -- Name of the parameter to set (optional)
509 * **node-label** (`str`) -- Label of the nodes where build
510 should be triggered
511 * **ignore-offline-nodes** (`bool`) -- Don't trigger build on
512 offline nodes (default true)
513
514 :Factory:
515 * **factory** (`str`) **allonlinenodes** -- Trigger a build on
516 every online node. Requires NodeLabel Parameter Plugin (optional)
517
518 Examples:
519
520 Basic usage with yaml list of projects.
521
522 .. literalinclude::
523 /../../tests/builders/fixtures/trigger-builds/project-list.yaml
524 :language: yaml
525
526 Basic usage with passing svn revision through.
527
528 .. literalinclude:: /../../tests/builders/fixtures/trigger-builds001.yaml
529 :language: yaml
530
531 Basic usage with passing git revision through.
532
533 .. literalinclude:: /../../tests/builders/fixtures/trigger-builds006.yaml
534 :language: yaml
535
536 Example with all supported parameter factories.
537
538 .. literalinclude::
539 /../../tests/builders/fixtures/trigger-builds-configfactory-multi.yaml
540 :language: yaml
541 """
542 tbuilder = XML.SubElement(
543 xml_parent, "hudson.plugins.parameterizedtrigger." "TriggerBuilder"
544 )
545 configs = XML.SubElement(tbuilder, "configs")
546 for project_def in data:
547 if "project" not in project_def or project_def["project"] == "":
548 logger.debug("No project specified - skipping trigger-build")
549 continue
550 tconfig = XML.SubElement(
551 configs,
552 "hudson.plugins.parameterizedtrigger." "BlockableBuildTriggerConfig",
553 )
554 tconfigs = XML.SubElement(tconfig, "configs")
555 if project_def.get("current-parameters"):
556 XML.SubElement(
557 tconfigs,
558 "hudson.plugins.parameterizedtrigger." "CurrentBuildParameters",
559 )
560 if project_def.get("svn-revision"):
561 XML.SubElement(
562 tconfigs,
563 "hudson.plugins.parameterizedtrigger."
564 "SubversionRevisionBuildParameters",
565 )
566
567 if project_def.get("git-revision"):
568 helpers.append_git_revision_config(tconfigs, project_def["git-revision"])
569
570 if project_def.get("same-node"):
571 XML.SubElement(
572 tconfigs, "hudson.plugins.parameterizedtrigger." "NodeParameters"
573 )
574 if "property-file" in project_def:
575 params = XML.SubElement(
576 tconfigs, "hudson.plugins.parameterizedtrigger." "FileBuildParameters"
577 )
578 mapping = [
579 ("property-file", "propertiesFile", None),
580 ("property-file-fail-on-missing", "failTriggerOnMissing", True),
581 ]
582 helpers.convert_mapping_to_xml(
583 params, project_def, mapping, fail_required=True
584 )
585
586 if "predefined-parameters" in project_def:
587 params = XML.SubElement(
588 tconfigs,
589 "hudson.plugins.parameterizedtrigger." "PredefinedBuildParameters",
590 )
591 mapping = [("predefined-parameters", "properties", None)]
592 helpers.convert_mapping_to_xml(
593 params, project_def, mapping, fail_required=True
594 )
595
596 if "bool-parameters" in project_def:
597 params = XML.SubElement(
598 tconfigs, "hudson.plugins.parameterizedtrigger." "BooleanParameters"
599 )
600 configs = XML.SubElement(params, "configs")
601 for bool_param in project_def["bool-parameters"]:
602 param = XML.SubElement(
603 configs,
604 "hudson.plugins.parameterizedtrigger." "BooleanParameterConfig",
605 )
606 mapping = [("name", "name", None), ("value", "value", False)]
607 helpers.convert_mapping_to_xml(
608 param, bool_param, mapping, fail_required=True
609 )
610
611 if "node-label-name" in project_def and "node-label" in project_def:
612 node = XML.SubElement(
613 tconfigs,
614 "org.jvnet.jenkins.plugins."
615 "nodelabelparameter.parameterizedtrigger."
616 "NodeLabelBuildParameter",
617 )
618 mapping = [
619 ("node-label-name", "name", None),
620 ("node-label", "nodeLabel", None),
621 ]
622 helpers.convert_mapping_to_xml(
623 node, project_def, mapping, fail_required=True
624 )
625
626 if "restrict-matrix-project" in project_def:
627 params = XML.SubElement(
628 tconfigs,
629 "hudson.plugins.parameterizedtrigger."
630 "matrix.MatrixSubsetBuildParameters",
631 )
632 mapping = [("restrict-matrix-project", "filter", None)]
633 helpers.convert_mapping_to_xml(
634 params, project_def, mapping, fail_required=True
635 )
636
637 if len(list(tconfigs)) == 0:
638 tconfigs.set("class", "java.util.Collections$EmptyList")
639
640 if "parameter-factories" in project_def:
641 fconfigs = XML.SubElement(tconfig, "configFactories")
642
643 supported_factories = [
644 "filebuild",
645 "binaryfile",
646 "counterbuild",
647 "allnodesforlabel",
648 "allonlinenodes",
649 ]
650 supported_actions = ["SKIP", "NOPARMS", "FAIL"]
651 for factory in project_def["parameter-factories"]:
652
653 if factory["factory"] not in supported_factories:
654 raise InvalidAttributeError(
655 "factory", factory["factory"], supported_factories
656 )
657
658 if factory["factory"] == "filebuild":
659 params = XML.SubElement(
660 fconfigs,
661 "hudson.plugins.parameterizedtrigger."
662 "FileBuildParameterFactory",
663 )
664 if factory["factory"] == "binaryfile":
665 params = XML.SubElement(
666 fconfigs,
667 "hudson.plugins.parameterizedtrigger."
668 "BinaryFileParameterFactory",
669 )
670 mapping = [("parameter-name", "parameterName", None)]
671 helpers.convert_mapping_to_xml(
672 params, factory, mapping, fail_required=True
673 )
674
675 if (
676 factory["factory"] == "filebuild"
677 or factory["factory"] == "binaryfile"
678 ):
679 mapping = [
680 ("file-pattern", "filePattern", None),
681 (
682 "no-files-found-action",
683 "noFilesFoundAction",
684 "SKIP",
685 supported_actions,
686 ),
687 ]
688 helpers.convert_mapping_to_xml(
689 params, factory, mapping, fail_required=True
690 )
691
692 if factory["factory"] == "counterbuild":
693 params = XML.SubElement(
694 fconfigs,
695 "hudson.plugins.parameterizedtrigger."
696 "CounterBuildParameterFactory",
697 )
698 mapping = [
699 ("from", "from", None),
700 ("to", "to", None),
701 ("step", "step", None),
702 ("parameters", "paramExpr", ""),
703 (
704 "validation-fail",
705 "validationFail",
706 "FAIL",
707 supported_actions,
708 ),
709 ]
710 helpers.convert_mapping_to_xml(
711 params, factory, mapping, fail_required=True
712 )
713
714 if factory["factory"] == "allnodesforlabel":
715 params = XML.SubElement(
716 fconfigs,
717 "org.jvnet.jenkins.plugins.nodelabelparameter."
718 "parameterizedtrigger."
719 "AllNodesForLabelBuildParameterFactory",
720 )
721 mapping = [
722 ("name", "name", ""),
723 ("node-label", "nodeLabel", None),
724 ("ignore-offline-nodes", "ignoreOfflineNodes", True),
725 ]
726 helpers.convert_mapping_to_xml(
727 params, factory, mapping, fail_required=True
728 )
729
730 if factory["factory"] == "allonlinenodes":
731 params = XML.SubElement(
732 fconfigs,
733 "org.jvnet.jenkins.plugins.nodelabelparameter."
734 "parameterizedtrigger."
735 "AllNodesBuildParameterFactory",
736 )
737
738 projects = XML.SubElement(tconfig, "projects")
739 if isinstance(project_def["project"], list):
740 projects.text = ",".join(project_def["project"])
741 else:
742 projects.text = project_def["project"]
743
744 mapping = [
745 ("", "condition", "ALWAYS"),
746 ("", "triggerWithNoParameters", False),
747 ("", "buildAllNodesWithLabel", False),
748 ]
749 helpers.convert_mapping_to_xml(tconfig, {}, mapping, fail_required=True)
750
751 block = project_def.get("block", False)
752 if block:
753 block = XML.SubElement(tconfig, "block")
754 supported_thresholds = [
755 [
756 "build-step-failure-threshold",
757 "buildStepFailureThreshold",
758 "FAILURE",
759 ],
760 ["unstable-threshold", "unstableThreshold", "UNSTABLE"],
761 ["failure-threshold", "failureThreshold", "FAILURE"],
762 ]
763 supported_threshold_values = [
764 "never",
765 hudson_model.SUCCESS["name"],
766 hudson_model.UNSTABLE["name"],
767 hudson_model.FAILURE["name"],
768 ]
769 thrsh = project_def.get("block-thresholds", False)
770 for toptname, txmltag, tvalue in supported_thresholds:
771 if thrsh:
772 tvalue = thrsh.get(toptname, tvalue)
773 if tvalue.lower() == supported_threshold_values[0]:
774 continue
775 if tvalue.upper() not in supported_threshold_values:
776 raise InvalidAttributeError(
777 toptname, tvalue, supported_threshold_values
778 )
779 th = XML.SubElement(block, txmltag)
780 mapping = [
781 ("name", "name", None),
782 ("ordinal", "ordinal", None),
783 ("color", "color", None),
784 ("", "completeBuild", True),
785 ]
786 helpers.convert_mapping_to_xml(
787 th,
788 hudson_model.THRESHOLDS[tvalue.upper()],
789 mapping,
790 fail_required=True,
791 )
792
793 # If configs is empty, remove the entire tbuilder tree.
794 if len(configs) == 0:
795 logger.debug("Pruning empty TriggerBuilder tree.")
796 xml_parent.remove(tbuilder)
797
798
799 def builders_from(registry, xml_parent, data):
800 """yaml: builders-from
801 Use builders from another project.
802
803 Requires the Jenkins :jenkins-plugins:`Template Project Plugin
804 <template-project>`.
805
806 :arg str projectName: the name of the other project
807
808 Example:
809
810 .. literalinclude:: ../../tests/builders/fixtures/builders-from.yaml
811 :language: yaml
812 """
813 pbs = XML.SubElement(xml_parent, "hudson.plugins.templateproject.ProxyBuilder")
814 mapping = [("", "projectName", data)]
815 helpers.convert_mapping_to_xml(pbs, {}, mapping, fail_required=True)
816
817
818 def http_request(registry, xml_parent, data):
819 """yaml: http-request
820 This plugin sends a http request to an url with some parameters.
821
822 Requires the Jenkins :jenkins-plugins:`HTTP Request Plugin
823 <http_request>`.
824
825 :arg str url: Specify an URL to be requested (required)
826 :arg str mode: The http mode of the request (default GET)
827
828 :mode values:
829 * **GET**
830 * **POST**
831 * **PUT**
832 * **DELETE**
833 * **HEAD**
834 :arg str content-type: Add 'Content-type: foo' HTTP request headers
835 where foo is the http content-type the request is using.
836 (default NOT_SET)
837 :arg str accept-type: Add 'Accept: foo' HTTP request headers
838 where foo is the http content-type to accept (default NOT_SET)
839
840 :content-type and accept-type values:
841 * **NOT_SET**
842 * **TEXT_HTML**
843 * **APPLICATION_JSON**
844 * **APPLICATION_TAR**
845 * **APPLICATION_ZIP**
846 * **APPLICATION_OCTETSTREAM**
847 :arg str output-file: Name of the file in which to write response data
848 (default '')
849 :arg int time-out: Specify a timeout value in seconds (default 0)
850 :arg bool console-log: This allows you to turn off writing the response
851 body to the log (default false)
852 :arg bool pass-build: Should build parameters be passed to the URL
853 being called (default false)
854 :arg str valid-response-codes: Configure response code to mark an
855 execution as success. You can configure simple code such as "200"
856 or multiple codes separated by comma(',') e.g. "200,404,500"
857 Interval of codes should be in format From:To e.g. "100:399".
858 The default (as if empty) is to fail to 4xx and 5xx.
859 That means success from 100 to 399 "100:399"
860 To ignore any response code use "100:599". (default '')
861 :arg str valid-response-content: If set response must contain this string
862 to mark an execution as success (default '')
863 :arg str authentication-key: Authentication that will be used before this
864 request. Authentications are created in global configuration under a
865 key name that is selected here.
866 :arg list custom-headers: list of header parameters
867
868 :custom-header:
869 * **name** (`str`) -- Name of the header
870 * **value** (`str`) -- Value of the header
871
872 Example:
873
874 .. literalinclude:: ../../tests/builders/fixtures/http-request-minimal.yaml
875 :language: yaml
876
877 .. literalinclude::
878 ../../tests/builders/fixtures/http-request-full.yaml
879 :language: yaml
880 """
881
882 http_request = XML.SubElement(
883 xml_parent, "jenkins.plugins.http__request.HttpRequest"
884 )
885 http_request.set("plugin", "http_request")
886
887 valid_modes = ["GET", "POST", "PUT", "DELETE", "HEAD"]
888 valid_types = [
889 "NOT_SET",
890 "TEXT_HTML",
891 "APPLICATION_JSON",
892 "APPLICATION_TAR",
893 "APPLICATION_ZIP",
894 "APPLICATION_OCTETSTREAM",
895 ]
896
897 mappings = [
898 ("url", "url", None),
899 ("mode", "httpMode", "GET", valid_modes),
900 ("content-type", "contentType", "NOT_SET", valid_types),
901 ("accept-type", "acceptType", "NOT_SET", valid_types),
902 ("output-file", "outputFile", ""),
903 ("console-log", "consoleLogResponseBody", False),
904 ("pass-build", "passBuildParameters", False),
905 ("time-out", "timeout", 0),
906 ("valid-response-codes", "validResponseCodes", ""),
907 ("valid-response-content", "validResponseContent", ""),
908 ]
909 helpers.convert_mapping_to_xml(http_request, data, mappings, fail_required=True)
910
911 if "authentication-key" in data:
912 XML.SubElement(http_request, "authentication").text = data["authentication-key"]
913
914 if "custom-headers" in data:
915 customHeader = XML.SubElement(http_request, "customHeaders")
916 header_mappings = [("name", "name", None), ("value", "value", None)]
917 for customhead in data["custom-headers"]:
918 pair = XML.SubElement(customHeader, "pair")
919 helpers.convert_mapping_to_xml(
920 pair, customhead, header_mappings, fail_required=True
921 )
922
923
924 def inject(registry, xml_parent, data):
925 """yaml: inject
926 Inject an environment for the job.
927
928 Requires the Jenkins :jenkins-plugins:`EnvInject Plugin <envinject>`.
929
930 :arg str properties-file: the name of the property file (optional)
931 :arg str properties-content: the properties content (optional)
932 :arg str script-file: the name of a script file to run (optional)
933 :arg str script-content: the script content (optional)
934
935 Example:
936
937 .. literalinclude:: ../../tests/builders/fixtures/inject.yaml
938 :language: yaml
939 """
940 eib = XML.SubElement(xml_parent, "EnvInjectBuilder")
941 info = XML.SubElement(eib, "info")
942 mapping = [
943 ("properties-file", "propertiesFilePath", None),
944 ("properties-content", "propertiesContent", None),
945 ("script-file", "scriptFilePath", None),
946 ("script-content", "scriptContent", None),
947 ]
948 helpers.convert_mapping_to_xml(info, data, mapping, fail_required=False)
949
950
951 def kmap(registry, xml_parent, data):
952 """yaml: kmap
953 Publish mobile applications to your Keivox KMAP Private Mobile App Store.
954
955 Requires the Jenkins :jenkins-plugins:`Keivox KMAP Private Mobile App Store
956 Plugin <kmap-jenkins>`.
957
958 :arg str username: KMAP's user email with permissions to upload/publish
959 applications to KMAP (required)
960 :arg str password: Password for the KMAP user uploading/publishing
961 applications (required)
962 :arg str url: KMAP's url. This url must always end with "/kmap-client/".
963 For example: http://testing.example.org/kmap-client/ (required)
964 :arg str categories: Categories' names. If you want to add the application
965 to more than one category, write the categories between commas.
966 (required)
967 :arg str file-path: Path to the application's file (required)
968 :arg str app-name: KMAP's application name (required)
969 :arg str bundle: Bundle indentifier (default '')
970 :arg str version: Application's version (required)
971 :arg str description: Application's description (default '')
972 :arg str icon-path: Path to the application's icon (default '')
973 :arg bool publish-optional: Publish application after it has been uploaded
974 to KMAP (default false)
975
976 :publish-optional:
977 * **groups** ('str') -- groups' names to publish the application
978 (default '')
979 * **users** ('str') -- users' names to publish the application
980 (default '')
981 * **notify-users** ('bool') -- Send notifications to the users and
982 groups when publishing the application (default false)
983
984 Minimal Example:
985
986 .. literalinclude:: ../../tests/builders/fixtures/kmap-minimal.yaml
987 :language: yaml
988
989 Full Example:
990
991 .. literalinclude:: ../../tests/builders/fixtures/kmap-full.yaml
992 :language: yaml
993 """
994 kmap = XML.SubElement(xml_parent, "org.jenkinsci.plugins.KmapJenkinsBuilder")
995
996 kmap.set("plugin", "kmap-jenkins")
997 publish = data.get("publish-optional", False)
998
999 mapping = [
1000 ("username", "username", None),
1001 ("password", "password", None),
1002 ("url", "kmapClient", None),
1003 ("categories", "categories", None),
1004 ("file-path", "filePath", None),
1005 ("app-name", "appName", None),
1006 ("bundle", "bundle", ""),
1007 ("version", "version", None),
1008 ("description", "description", ""),
1009 ("icon-path", "iconPath", ""),
1010 ]
1011 helpers.convert_mapping_to_xml(kmap, data, mapping, fail_required=True)
1012
1013 if publish is True:
1014 publish_optional = XML.SubElement(kmap, "publishOptional")
1015 publish_mapping = [
1016 ("groups", "teams", ""),
1017 ("users", "users", ""),
1018 ("notify-users", "sendNotifications", False),
1019 ]
1020 helpers.convert_mapping_to_xml(
1021 publish_optional, data, publish_mapping, fail_required=True
1022 )
1023
1024
1025 def artifact_resolver(registry, xml_parent, data):
1026 """yaml: artifact-resolver
1027 Allows one to resolve artifacts from a maven repository like nexus
1028 (without having maven installed)
1029
1030 Requires the Jenkins :jenkins-plugins:`Repository Connector Plugin
1031 <repository-connector>`.
1032
1033 :arg bool fail-on-error: Whether to fail the build on error (default false)
1034 :arg bool repository-logging: Enable repository logging (default false)
1035 :arg str target-directory: Where to resolve artifacts to (required)
1036 :arg list artifacts: list of artifacts to resolve
1037
1038 :Artifact:
1039 * **group-id** (`str`) -- Group ID of the artifact (required)
1040 * **artifact-id** (`str`) -- Artifact ID of the artifact (required)
1041 * **version** (`str`) -- Version of the artifact (required)
1042 * **classifier** (`str`) -- Classifier of the artifact (default '')
1043 * **extension** (`str`) -- Extension of the artifact
1044 (default 'jar')
1045 * **target-file-name** (`str`) -- What to name the artifact
1046 (default '')
1047
1048 Minimal Example:
1049
1050 .. literalinclude::
1051 ../../tests/builders/fixtures/artifact-resolver-minimal.yaml
1052 :language: yaml
1053
1054 Full Example:
1055
1056 .. literalinclude::
1057 ../../tests/builders/fixtures/artifact-resolver-full.yaml
1058 :language: yaml
1059 """
1060 ar = XML.SubElement(
1061 xml_parent, "org.jvnet.hudson.plugins.repositoryconnector.ArtifactResolver"
1062 )
1063 mapping = [
1064 ("target-directory", "targetDirectory", None),
1065 ("fail-on-error", "failOnError", False),
1066 ("repository-logging", "enableRepoLogging", False),
1067 ("", "snapshotUpdatePolicy", "never"),
1068 ("", "releaseUpdatePolicy", "never"),
1069 ("", "snapshotChecksumPolicy", "warn"),
1070 ("", "releaseChecksumPolicy", "warn"),
1071 ]
1072 helpers.convert_mapping_to_xml(ar, data, mapping, fail_required=True)
1073
1074 artifact_top = XML.SubElement(ar, "artifacts")
1075 artifacts = data["artifacts"]
1076 artifacts_mapping = [
1077 ("group-id", "groupId", None),
1078 ("artifact-id", "artifactId", None),
1079 ("version", "version", None),
1080 ("classifier", "classifier", ""),
1081 ("extension", "extension", "jar"),
1082 ("target-file-name", "targetFileName", ""),
1083 ]
1084 for artifact in artifacts:
1085 rcartifact = XML.SubElement(
1086 artifact_top, "org.jvnet.hudson.plugins.repositoryconnector.Artifact"
1087 )
1088 helpers.convert_mapping_to_xml(
1089 rcartifact, artifact, artifacts_mapping, fail_required=True
1090 )
1091
1092
1093 def doxygen(registry, xml_parent, data):
1094 """yaml: doxygen
1095 Builds doxygen HTML documentation.
1096
1097 Requires the Jenkins :jenkins-plugins:`Doxygen plugin <doxygen>`.
1098
1099 :arg str doxyfile: The doxyfile path (required)
1100 :arg str install: The doxygen installation to use (required)
1101 :arg bool ignore-failure: Keep executing build even on doxygen generation
1102 failure (default false)
1103 :arg bool unstable-warning: Mark the build as unstable if warnings are
1104 generated (default false)
1105
1106 Example:
1107
1108 .. literalinclude:: /../../tests/builders/fixtures/doxygen001.yaml
1109 :language: yaml
1110
1111 """
1112 doxygen = XML.SubElement(xml_parent, "hudson.plugins.doxygen.DoxygenBuilder")
1113 mappings = [
1114 ("doxyfile", "doxyfilePath", None),
1115 ("install", "installationName", None),
1116 ("ignore-failure", "continueOnBuildFailure", False),
1117 ("unstable-warning", "unstableIfWarnings", False),
1118 ]
1119 helpers.convert_mapping_to_xml(doxygen, data, mappings, fail_required=True)
1120
1121
1122 def gradle(registry, xml_parent, data):
1123 """yaml: gradle
1124 Execute gradle tasks.
1125
1126 Requires the Jenkins :jenkins-plugins:`Gradle Plugin <gradle>`.
1127
1128 :arg str tasks: List of tasks to execute
1129 :arg str gradle-name: Use a custom gradle name (default '')
1130 :arg bool wrapper: use gradle wrapper (default false)
1131 :arg bool executable: make gradlew executable (default false)
1132 :arg list switches: Switches for gradle, can have multiples
1133 :arg bool use-root-dir: Whether to run the gradle script from the
1134 top level directory or from a different location (default false)
1135 :arg str root-build-script-dir: If your workspace has the
1136 top-level build.gradle in somewhere other than the module
1137 root directory, specify the path (relative to the module
1138 root) here, such as ${workspace}/parent/ instead of just
1139 ${workspace}.
1140 :arg str build-file: name of gradle build script (default 'build.gradle')
1141 :arg bool pass-system-properties: Pass all parameters as
1142 System properties (default false)
1143 :arg bool pass-project-properties: Pass all parameters as
1144 Project properties (default false)
1145
1146 Example:
1147
1148 .. literalinclude:: ../../tests/builders/fixtures/gradle.yaml
1149 :language: yaml
1150 """
1151 gradle = XML.SubElement(xml_parent, "hudson.plugins.gradle.Gradle")
1152
1153 XML.SubElement(gradle, "description").text = ""
1154
1155 mappings = [
1156 ("build-file", "buildFile", "build.gradle"),
1157 ("tasks", "tasks", None),
1158 ("root-build-script-dir", "rootBuildScriptDir", ""),
1159 ("gradle-name", "gradleName", ""),
1160 ("wrapper", "useWrapper", False),
1161 ("executable", "makeExecutable", False),
1162 ("use-root-dir", "fromRootBuildScriptDir", False),
1163 ("pass-system-properties", "passAllAsSystemProperties", False),
1164 ("pass-project-properties", "passAllAsProjectProperties", False),
1165 ]
1166 helpers.convert_mapping_to_xml(gradle, data, mappings, fail_required=True)
1167
1168 XML.SubElement(gradle, "switches").text = "\n".join(data.get("switches", []))
1169
1170
1171 def _groovy_common_scriptSource(data):
1172 """Helper function to generate the XML element common to groovy builders."""
1173
1174 scriptSource = XML.Element("scriptSource")
1175 if "command" in data and "file" in data:
1176 raise JenkinsJobsException("Use just one of 'command' or 'file'")
1177
1178 if "command" in data:
1179 mapping = [("command", "command", None)]
1180 helpers.convert_mapping_to_xml(scriptSource, data, mapping, fail_required=True)
1181 scriptSource.set("class", "hudson.plugins.groovy.StringScriptSource")
1182 elif "file" in data:
1183 mapping = [("file", "scriptFile", None)]
1184 helpers.convert_mapping_to_xml(scriptSource, data, mapping, fail_required=True)
1185 scriptSource.set("class", "hudson.plugins.groovy.FileScriptSource")
1186 else:
1187 raise JenkinsJobsException("A groovy command or file is required")
1188
1189 return scriptSource
1190
1191
1192 def groovy(registry, xml_parent, data):
1193 """yaml: groovy
1194 Execute a groovy script or command.
1195
1196 Requires the Jenkins :jenkins-plugins:`Groovy Plugin <groovy>`.
1197
1198 :arg str file: Groovy file to run. (Alternative: you can chose a command
1199 instead)
1200 :arg str command: Groovy command to run. (Alternative: you can chose a
1201 script file instead)
1202 :arg str version: Groovy version to use. (default '(Default)')
1203 :arg str parameters: Parameters for the Groovy executable. (default '')
1204 :arg str script-parameters: These parameters will be passed to the script.
1205 (default '')
1206 :arg str properties: Instead of passing properties using the -D parameter
1207 you can define them here. (default '')
1208 :arg str java-opts: Direct access to JAVA_OPTS. Properties allows only
1209 -D properties, while sometimes also other properties like -XX need to
1210 be setup. It can be done here. This line is appended at the end of
1211 JAVA_OPTS string. (default '')
1212 :arg str class-path: Specify script classpath here. Each line is one
1213 class path item. (default '')
1214
1215 Minimal Example:
1216
1217 .. literalinclude:: ../../tests/builders/fixtures/groovy-minimal.yaml
1218 :language: yaml
1219
1220
1221 Full Example:
1222
1223 .. literalinclude:: ../../tests/builders/fixtures/groovy-full.yaml
1224 :language: yaml
1225 """
1226
1227 root_tag = "hudson.plugins.groovy.Groovy"
1228 groovy = XML.SubElement(xml_parent, root_tag)
1229 groovy.append(_groovy_common_scriptSource(data))
1230
1231 mappings = [
1232 ("version", "groovyName", "(Default)"),
1233 ("parameters", "parameters", ""),
1234 ("script-parameters", "scriptParameters", ""),
1235 ("properties", "properties", ""),
1236 ("java-opts", "javaOpts", ""),
1237 ("class-path", "classPath", ""),
1238 ]
1239 helpers.convert_mapping_to_xml(groovy, data, mappings, fail_required=True)
1240
1241
1242 def system_groovy(registry, xml_parent, data):
1243 """yaml: system-groovy
1244 Execute a system groovy script or command.
1245
1246 Requires the Jenkins :jenkins-plugins:`Groovy Plugin <groovy>`.
1247
1248 :arg str file: Groovy file to run. (Alternative: you can chose a command
1249 instead)
1250 :arg str command: Groovy command to run. (Alternative: you can choose a
1251 script file instead)
1252 :arg bool sandbox: Execute script inside of groovy sandbox (>=2.0)
1253 (default false)
1254 :arg str bindings: Define variable bindings (in the properties file
1255 format). Specified variables can be addressed from the script.
1256 (optional)
1257 :arg list class-path: List of script class paths.
1258 (optional)
1259
1260 Examples:
1261
1262 .. literalinclude:: ../../tests/builders/fixtures/system-groovy001.yaml
1263 :language: yaml
1264 .. literalinclude:: ../../tests/builders/fixtures/system-groovy002.yaml
1265 :language: yaml
1266 """
1267 root_tag = "hudson.plugins.groovy.SystemGroovy"
1268 sysgroovy = XML.SubElement(xml_parent, root_tag)
1269 if "file" in data:
1270 scriptSource = _groovy_common_scriptSource(data)
1271 if "command" in data:
1272 scriptSource = XML.Element("source")
1273 scriptSource.set("class", "hudson.plugins.groovy.StringSystemScriptSource")
1274 script = XML.SubElement(scriptSource, "script")
1275 mapping = [("command", "script", None), ("sandbox", "sandbox", False)]
1276 helpers.convert_mapping_to_xml(script, data, mapping, fail_required=True)
1277 classpath = XML.SubElement(script, "classpath")
1278 classpaths = data.get("class-path", [])
1279 if isinstance(classpaths, str):
1280 classpaths = [classpaths]
1281 for path in classpaths:
1282 entry = XML.SubElement(classpath, "entry")
1283 XML.SubElement(entry, "url").text = path
1284 sysgroovy.append(scriptSource)
1285 mapping = [("bindings", "bindings", "")]
1286 helpers.convert_mapping_to_xml(sysgroovy, data, mapping, fail_required=True)
1287
1288
1289 def batch(registry, xml_parent, data):
1290 """yaml: batch
1291 Execute a batch command.
1292
1293 :Parameter: the batch command to execute
1294
1295 Example:
1296
1297 .. literalinclude:: ../../tests/builders/fixtures/batch.yaml
1298 :language: yaml
1299 """
1300 batch = XML.SubElement(xml_parent, "hudson.tasks.BatchFile")
1301 XML.SubElement(batch, "command").text = data
1302
1303
1304 def powershell(registry, xml_parent, data):
1305 """yaml: powershell
1306 Execute a powershell command.
1307
1308 Requires the :jenkins-plugins:`Powershell Plugin <powershell>`.
1309
1310 :Parameter: the powershell command to execute
1311
1312 Example:
1313
1314 .. literalinclude:: ../../tests/builders/fixtures/powershell.yaml
1315 :language: yaml
1316 """
1317 ps = XML.SubElement(xml_parent, "hudson.plugins.powershell.PowerShell")
1318 XML.SubElement(ps, "command").text = data
1319
1320
1321 def msbuild(registry, xml_parent, data):
1322 """yaml: msbuild
1323 Build .NET project using msbuild.
1324
1325 Requires the Jenkins :jenkins-plugins:'MSBuild Plugin <msbuild>`.
1326
1327 :arg str msbuild-version: which msbuild configured in Jenkins to use
1328 (default '(Default)')
1329 :arg str solution-file: location of the solution file to build (required)
1330 :arg str extra-parameters: extra parameters to pass to msbuild (default '')
1331 :arg bool pass-build-variables: should build variables be passed
1332 to msbuild (default true)
1333 :arg bool continue-on-build-failure: should the build continue if
1334 msbuild returns an error (default false)
1335 :arg bool unstable-if-warnings: If set to true and warnings on compilation,
1336 the build will be unstable (>=1.20) (default false)
1337
1338 Full Example:
1339
1340 .. literalinclude:: ../../tests/builders/fixtures/msbuild-full.yaml
1341 :language: yaml
1342
1343 Minimal Example:
1344
1345 .. literalinclude:: ../../tests/builders/fixtures/msbuild-minimal.yaml
1346 :language: yaml
1347 """
1348 msbuilder = XML.SubElement(xml_parent, "hudson.plugins.msbuild.MsBuildBuilder")
1349 msbuilder.set("plugin", "msbuild")
1350
1351 mapping = [
1352 ("msbuild-version", "msBuildName", "(Default)"),
1353 ("solution-file", "msBuildFile", None),
1354 ("extra-parameters", "cmdLineArgs", ""),
1355 ("pass-build-variables", "buildVariablesAsProperties", True),
1356 ("continue-on-build-failure", "continueOnBuildFailure", False),
1357 ("unstable-if-warnings", "unstableIfWarnings", False),
1358 ]
1359 helpers.convert_mapping_to_xml(msbuilder, data, mapping, fail_required=True)
1360
1361
1362 def create_builders(registry, step):
1363 dummy_parent = XML.Element("dummy")
1364 registry.dispatch("builder", dummy_parent, step)
1365 return list(dummy_parent)
1366
1367
1368 def conditional_step(registry, xml_parent, data):
1369 """yaml: conditional-step
1370 Conditionally execute some build steps.
1371
1372 Requires the Jenkins :jenkins-plugins:`Conditional BuildStep Plugin
1373 <conditional-buildstep>`.
1374
1375 Depending on the number of declared steps, a `Conditional step (single)`
1376 or a `Conditional steps (multiple)` is created in Jenkins.
1377
1378 :arg str condition-kind: Condition kind that must be verified before the
1379 steps are executed. Valid values and their additional attributes are
1380 described in the conditions_ table.
1381 :arg str on-evaluation-failure: What should be the outcome of the build
1382 if the evaluation of the condition fails. Possible values are `fail`,
1383 `mark-unstable`, `run-and-mark-unstable`, `run` and `dont-run`.
1384 (default 'fail').
1385 :arg list steps: List of steps to run if the condition is verified. Items
1386 in the list can be any builder known by Jenkins Job Builder.
1387
1388 .. _conditions:
1389
1390 ================== ====================================================
1391 Condition kind Description
1392 ================== ====================================================
1393 always Condition is always verified
1394 never Condition is never verified
1395 boolean-expression Run the step if the expression expends to a
1396 representation of true
1397
1398 :condition-expression: Expression to expand (required)
1399 build-cause Run if the current build has a specific cause
1400
1401 :cause: The cause why the build was triggered.
1402 Following causes are supported -
1403
1404 :USER_CAUSE: build was triggered by a manual
1405 interaction. (default)
1406 :SCM_CAUSE: build was triggered by a SCM change.
1407 :TIMER_CAUSE: build was triggered by a timer.
1408 :CLI_CAUSE: build was triggered by via CLI interface
1409 :REMOTE_CAUSE: build was triggered via remote
1410 interface.
1411 :UPSTREAM_CAUSE: build was triggered by an upstream
1412 project.
1413
1414 Following supported if XTrigger plugin installed:
1415
1416 :FS_CAUSE: build was triggered by a file system
1417 change (FSTrigger Plugin).
1418 :URL_CAUSE: build was triggered by a URL change
1419 (URLTrigger Plugin)
1420 :IVY_CAUSE: build triggered by an Ivy dependency
1421 version has change (IvyTrigger Plugin)
1422 :SCRIPT_CAUSE: build was triggered by a script
1423 (ScriptTrigger Plugin)
1424 :BUILDRESULT_CAUSE: build was triggered by a
1425 result of another job (BuildResultTrigger Plugin)
1426 :exclusive-cause: (bool) There might by multiple
1427 causes causing a build to be triggered, with
1428 this true, the cause must be the only one
1429 causing this build this build to be triggered.
1430 (default false)
1431 day-of-week Only run on specific days of the week.
1432
1433 :day-selector: Days you want the build to run on.
1434 Following values are supported -
1435
1436 :weekend: Saturday and Sunday (default).
1437 :weekday: Monday - Friday.
1438 :select-days: Selected days, defined by 'days'
1439 below.
1440 :days: True for days for which the build should
1441 run. Definition needed only for 'select-days'
1442 day-selector, at the same level as day-selector.
1443 Define the days to run under this.
1444
1445 :SUN: Run on Sunday (default false)
1446 :MON: Run on Monday (default false)
1447 :TUES: Run on Tuesday (default false)
1448 :WED: Run on Wednesday (default false)
1449 :THURS: Run on Thursday (default false)
1450 :FRI: Run on Friday (default false)
1451 :SAT: Run on Saturday (default false)
1452 :use-build-time: (bool) Use the build time instead of
1453 the the time that the condition is evaluated.
1454 (default false)
1455 execution-node Run only on selected nodes.
1456
1457 :nodes: (list) List of nodes to execute on. (required)
1458 strings-match Run the step if two strings match
1459
1460 :condition-string1: First string (optional)
1461 :condition-string2: Second string (optional)
1462 :condition-case-insensitive: Case insensitive
1463 (default false)
1464 current-status Run the build step if the current build status is
1465 within the configured range
1466
1467 :condition-worst: Accepted values are SUCCESS,
1468 UNSTABLE, FAILURE, NOT_BUILD, ABORTED
1469 (default SUCCESS)
1470 :condition-best: Accepted values are SUCCESS,
1471 UNSTABLE, FAILURE, NOT_BUILD, ABORTED
1472 (default SUCCESS)
1473
1474 shell Run the step if the shell command succeed
1475
1476 :condition-command: Shell command to execute
1477 (optional)
1478 windows-shell Similar to shell, except that commands will be
1479 executed by cmd, under Windows
1480
1481 :condition-command: Command to execute (optional)
1482 file-exists Run the step if a file exists
1483
1484 :condition-filename: Check existence of this file
1485 (required)
1486 :condition-basedir: If condition-filename is
1487 relative, it will be considered relative to
1488 either `workspace`, `artifact-directory`,
1489 or `jenkins-home`. (default 'workspace')
1490 files-match Run if one or more files match the selectors.
1491
1492 :include-pattern: (list str) List of Includes
1493 Patterns. Since the separator in the patterns is
1494 hardcoded as ',', any use of ',' would need
1495 escaping. (optional)
1496 :exclude-pattern: (list str) List of Excludes
1497 Patterns. Since the separator in the patterns is
1498 hardcoded as ',', any use of ',' would need
1499 escaping. (optional)
1500 :condition-basedir: Accepted values are `workspace`,
1501 `artifact-directory`, or `jenkins-home`.
1502 (default 'workspace')
1503 num-comp Run if the numerical comparison is true.
1504
1505 :lhs: Left Hand Side. Must evaluate to a number.
1506 (required)
1507 :rhs: Right Hand Side. Must evaluate to a number.
1508 (required)
1509 :comparator: Accepted values are `less-than`,
1510 `greater-than`, `equal`, `not-equal`,
1511 `less-than-equal`, `greater-than-equal`.
1512 (default 'less-than')
1513 regex-match Run if the Expression matches the Label.
1514
1515 :regex: The regular expression used to match the label
1516 (optional)
1517 :label: The label that will be tested by the regular
1518 expression. (optional)
1519 time Only run during a certain period of the day.
1520
1521 :earliest-hour: Starting hour (default "09")
1522 :earliest-min: Starting min (default "00")
1523 :latest-hour: Ending hour (default "17")
1524 :latest-min: Ending min (default "30")
1525 :use-build-time: (bool) Use the build time instead of
1526 the the time that the condition is evaluated.
1527 (default false)
1528 not Run the step if the inverse of the condition-operand
1529 is true
1530
1531 :condition-operand: Condition to evaluate. Can be
1532 any supported conditional-step condition. (required)
1533 and Run the step if logical and of all conditional-operands
1534 is true
1535
1536 :condition-operands: (list) Conditions to evaluate.
1537 Can be any supported conditional-step condition.
1538 (required)
1539 or Run the step if logical or of all conditional-operands
1540 is true
1541
1542 :condition-operands: (list) Conditions to evaluate.
1543 Can be any supported conditional-step condition.
1544 (required)
1545 ================== ====================================================
1546
1547 Examples:
1548
1549 .. literalinclude::
1550 /../../tests/builders/fixtures/conditional-step-multiple-steps.yaml
1551 :language: yaml
1552 .. literalinclude::
1553 /../../tests/builders/fixtures/conditional-step-success-failure.yaml
1554 :language: yaml
1555 .. literalinclude::
1556 /../../tests/builders/fixtures/conditional-step-not-file-exists.yaml
1557 :language: yaml
1558 .. literalinclude::
1559 /../../tests/builders/fixtures/conditional-step-day-of-week001.yaml
1560 :language: yaml
1561 .. literalinclude::
1562 /../../tests/builders/fixtures/conditional-step-day-of-week003.yaml
1563 :language: yaml
1564 .. literalinclude::
1565 /../../tests/builders/fixtures/conditional-step-time.yaml
1566 :language: yaml
1567 .. literalinclude::
1568 /../../tests/builders/fixtures/conditional-step-regex-match.yaml
1569 :language: yaml
1570 .. literalinclude::
1571 /../../tests/builders/fixtures/conditional-step-or.yaml
1572 :language: yaml
1573 .. literalinclude::
1574 /../../tests/builders/fixtures/conditional-step-and.yaml
1575 :language: yaml
1576 """
1577
1578 def build_condition(cdata, cond_root_tag, condition_tag):
1579 kind = cdata["condition-kind"]
1580 ctag = XML.SubElement(cond_root_tag, condition_tag)
1581 core_prefix = "org.jenkins_ci.plugins.run_condition.core."
1582 logic_prefix = "org.jenkins_ci.plugins.run_condition.logic."
1583 if kind == "always":
1584 ctag.set("class", core_prefix + "AlwaysRun")
1585 elif kind == "never":
1586 ctag.set("class", core_prefix + "NeverRun")
1587 elif kind == "boolean-expression":
1588 ctag.set("class", core_prefix + "BooleanCondition")
1589 mapping = [("condition-expression", "token", None)]
1590 helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
1591 elif kind == "build-cause":
1592 ctag.set("class", core_prefix + "CauseCondition")
1593 cause_list = (
1594 "USER_CAUSE",
1595 "SCM_CAUSE",
1596 "TIMER_CAUSE",
1597 "CLI_CAUSE",
1598 "REMOTE_CAUSE",
1599 "UPSTREAM_CAUSE",
1600 "FS_CAUSE",
1601 "URL_CAUSE",
1602 "IVY_CAUSE",
1603 "SCRIPT_CAUSE",
1604 "BUILDRESULT_CAUSE",
1605 )
1606 mapping = [
1607 ("cause", "buildCause", "USER_CAUSE", cause_list),
1608 ("exclusive-cause", "exclusiveCause", False),
1609 ]
1610 helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
1611 elif kind == "day-of-week":
1612 ctag.set("class", core_prefix + "DayCondition")
1613 day_selector_class_prefix = core_prefix + "DayCondition$"
1614 day_selector_classes = {
1615 "weekend": day_selector_class_prefix + "Weekend",
1616 "weekday": day_selector_class_prefix + "Weekday",
1617 "select-days": day_selector_class_prefix + "SelectDays",
1618 }
1619 day_selector = cdata.get("day-selector", "weekend")
1620 if day_selector not in day_selector_classes:
1621 raise InvalidAttributeError(
1622 "day-selector", day_selector, day_selector_classes
1623 )
1624 day_selector_tag = XML.SubElement(ctag, "daySelector")
1625 day_selector_tag.set("class", day_selector_classes[day_selector])
1626 if day_selector == "select-days":
1627 days_tag = XML.SubElement(day_selector_tag, "days")
1628 day_tag_text = (
1629 "org.jenkins__ci.plugins.run__condition." "core.DayCondition_-Day"
1630 )
1631 inp_days = cdata.get("days") if cdata.get("days") else {}
1632 days = ["SUN", "MON", "TUES", "WED", "THURS", "FRI", "SAT"]
1633 for day_no, day in enumerate(days, 1):
1634 day_tag = XML.SubElement(days_tag, day_tag_text)
1635 mapping = [("", "day", day_no), (day, "selected", False)]
1636 helpers.convert_mapping_to_xml(
1637 day_tag, inp_days, mapping, fail_required=True
1638 )
1639 mapping = [("use-build-time", "useBuildTime", False)]
1640 helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
1641 elif kind == "execution-node":
1642 ctag.set("class", core_prefix + "NodeCondition")
1643 allowed_nodes_tag = XML.SubElement(ctag, "allowedNodes")
1644 for node in cdata["nodes"]:
1645 mapping = [("", "string", node)]
1646 helpers.convert_mapping_to_xml(
1647 allowed_nodes_tag, cdata, mapping, fail_required=True
1648 )
1649 elif kind == "strings-match":
1650 ctag.set("class", core_prefix + "StringsMatchCondition")
1651 mapping = [
1652 ("condition-string1", "arg1", ""),
1653 ("condition-string2", "arg2", ""),
1654 ("condition-case-insensitive", "ignoreCase", False),
1655 ]
1656 helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
1657 elif kind == "current-status":
1658 ctag.set("class", core_prefix + "StatusCondition")
1659 wr = XML.SubElement(ctag, "worstResult")
1660 wr_name = cdata.get("condition-worst", "SUCCESS")
1661 if wr_name not in hudson_model.THRESHOLDS:
1662 raise InvalidAttributeError(
1663 "condition-worst", wr_name, hudson_model.THRESHOLDS.keys()
1664 )
1665 wr_threshold = hudson_model.THRESHOLDS[wr_name]
1666 mapping = [
1667 ("name", "name", None),
1668 ("ordinal", "ordinal", None),
1669 ("color", "color", "color"),
1670 ("complete", "completeBuild", None),
1671 ]
1672 helpers.convert_mapping_to_xml(
1673 wr, wr_threshold, mapping, fail_required=True
1674 )
1675 br = XML.SubElement(ctag, "bestResult")
1676 br_name = cdata.get("condition-best", "SUCCESS")
1677 if br_name not in hudson_model.THRESHOLDS:
1678 raise InvalidAttributeError(
1679 "condition-best", br_name, hudson_model.THRESHOLDS.keys()
1680 )
1681 br_threshold = hudson_model.THRESHOLDS[br_name]
1682 mapping = [
1683 ("name", "name", None),
1684 ("ordinal", "ordinal", None),
1685 ("color", "color", "color"),
1686 ("complete", "completeBuild", None),
1687 ]
1688 helpers.convert_mapping_to_xml(
1689 br, br_threshold, mapping, fail_required=True
1690 )
1691 elif kind == "shell":
1692 ctag.set(
1693 "class",
1694 "org.jenkins_ci.plugins.run_condition.contributed." "ShellCondition",
1695 )
1696 mapping = [("condition-command", "command", "")]
1697 helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
1698 elif kind == "windows-shell":
1699 ctag.set(
1700 "class",
1701 "org.jenkins_ci.plugins.run_condition.contributed."
1702 "BatchFileCondition",
1703 )
1704 mapping = [("condition-command", "command", "")]
1705 helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
1706 elif kind == "file-exists" or kind == "files-match":
1707 if kind == "file-exists":
1708 ctag.set("class", core_prefix + "FileExistsCondition")
1709 mapping = [("condition-filename", "file", None)]
1710 helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
1711 else:
1712 ctag.set("class", core_prefix + "FilesMatchCondition")
1713 XML.SubElement(ctag, "includes").text = ",".join(
1714 cdata.get("include-pattern", "")
1715 )
1716 XML.SubElement(ctag, "excludes").text = ",".join(
1717 cdata.get("exclude-pattern", "")
1718 )
1719 basedir_class_prefix = (
1720 "org.jenkins_ci.plugins.run_condition." "common.BaseDirectory$"
1721 )
1722 basedir_classes = {
1723 "workspace": basedir_class_prefix + "Workspace",
1724 "artifact-directory": basedir_class_prefix + "ArtifactsDir",
1725 "jenkins-home": basedir_class_prefix + "JenkinsHome",
1726 }
1727 basedir = cdata.get("condition-basedir", "workspace")
1728 if basedir not in basedir_classes:
1729 raise InvalidAttributeError(
1730 "condition-basedir", basedir, basedir_classes
1731 )
1732 XML.SubElement(ctag, "baseDir").set("class", basedir_classes[basedir])
1733 elif kind == "num-comp":
1734 ctag.set("class", core_prefix + "NumericalComparisonCondition")
1735 mapping = [("lhs", "lhs", None), ("rhs", "rhs", None)]
1736 helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
1737 comp_class_prefix = core_prefix + "NumericalComparisonCondition$"
1738 comp_classes = {
1739 "less-than": comp_class_prefix + "LessThan",
1740 "greater-than": comp_class_prefix + "GreaterThan",
1741 "equal": comp_class_prefix + "EqualTo",
1742 "not-equal": comp_class_prefix + "NotEqualTo",
1743 "less-than-equal": comp_class_prefix + "LessThanOrEqualTo",
1744 "greater-than-equal": comp_class_prefix + "GreaterThanOrEqualTo",
1745 }
1746 comp = cdata.get("comparator", "less-than")
1747 if comp not in comp_classes:
1748 raise InvalidAttributeError("comparator", comp, comp_classes)
1749 XML.SubElement(ctag, "comparator").set("class", comp_classes[comp])
1750 elif kind == "regex-match":
1751 ctag.set("class", core_prefix + "ExpressionCondition")
1752 mapping = [("regex", "expression", ""), ("label", "label", "")]
1753 helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
1754 elif kind == "time":
1755 ctag.set("class", core_prefix + "TimeCondition")
1756 mapping = [
1757 ("earliest-hour", "earliestHours", "09"),
1758 ("earliest-min", "earliestMinutes", "00"),
1759 ("latest-hour", "latestHours", "17"),
1760 ("latest-min", "latestMinutes", "30"),
1761 ("use-build-time", "useBuildTime", False),
1762 ]
1763 helpers.convert_mapping_to_xml(ctag, cdata, mapping, fail_required=True)
1764 elif kind == "not":
1765 ctag.set("class", logic_prefix + "Not")
1766 try:
1767 notcondition = cdata["condition-operand"]
1768 except KeyError:
1769 raise MissingAttributeError("condition-operand")
1770 build_condition(notcondition, ctag, "condition")
1771 elif kind == "and" or "or":
1772 if kind == "and":
1773 ctag.set("class", logic_prefix + "And")
1774 else:
1775 ctag.set("class", logic_prefix + "Or")
1776 conditions_tag = XML.SubElement(ctag, "conditions")
1777 container_tag_text = (
1778 "org.jenkins__ci.plugins.run__condition." "logic.ConditionContainer"
1779 )
1780 try:
1781 conditions_list = cdata["condition-operands"]
1782 except KeyError:
1783 raise MissingAttributeError("condition-operands")
1784 for condition in conditions_list:
1785 conditions_container_tag = XML.SubElement(
1786 conditions_tag, container_tag_text
1787 )
1788 build_condition(condition, conditions_container_tag, "condition")
1789
1790 cond_builder_tag = (
1791 "org.jenkinsci.plugins.conditionalbuildstep."
1792 "singlestep.SingleConditionalBuilder"
1793 )
1794 cond_builders_tag = (
1795 "org.jenkinsci.plugins.conditionalbuildstep." "ConditionalBuilder"
1796 )
1797 # A builder could be a macro, so it's required to create builders at first
1798 # to set `has_multiple_steps` flag correctly.
1799 edited_nodes = [
1800 edited_node
1801 for step in data["steps"]
1802 for edited_node in create_builders(registry, step)
1803 ]
1804 has_multiple_steps = len(edited_nodes) > 1
1805
1806 if has_multiple_steps:
1807 root_tag = XML.SubElement(xml_parent, cond_builders_tag)
1808 steps_parent = XML.SubElement(root_tag, "conditionalbuilders")
1809 condition_tag = "runCondition"
1810 else:
1811 root_tag = XML.SubElement(xml_parent, cond_builder_tag)
1812 steps_parent = root_tag
1813 condition_tag = "condition"
1814
1815 build_condition(data, root_tag, condition_tag)
1816 evaluation_classes_pkg = "org.jenkins_ci.plugins.run_condition"
1817 evaluation_classes = {
1818 "fail": evaluation_classes_pkg + ".BuildStepRunner$Fail",
1819 "mark-unstable": evaluation_classes_pkg + ".BuildStepRunner$Unstable",
1820 "run-and-mark-unstable": evaluation_classes_pkg
1821 + ".BuildStepRunner$RunUnstable",
1822 "run": evaluation_classes_pkg + ".BuildStepRunner$Run",
1823 "dont-run": evaluation_classes_pkg + ".BuildStepRunner$DontRun",
1824 }
1825 evaluation_class = evaluation_classes[data.get("on-evaluation-failure", "fail")]
1826 XML.SubElement(root_tag, "runner").set("class", evaluation_class)
1827 for edited_node in edited_nodes:
1828 if not has_multiple_steps:
1829 edited_node.set("class", edited_node.tag)
1830 edited_node.tag = "buildStep"
1831 steps_parent.append(edited_node)
1832
1833
1834 def maven_builder(registry, xml_parent, data):
1835 """yaml: maven-builder
1836 Execute Maven3 builder
1837
1838 Allows your build jobs to deploy artifacts automatically to Artifactory.
1839
1840 Requires the Jenkins `Artifactory Plugin
1841 <https://jfrog.com/help/r/jfrog-integrations-documentation/jenkins-artifactory-plug-in>`_.
1842
1843 :arg str name: Name of maven installation from the configuration (required)
1844 :arg str pom: Location of pom.xml (default 'pom.xml')
1845 :arg str goals: Goals to execute (required)
1846 :arg str maven-opts: Additional options for maven (default '')
1847
1848 Example:
1849
1850 .. literalinclude:: /../../tests/builders/fixtures/maven-builder001.yaml
1851 :language: yaml
1852 """
1853 maven = XML.SubElement(xml_parent, "org.jfrog.hudson.maven3.Maven3Builder")
1854
1855 mapping = [
1856 ("name", "mavenName", None),
1857 ("goals", "goals", None),
1858 ("pom", "rootPom", "pom.xml"),
1859 ("maven-opts", "mavenOpts", ""),
1860 ]
1861 helpers.convert_mapping_to_xml(maven, data, mapping, fail_required=True)
1862
1863
1864 def jira_issue_updater(registry, xml_parent, data):
1865 """yaml: jenkins-jira-issue-updater
1866 Updates issues in Atlassian JIRA as part of a Jenkins job.
1867
1868 Requires the Jenkins :jenkins-plugins:`Jira Issue Updater Plugin
1869 <jenkins-jira-issue-updater>`.
1870
1871 :arg str base-url: The base url of the rest API. (default '')
1872 :arg str username: The Jira username (required)
1873 :arg str password: The Jira password (required)
1874 :arg str jql: The JQL used to select the issues to update. (required)
1875 :arg str workflow: The Name of the workflow action to be executed.
1876 (default '')
1877 :arg str comment: The Jira comment to be added. (default '')
1878 :arg str custom-Id: The Jira custom field to be edited. (default '')
1879 :arg str custom-value: Jira custom field value. (default '')
1880 :arg bool fail-if-error: Fail this build if JQL returns error.
1881 ((default false)
1882 :arg bool fail-if-no-match: Fail this build if no issues are matched.
1883 (default false)
1884 :arg bool fail-if-no-connection: Fail this build if can't connect to Jira.
1885 (default false)
1886
1887 Minimal Example:
1888
1889 .. literalinclude::
1890 /../../tests/builders/fixtures/jenkins-jira-issue-updater-minimal.yaml
1891 :language: yaml
1892
1893 Full Example:
1894
1895 .. literalinclude::
1896 /../../tests/builders/fixtures/jenkins-jira-issue-updater-full.yaml
1897 :language: yaml
1898 """
1899 issue_updater = XML.SubElement(
1900 xml_parent, "info.bluefloyd.jenkins." "IssueUpdatesBuilder"
1901 )
1902 issue_updater.set("plugin", "jenkins-jira-issue-updater")
1903
1904 mapping = [
1905 ("base-url", "restAPIUrl", ""),
1906 ("username", "userName", None),
1907 ("password", "password", None),
1908 ("jql", "jql", None),
1909 ("workflow", "workflowActionName", ""),
1910 ("comment", "comment", ""),
1911 ("custom-Id", "customFieldId", ""),
1912 ("custom-value", "customFieldValue", ""),
1913 ("fail-if-error", "failIfJqlFails", False),
1914 ("fail-if-no-match", "failIfNoIssuesReturned", False),
1915 ("fail-if-no-connection", "failIfNoJiraConnection", False),
1916 ]
1917 helpers.convert_mapping_to_xml(issue_updater, data, mapping, fail_required=True)
1918
1919
1920 def maven_target(registry, xml_parent, data):
1921 """yaml: maven-target
1922 Execute top-level Maven targets.
1923
1924 Requires the Jenkins :jenkins-plugins:`Config File Provider Plugin
1925 <config-file-provider>` for the Config File Provider "settings"
1926 and "global-settings" config.
1927
1928 :arg str goals: Goals to execute
1929 :arg str properties: Properties for maven, can have multiples
1930 :arg str pom: Location of pom.xml (default 'pom.xml')
1931 :arg bool private-repository: Use private maven repository for this
1932 job (default false)
1933 :arg str maven-version: Installation of maven which should be used
1934 (optional)
1935 :arg str java-opts: java options for maven, can have multiples,
1936 must be in quotes (optional)
1937 :arg str settings: Path to use as user settings.xml
1938 It is possible to provide a ConfigFileProvider settings file, such as
1939 see CFP Example below. (optional)
1940 :arg str settings-type: Type of settings file file|cfp. (default file)
1941 :arg str global-settings: Path to use as global settings.xml
1942 It is possible to provide a ConfigFileProvider settings file, such as
1943 see CFP Example below. (optional)
1944 :arg str global-settings-type: Type of settings file file|cfp. (default
1945 file)
1946
1947 Example:
1948
1949 .. literalinclude:: /../../tests/builders/fixtures/maven-target-doc.yaml
1950 :language: yaml
1951
1952 CFP Example:
1953
1954 .. literalinclude:: /../../tests/builders/fixtures/maven-target002.yaml
1955 :language: yaml
1956 """
1957 maven = XML.SubElement(xml_parent, "hudson.tasks.Maven")
1958 XML.SubElement(maven, "targets").text = data["goals"]
1959 prop_string = "\n".join(data.get("properties", []))
1960 XML.SubElement(maven, "properties").text = prop_string
1961
1962 mapping = [
1963 ("maven-version", "mavenName", None),
1964 ("pom", "pom", None),
1965 ("private-repository", "usePrivateRepository", False),
1966 ]
1967 helpers.convert_mapping_to_xml(maven, data, mapping, fail_required=False)
1968 if "java-opts" in data:
1969 javaoptions = " ".join(data.get("java-opts", []))
1970 XML.SubElement(maven, "jvmOptions").text = javaoptions
1971 helpers.config_file_provider_settings(maven, data)
1972
1973
1974 def multijob(registry, xml_parent, data):
1975 """yaml: multijob
1976 Define a multijob phase.
1977
1978 Requires the Jenkins :jenkins-plugins:`Multijob Plugin
1979 <jenkins-multijob-plugin>`.
1980
1981 This builder may only be used in
1982 :py:class:`jenkins_jobs.modules.project_multijob.MultiJob` projects.
1983
1984 :arg str name: MultiJob phase name
1985 :arg str condition: when to trigger the other job.
1986 Can be: 'SUCCESSFUL', 'UNSTABLE', 'COMPLETED', 'FAILURE', 'ALWAYS'.
1987 (default 'SUCCESSFUL')
1988 :arg str execution-type: Define how to run jobs in a phase:
1989 sequentially or parallel.
1990 Can be: 'PARALLEL', 'SEQUENTIALLY'
1991 (default 'PARALLEL')
1992
1993 :arg list projects: list of projects to include in the MultiJob phase
1994
1995 :Project:
1996 * **name** (`str`) -- Project name
1997 * **alias** (`str`) -- Project alias, which will be shown
1998 in MultiJob Overview. Helpful when working with the same
1999 project multiple times with different configurations
2000 * **current-parameters** (`bool`) -- Pass current build
2001 parameters to the other job (default false)
2002 * **node-label-name** (`str`) -- Define a list of nodes
2003 on which the job should be allowed to be executed on.
2004 Requires NodeLabel Parameter Plugin (optional)
2005 * **node-label** (`str`) -- Define a label
2006 of 'Restrict where this project can be run' on the fly.
2007 Requires NodeLabel Parameter Plugin (optional)
2008 * **node-parameters** (`bool`) -- Use the same Node for
2009 the triggered builds that was used for this build. (optional)
2010 * **git-revision** (`bool`) -- Pass current git-revision
2011 to the other job (default false)
2012 * **property-file** (`str`) -- Pass properties from file
2013 to the other job (optional)
2014 * **predefined-parameters** (`str`) -- Pass predefined
2015 parameters to the other job (optional)
2016 * **abort-all-job** (`bool`) -- Kill allsubs job and the phase job,
2017 if this subjob is killed (default false)
2018 * **aggregate-results** (`bool`) -- Aggregate test results.
2019 (default false)
2020 * **enable-condition** (`str`) -- Condition to run the
2021 job in groovy script format (optional)
2022 * **kill-phase-on** (`str`) -- Stop the phase execution
2023 on specific job status. Can be 'FAILURE', 'UNSTABLE',
2024 'NEVER'. (optional)
2025 * **restrict-matrix-project** (`str`) -- Filter that
2026 restricts the subset of the combinations that the
2027 downstream project will run (optional)
2028 * **retry** (`dict`): Enable retry strategy (optional)
2029 :retry:
2030 * **max-retry** (`int`) -- Max number of retries
2031 (default 0)
2032 * **strategy-path** (`str`) -- Parsing rules path
2033 (required)
2034
2035 Example:
2036
2037 .. literalinclude:: /../../tests/builders/fixtures/multibuild.yaml
2038 :language: yaml
2039 """
2040 builder = XML.SubElement(
2041 xml_parent, "com.tikal.jenkins.plugins.multijob." "MultiJobBuilder"
2042 )
2043 conditions_available = ("SUCCESSFUL", "UNSTABLE", "COMPLETED", "FAILURE", "ALWAYS")
2044 job_execution_type_available = ("PARALLEL", "SEQUENTIALLY")
2045 mapping = [
2046 ("name", "phaseName", None),
2047 ("condition", "continuationCondition", "SUCCESSFUL", conditions_available),
2048 ("execution-type", "executionType", "PARALLEL", job_execution_type_available),
2049 ]
2050 helpers.convert_mapping_to_xml(builder, data, mapping, fail_required=True)
2051
2052 phaseJobs = XML.SubElement(builder, "phaseJobs")
2053
2054 kill_status_list = ("FAILURE", "UNSTABLE", "NEVER")
2055
2056 for project in data.get("projects", []):
2057 phaseJob = XML.SubElement(
2058 phaseJobs, "com.tikal.jenkins.plugins." "multijob.PhaseJobsConfig"
2059 )
2060 mapping = [
2061 ("name", "jobName", None),
2062 # Pass through the current build params
2063 ("current-parameters", "currParams", False),
2064 ]
2065 helpers.convert_mapping_to_xml(phaseJob, project, mapping, fail_required=True)
2066 # Pass through other params
2067 if project.get("alias"):
2068 mapping = [("alias", "jobAlias", None)]
2069 helpers.convert_mapping_to_xml(
2070 phaseJob, project, mapping, fail_required=True
2071 )
2072
2073 configs = XML.SubElement(phaseJob, "configs")
2074
2075 nodeLabelName = project.get("node-label-name")
2076 nodeLabel = project.get("node-label")
2077 if nodeLabelName and nodeLabel:
2078 node = XML.SubElement(
2079 configs,
2080 "org.jvnet.jenkins.plugins.nodelabelparameter."
2081 "parameterizedtrigger.NodeLabelBuildParameter",
2082 )
2083 mapping = [("", "name", nodeLabelName), ("", "nodeLabel", nodeLabel)]
2084 helpers.convert_mapping_to_xml(node, project, mapping, fail_required=True)
2085
2086 # Node parameter
2087 if project.get("node-parameters", False):
2088 XML.SubElement(
2089 configs, "hudson.plugins.parameterizedtrigger." "NodeParameters"
2090 )
2091
2092 # Git Revision
2093 if project.get("git-revision", False):
2094 param = XML.SubElement(
2095 configs, "hudson.plugins.git." "GitRevisionBuildParameters"
2096 )
2097 mapping = [("", "combineQueuedCommits", False)]
2098 helpers.convert_mapping_to_xml(param, project, mapping, fail_required=True)
2099
2100 # Properties File
2101 properties_file = project.get("property-file", False)
2102 if properties_file:
2103 param = XML.SubElement(
2104 configs, "hudson.plugins.parameterizedtrigger." "FileBuildParameters"
2105 )
2106 mapping = [
2107 ("", "propertiesFile", properties_file),
2108 ("", "failTriggerOnMissing", True),
2109 ]
2110 helpers.convert_mapping_to_xml(param, project, mapping, fail_required=True)
2111
2112 # Predefined Parameters
2113 predefined_parameters = project.get("predefined-parameters", False)
2114 if predefined_parameters:
2115 param = XML.SubElement(
2116 configs,
2117 "hudson.plugins.parameterizedtrigger." "PredefinedBuildParameters",
2118 )
2119 mapping = [("", "properties", predefined_parameters)]
2120 helpers.convert_mapping_to_xml(param, project, mapping, fail_required=True)
2121
2122 mapping = [
2123 ("abort-all-job", "abortAllJob", False),
2124 ("aggregate-results", "aggregatedTestResults", False),
2125 ]
2126 helpers.convert_mapping_to_xml(phaseJob, project, mapping, fail_required=True)
2127
2128 # Retry job
2129 retry = project.get("retry", False)
2130 if retry:
2131 max_retry = retry.get("max-retry", 0)
2132 mapping = [
2133 ("strategy-path", "parsingRulesPath", None),
2134 ("", "maxRetries", int(max_retry)),
2135 ("", "enableRetryStrategy", True),
2136 ]
2137 helpers.convert_mapping_to_xml(phaseJob, retry, mapping, fail_required=True)
2138 else:
2139 XML.SubElement(phaseJob, "enableRetryStrategy").text = "false"
2140
2141 # Restrict matrix jobs to a subset
2142 if project.get("restrict-matrix-project") is not None:
2143 subset = XML.SubElement(
2144 configs,
2145 "hudson.plugins.parameterizedtrigger."
2146 "matrix.MatrixSubsetBuildParameters",
2147 )
2148 mapping = [("restrict-matrix-project", "filter", None)]
2149 helpers.convert_mapping_to_xml(subset, project, mapping, fail_required=True)
2150
2151 # Enable Condition
2152 enable_condition = project.get("enable-condition")
2153 if enable_condition is not None:
2154 mapping = [
2155 ("", "enableCondition", True),
2156 ("", "condition", enable_condition),
2157 ]
2158 helpers.convert_mapping_to_xml(
2159 phaseJob, project, mapping, fail_required=True
2160 )
2161
2162 # Kill phase on job status
2163 kill_status = project.get("kill-phase-on")
2164 if kill_status is not None:
2165 kill_status = kill_status.upper()
2166 mapping = [
2167 ("", "killPhaseOnJobResultCondition", kill_status, kill_status_list)
2168 ]
2169 helpers.convert_mapping_to_xml(
2170 phaseJob, project, mapping, fail_required=True
2171 )
2172
2173
2174 def config_file_provider(registry, xml_parent, data):
2175 """yaml: config-file-provider
2176 Provide configuration files (i.e., settings.xml for maven etc.)
2177 which will be copied to the job's workspace.
2178
2179 Requires the Jenkins :jenkins-plugins:`Config File Provider Plugin
2180 <config-file-provider>`.
2181
2182 :arg list files: List of managed config files made up of three
2183 parameters
2184
2185 :files:
2186 * **file-id** (`str`) -- The identifier for the managed config
2187 file
2188 * **target** (`str`) -- Define where the file should be created
2189 (default '')
2190 * **variable** (`str`) -- Define an environment variable to be
2191 used (default '')
2192 * **replace-tokens** (`bool`) -- Replace tokens in config file. For
2193 example "password: ${PYPI_JENKINS_PASS}" will be replaced with
2194 the global variable configured in Jenkins.
2195
2196 Full Example:
2197
2198 .. literalinclude::
2199 ../../tests/builders/fixtures/config-file-provider-full.yaml
2200 :language: yaml
2201
2202 Minimal Example:
2203
2204 .. literalinclude::
2205 ../../tests/builders/fixtures/config-file-provider-minimal.yaml
2206 :language: yaml
2207 """
2208 cfp = XML.SubElement(
2209 xml_parent, "org.jenkinsci.plugins.configfiles.builder." "ConfigFileBuildStep"
2210 )
2211 cfp.set("plugin", "config-file-provider")
2212 helpers.config_file_provider_builder(cfp, data)
2213
2214
2215 def grails(registry, xml_parent, data):
2216 """yaml: grails
2217 Execute a grails build step.
2218
2219 Requires the :jenkins-plugins:`Jenkins Grails Plugin <grails>`.
2220
2221 :arg bool use-wrapper: Use a grails wrapper (default false)
2222 :arg str name: Select a grails installation to use (default '(Default)')
2223 :arg bool force-upgrade: Run 'grails upgrade --non-interactive'
2224 first (default false)
2225 :arg bool non-interactive: append --non-interactive to all build targets
2226 (default false)
2227 :arg str targets: Specify target(s) to run separated by spaces (required)
2228 :arg str server-port: Specify a value for the server.port system
2229 property (default '')
2230 :arg str work-dir: Specify a value for the grails.work.dir system
2231 property (default '')
2232 :arg str project-dir: Specify a value for the grails.project.work.dir
2233 system property (default '')
2234 :arg str base-dir: Specify a path to the root of the Grails
2235 project (default '')
2236 :arg str properties: Additional system properties to set (default '')
2237 :arg bool plain-output: append --plain-output to all build targets
2238 (default false)
2239 :arg bool stack-trace: append --stack-trace to all build targets
2240 (default false)
2241 :arg bool verbose: append --verbose to all build targets
2242 (default false)
2243 :arg bool refresh-dependencies: append --refresh-dependencies to all
2244 build targets (default false)
2245
2246 Full Example:
2247
2248 .. literalinclude:: ../../tests/builders/fixtures/grails-full.yaml
2249 :language: yaml
2250
2251 Minimal Example:
2252
2253 .. literalinclude:: ../../tests/builders/fixtures/grails-minimal.yaml
2254 :language: yaml
2255 """
2256 grails = XML.SubElement(xml_parent, "com.g2one.hudson.grails." "GrailsBuilder")
2257 grails.set("plugin", "grails")
2258
2259 mappings = [
2260 ("targets", "targets", None),
2261 ("name", "name", "(Default)"),
2262 ("work-dir", "grailsWorkDir", ""),
2263 ("project-dir", "projectWorkDir", ""),
2264 ("base-dir", "projectBaseDir", ""),
2265 ("server-port", "serverPort", ""),
2266 ("properties", "properties", ""),
2267 ("force-upgrade", "forceUpgrade", False),
2268 ("non-interactive", "nonInteractive", False),
2269 ("use-wrapper", "useWrapper", False),
2270 ("plain-output", "plainOutput", False),
2271 ("stack-trace", "stackTrace", False),
2272 ("verbose", "verbose", False),
2273 ("refresh-dependencies", "refreshDependencies", False),
2274 ]
2275 helpers.convert_mapping_to_xml(grails, data, mappings, fail_required=True)
2276
2277
2278 def sbt(registry, xml_parent, data):
2279 """yaml: sbt
2280 Execute a sbt build step.
2281
2282 Requires the Jenkins :jenkins-plugins:`Sbt Plugin <sbt>`.
2283
2284 :arg str name: Select a sbt installation to use. If no name is
2285 provided, the first in the list of defined SBT builders will be
2286 used. (default to first in list)
2287 :arg str jvm-flags: Parameters to pass to the JVM (default '')
2288 :arg str actions: Select the sbt tasks to execute (default '')
2289 :arg str sbt-flags: Add flags to SBT launcher
2290 (default '-Dsbt.log.noformat=true')
2291 :arg str subdir-path: Path relative to workspace to run sbt in
2292 (default '')
2293
2294 Example:
2295
2296 .. literalinclude:: ../../tests/builders/fixtures/sbt.yaml
2297 :language: yaml
2298 """
2299 sbt = XML.SubElement(xml_parent, "org.jvnet.hudson.plugins." "SbtPluginBuilder")
2300 mappings = [
2301 ("name", "name", ""),
2302 ("jvm-flags", "jvmFlags", ""),
2303 ("sbt-flags", "sbtFlags", "-Dsbt.log.noformat=true"),
2304 ("actions", "actions", ""),
2305 ("subdir-path", "subdirPath", ""),
2306 ]
2307 helpers.convert_mapping_to_xml(sbt, data, mappings, fail_required=True)
2308
2309
2310 def critical_block_start(registry, xml_parent, data):
2311 """yaml: critical-block-start
2312 Designate the start of a critical block. Must be used in conjunction with
2313 critical-block-end.
2314
2315 Must also add a build wrapper (exclusion), specifying the resources that
2316 control the critical block. Otherwise, this will have no effect.
2317
2318 Requires the Jenkins :jenkins-plugins:`Exclusion Plugin <Exclusion>`.
2319
2320 Example:
2321
2322 .. literalinclude::
2323 ../../tests/yamlparser/job_fixtures/critical_block_complete001.yaml
2324 :language: yaml
2325 """
2326 cbs = XML.SubElement(
2327 xml_parent, "org.jvnet.hudson.plugins.exclusion.CriticalBlockStart"
2328 )
2329 cbs.set("plugin", "Exclusion")
2330
2331
2332 def critical_block_end(registry, xml_parent, data):
2333 """yaml: critical-block-end
2334 Designate the end of a critical block. Must be used in conjunction with
2335 critical-block-start.
2336
2337 Must also add a build wrapper (exclusion), specifying the resources that
2338 control the critical block. Otherwise, this will have no effect.
2339
2340 Requires the Jenkins :jenkins-plugins:`Exclusion Plugin <Exclusion>`.
2341
2342 Example:
2343
2344 .. literalinclude::
2345 ../../tests/yamlparser/job_fixtures/critical_block_complete001.yaml
2346 :language: yaml
2347 """
2348 cbs = XML.SubElement(
2349 xml_parent, "org.jvnet.hudson.plugins.exclusion.CriticalBlockEnd"
2350 )
2351 cbs.set("plugin", "Exclusion")
2352
2353
2354 def publish_over_ssh(registry, xml_parent, data):
2355 """yaml: publish-over-ssh
2356 Send files or execute commands over SSH.
2357
2358 Requires the Jenkins :jenkins-plugins:`Publish over SSH Plugin
2359 <publish-over-ssh>`.
2360
2361 :arg str site: name of the ssh site
2362 :arg str target: destination directory
2363 :arg bool target-is-date-format: whether target is a date format. If true,
2364 raw text should be quoted (default false)
2365 :arg bool clean-remote: should the remote directory be deleted before
2366 transferring files (default false)
2367 :arg str source: source path specifier
2368 :arg str command: a command to execute on the remote server (optional)
2369 :arg int timeout: timeout in milliseconds for the Exec command (optional)
2370 :arg bool use-pty: run the exec command in pseudo TTY (default false)
2371 :arg str excludes: excluded file pattern (optional)
2372 :arg str remove-prefix: prefix to remove from uploaded file paths
2373 (optional)
2374 :arg bool fail-on-error: fail the build if an error occurs (default false)
2375
2376 Example:
2377
2378 .. literalinclude:: /../../tests/builders/fixtures/publish-over-ssh.yaml
2379 :language: yaml
2380 """
2381 ssh(registry, xml_parent, data)
2382
2383
2384 def publish_over_cifs(registry, xml_parent, data):
2385 """yaml: publish-over-cifs
2386 Upload files via CIFS.
2387
2388 Requires the Jenkins :jenkins-plugins:`Publish over CIFS Plugin
2389 <publish-over-cifs>`.
2390
2391 :arg str site: name of the ssh site
2392 :arg str target: destination directory
2393 :arg bool target-is-date-format: whether target is a date format. If true,
2394 raw text should be quoted (default false)
2395 :arg bool clean-remote: should the remote directory be deleted before
2396 transferring files (default false)
2397 :arg str source: source path specifier
2398 :arg str excludes: excluded file pattern (optional)
2399 :arg str remove-prefix: prefix to remove from uploaded file paths
2400 (optional)
2401 :arg bool fail-on-error: fail the build if an error occurs (default false)
2402 :arg bool flatten: only create files on the server, don't create
2403 directories (default false)
2404
2405 Example:
2406
2407 .. literalinclude:: /../../tests/builders/fixtures/publish-over-cifs.yaml
2408 :language: yaml
2409 """
2410 cifs(registry, xml_parent, data)
2411
2412
2413 def saltstack(parser, xml_parent, data):
2414 """yaml: saltstack
2415
2416 Send a message to Salt API.
2417
2418 Requires the Jenkins :jenkins-plugins:`saltstack plugin <saltstack>`.
2419
2420 :arg str servername: Salt master server name (required)
2421 :arg str authtype: Authentication type ('pam' or 'ldap', default 'pam')
2422 :arg str credentials: Credentials ID for which to authenticate to Salt
2423 master (required)
2424 :arg str target: Target minions (default '')
2425 :arg str targettype: Target type ('glob', 'pcre', 'list', 'grain',
2426 'pillar', 'nodegroup', 'range', or 'compound', default 'glob')
2427 :arg str function: Function to execute (default '')
2428 :arg str arguments: Salt function arguments (default '')
2429 :arg str kwarguments: Salt keyword arguments (default '')
2430 :arg bool saveoutput: Save Salt return data into environment variable
2431 (default false)
2432 :arg str clientinterface: Client interface type ('local', 'local-batch',
2433 or 'runner', default 'local')
2434 :arg bool wait: Wait for completion of command (default false)
2435 :arg str polltime: Number of seconds to wait before polling job completion
2436 status (default '')
2437 :arg str batchsize: Salt batch size, absolute value or %-age (default 100%)
2438 :arg str mods: Mods to runner (default '')
2439 :arg bool setpillardata: Set Pillar data (default false)
2440 :arg str pillarkey: Pillar key (default '')
2441 :arg str pillarvalue: Pillar value (default '')
2442
2443 Minimal Example:
2444
2445 .. literalinclude:: ../../tests/builders/fixtures/saltstack-minimal.yaml
2446 :language: yaml
2447
2448 Full Example:
2449
2450 .. literalinclude:: ../../tests/builders/fixtures/saltstack-full.yaml
2451 :language: yaml
2452 """
2453 saltstack = XML.SubElement(xml_parent, "com.waytta.SaltAPIBuilder")
2454
2455 supported_auth_types = ["pam", "ldap"]
2456 supported_target_types = [
2457 "glob",
2458 "pcre",
2459 "list",
2460 "grain",
2461 "pillar",
2462 "nodegroup",
2463 "range",
2464 "compound",
2465 ]
2466 supported_client_interfaces = ["local", "local-batch", "runner"]
2467
2468 mapping = [
2469 ("servername", "servername", None),
2470 ("credentials", "credentialsId", None),
2471 ("authtype", "authtype", "pam", supported_auth_types),
2472 ("target", "target", ""),
2473 ("targettype", "targettype", "glob", supported_target_types),
2474 ("clientinterface", "clientInterface", "local", supported_client_interfaces),
2475 ("function", "function", ""),
2476 ("arguments", "arguments", ""),
2477 ("kwarguments", "kwarguments", ""),
2478 ("setpillardata", "usePillar", False),
2479 ("pillarkey", "pillarkey", ""),
2480 ("pillarvalue", "pillarvalue", ""),
2481 ("wait", "blockbuild", False),
2482 ("polltime", "jobPollTime", ""),
2483 ("batchsize", "batchSize", "100%"),
2484 ("mods", "mods", ""),
2485 ("saveoutput", "saveEnvVar", False),
2486 ]
2487
2488 helpers.convert_mapping_to_xml(saltstack, data, mapping, fail_required=True)
2489
2490 clientInterface = data.get("clientinterface", "local")
2491 blockbuild = str(data.get("wait", False)).lower()
2492 jobPollTime = str(data.get("polltime", ""))
2493 batchSize = data.get("batchsize", "100%")
2494 mods = data.get("mods", "")
2495 usePillar = str(data.get("setpillardata", False)).lower()
2496
2497 # Build the clientInterfaces structure, based on the
2498 # clientinterface setting
2499 clientInterfaces = XML.SubElement(saltstack, "clientInterfaces")
2500 XML.SubElement(clientInterfaces, "nullObject").text = "false"
2501
2502 ci_attrib = {
2503 "class": "org.apache.commons.collections.map.ListOrderedMap",
2504 "serialization": "custom",
2505 }
2506 properties = XML.SubElement(clientInterfaces, "properties", ci_attrib)
2507
2508 lomElement = "org.apache.commons.collections.map.ListOrderedMap"
2509 listOrderedMap = XML.SubElement(properties, lomElement)
2510
2511 default = XML.SubElement(listOrderedMap, "default")
2512 ordered_map = XML.SubElement(listOrderedMap, "map")
2513
2514 insertOrder = XML.SubElement(default, "insertOrder")
2515
2516 ci_config = []
2517 if clientInterface == "local":
2518 ci_config = [
2519 ("blockbuild", blockbuild),
2520 ("jobPollTime", jobPollTime),
2521 ("clientInterface", clientInterface),
2522 ]
2523
2524 elif clientInterface == "local-batch":
2525 ci_config = [("batchSize", batchSize), ("clientInterface", clientInterface)]
2526
2527 elif clientInterface == "runner":
2528 ci_config = [("mods", mods), ("clientInterface", clientInterface)]
2529
2530 if usePillar == "true":
2531 ci_config.append(("usePillar", usePillar))
2532
2533 pillar_cfg = [
2534 ("pillarkey", data.get("pillarkey")),
2535 ("pillarvalue", data.get("pillarvalue")),
2536 ]
2537
2538 for emt, value in ci_config:
2539 XML.SubElement(insertOrder, "string").text = emt
2540 entry = XML.SubElement(ordered_map, "entry")
2541 XML.SubElement(entry, "string").text = emt
2542
2543 # Special handling when usePillar == true, requires additional
2544 # structure in the builder XML
2545 if emt != "usePillar":
2546 XML.SubElement(entry, "string").text = value
2547 else:
2548 jsonobj = XML.SubElement(entry, "net.sf.json.JSONObject")
2549 XML.SubElement(jsonobj, "nullObject").text = "false"
2550
2551 pillarProps = XML.SubElement(jsonobj, "properties", ci_attrib)
2552 XML.SubElement(pillarProps, "unserializable-parents")
2553
2554 pillarLom = XML.SubElement(pillarProps, lomElement)
2555
2556 pillarDefault = XML.SubElement(pillarLom, "default")
2557 pillarMap = XML.SubElement(pillarLom, "map")
2558 pillarInsertOrder = XML.SubElement(pillarDefault, "insertOrder")
2559
2560 for pemt, value in pillar_cfg:
2561 XML.SubElement(pillarInsertOrder, "string").text = pemt
2562 pillarEntry = XML.SubElement(pillarMap, "entry")
2563 XML.SubElement(pillarEntry, "string").text = pemt
2564 XML.SubElement(pillarEntry, "string").text = value
2565
2566
2567 class Builders(jenkins_jobs.modules.base.Base):
2568 sequence = 60
2569
2570 component_type = "builder"
2571 component_list_type = "builders"
2572
2573 def gen_xml(self, xml_parent, data):
2574
2575 for alias in ["prebuilders", "builders", "postbuilders"]:
2576 if alias in data:
2577 xml_builders = XML.SubElement(xml_parent, alias)
2578 self.dispatch_component_list("builder", data[alias], xml_builders)
2579
2580 # Make sure freestyle projects always have a <builders> entry
2581 # or Jenkins v1.472 (at least) will NPE.
2582 project_type = data.get("project-type", "freestyle")
2583 if project_type in ("freestyle", "matrix") and "builders" not in data:
2584 XML.SubElement(xml_parent, "builders")
2585
2586
2587 def shining_panda(registry, xml_parent, data):
2588 """yaml: shining-panda
2589 Execute a command inside various python environments.
2590
2591 Requires the Jenkins :jenkins-plugins:`ShiningPanda plugin
2592 <shiningpanda>`.
2593
2594 :arg str build-environment: Building environment to set up (required).
2595
2596 :build-environment values:
2597 * **python**: Use a python installation configured in Jenkins.
2598 * **custom**: Use a manually installed python.
2599 * **virtualenv**: Create a virtualenv
2600
2601 For the **python** environment
2602
2603 :arg str python-version: Name of the python installation to use.
2604 Must match one of the configured installations on server
2605 configuration (default 'System-CPython-2.7')
2606
2607 For the **custom** environment:
2608
2609 :arg str home: path to the home folder of the custom installation
2610 (required)
2611
2612 For the **virtualenv** environment:
2613
2614 :arg str python-version: Name of the python installation to use.
2615 Must match one of the configured installations on server
2616 configuration (default 'System-CPython-2.7')
2617 :arg str name: Name of this virtualenv. Two virtualenv builders with
2618 the same name will use the same virtualenv installation (optional)
2619 :arg bool clear: If true, delete and recreate virtualenv on each build.
2620 (default false)
2621 :arg bool use-distribute: if true use distribute, if false use
2622 setuptools. (default true)
2623 :arg bool system-site-packages: if true, give access to the global
2624 site-packages directory to the virtualenv. (default false)
2625
2626 Common to all environments:
2627
2628 :arg str nature: Nature of the command field. (default shell)
2629
2630 :nature values:
2631 * **shell**: execute the Command contents with default shell
2632 * **xshell**: like **shell** but performs platform conversion
2633 first
2634 * **python**: execute the Command contents with the Python
2635 executable
2636
2637 :arg str command: The command to execute
2638 :arg bool ignore-exit-code: mark the build as failure if any of the
2639 commands exits with a non-zero exit code. (default false)
2640
2641 Examples:
2642
2643 .. literalinclude::
2644 /../../tests/builders/fixtures/shining-panda-pythonenv.yaml
2645 :language: yaml
2646
2647 .. literalinclude::
2648 /../../tests/builders/fixtures/shining-panda-customenv.yaml
2649 :language: yaml
2650
2651 .. literalinclude::
2652 /../../tests/builders/fixtures/shining-panda-virtualenv.yaml
2653 :language: yaml
2654 """
2655
2656 pluginelementpart = "jenkins.plugins.shiningpanda.builders."
2657 buildenvdict = {
2658 "custom": "CustomPythonBuilder",
2659 "virtualenv": "VirtualenvBuilder",
2660 "python": "PythonBuilder",
2661 }
2662 envs = buildenvdict.keys()
2663
2664 try:
2665 buildenv = data["build-environment"]
2666 except KeyError:
2667 raise MissingAttributeError("build-environment")
2668
2669 if buildenv not in envs:
2670 raise InvalidAttributeError("build-environment", buildenv, envs)
2671
2672 t = XML.SubElement(xml_parent, "%s%s" % (pluginelementpart, buildenvdict[buildenv]))
2673
2674 if buildenv in ("python", "virtualenv"):
2675 python_mapping = [("python-version", "pythonName", "System-CPython-2.7")]
2676 helpers.convert_mapping_to_xml(t, data, python_mapping, fail_required=True)
2677
2678 if buildenv in "custom":
2679 custom_mapping = [("home", "home", None)]
2680 helpers.convert_mapping_to_xml(t, data, custom_mapping, fail_required=True)
2681 if buildenv in "virtualenv":
2682 virtualenv_mapping = [
2683 ("name", "home", ""),
2684 ("clear", "clear", False),
2685 ("use-distribute", "useDistribute", False),
2686 ("system-site-packages", "systemSitePackages", False),
2687 ]
2688 helpers.convert_mapping_to_xml(t, data, virtualenv_mapping, fail_required=True)
2689
2690 # Common arguments
2691 naturelist = ["shell", "xshell", "python"]
2692 mapping = [
2693 ("nature", "nature", "shell", naturelist),
2694 ("command", "command", ""),
2695 ("ignore-exit-code", "ignoreExitCode", False),
2696 ]
2697 helpers.convert_mapping_to_xml(t, data, mapping, fail_required=True)
2698
2699
2700 def tox(registry, xml_parent, data):
2701 """yaml: tox
2702 Use tox to build a multi-configuration project.
2703
2704 Requires the Jenkins :jenkins-plugins:`ShiningPanda plugin
2705 <shiningpanda>`.
2706
2707 :arg str ini: The TOX configuration file path (default tox.ini)
2708 :arg bool recreate: If true, create a new environment each time (default
2709 false)
2710 :arg str toxenv-pattern: The pattern used to build the TOXENV environment
2711 variable. (optional)
2712
2713 Example:
2714
2715 .. literalinclude:: /../../tests/builders/fixtures/tox001.yaml
2716 :language: yaml
2717 """
2718 pluginelement = "jenkins.plugins.shiningpanda.builders.ToxBuilder"
2719 t = XML.SubElement(xml_parent, pluginelement)
2720 mappings = [("ini", "toxIni", "tox.ini"), ("recreate", "recreate", False)]
2721 helpers.convert_mapping_to_xml(t, data, mappings, fail_required=True)
2722 pattern = data.get("toxenv-pattern")
2723 if pattern:
2724 XML.SubElement(t, "toxenvPattern").text = pattern
2725
2726
2727 def managed_script(registry, xml_parent, data):
2728 """yaml: managed-script
2729 This step allows you to reference and execute a centrally managed
2730 script within your build.
2731
2732 Requires the Jenkins :jenkins-plugins:`Managed Scripts Plugin
2733 <managed-scripts>`.
2734
2735 :arg str script-id: Id of script to execute (required)
2736 :arg str type: Type of managed file (default script)
2737
2738 :type values:
2739 * **batch**: Execute managed windows batch
2740 * **script**: Execute managed script
2741
2742 :arg list args: Arguments to be passed to referenced script
2743
2744 Example:
2745
2746 .. literalinclude:: /../../tests/builders/fixtures/managed-script.yaml
2747 :language: yaml
2748
2749 .. literalinclude:: /../../tests/builders/fixtures/managed-winbatch.yaml
2750 :language: yaml
2751 """
2752 step_type = data.get("type", "script").lower()
2753 if step_type == "script":
2754 step = "ScriptBuildStep"
2755 script_tag = "buildStepId"
2756 elif step_type == "batch":
2757 step = "WinBatchBuildStep"
2758 script_tag = "command"
2759 else:
2760 raise InvalidAttributeError("type", step_type, ["script", "batch"])
2761 ms = XML.SubElement(xml_parent, "org.jenkinsci.plugins.managedscripts." + step)
2762 mapping = [("script-id", script_tag, None)]
2763 helpers.convert_mapping_to_xml(ms, data, mapping, fail_required=True)
2764 args = XML.SubElement(ms, "buildStepArgs")
2765 for arg in data.get("args", []):
2766 XML.SubElement(args, "string").text = arg
2767
2768
2769 def cmake(registry, xml_parent, data):
2770 """yaml: cmake
2771 Execute a CMake target.
2772
2773 Requires the Jenkins :jenkins-plugins:`CMake Plugin <cmakebuilder>`.
2774
2775 This builder is compatible with both versions 2.x and 1.x of the
2776 plugin. When specifying paramenters from both versions only the ones from
2777 the installed version in Jenkins will be used, and the rest will be
2778 ignored.
2779
2780 :arg str source-dir: the source code directory relative to the workspace
2781 directory. (required)
2782 :arg str build-type: Sets the "build type" option for CMake (default
2783 "Debug").
2784 :arg str preload-script: Path to a CMake preload script file. (optional)
2785 :arg str other-arguments: Other arguments to be added to the CMake
2786 call. (optional)
2787 :arg bool clean-build-dir: If true, delete the build directory before each
2788 build (default false).
2789
2790 :arg list generator: The makefile generator (default "Unix Makefiles").
2791
2792 :type Possible generators:
2793 * **Borland Makefiles**
2794 * **CodeBlocks - MinGW Makefiles**
2795 * **CodeBlocks - Unix Makefiles**
2796 * **Eclipse CDT4 - MinGW Makefiles**
2797 * **Eclipse CDT4 - NMake Makefiles**
2798 * **Eclipse CDT4 - Unix Makefiles**
2799 * **MSYS Makefiles**
2800 * **MinGW Makefiles**
2801 * **NMake Makefiles**
2802 * **Unix Makefiles**
2803 * **Visual Studio 6**
2804 * **Visual Studio 7 .NET 2003**
2805 * **Visual Studio 8 2005**
2806 * **Visual Studio 8 2005 Win64**
2807 * **Visual Studio 9 2008**
2808 * **Visual Studio 9 2008 Win64**
2809 * **Watcom WMake**
2810
2811 :Version 2.x: Parameters that available only to versions 2.x of the plugin
2812
2813 * **working-dir** (`str`): The directory where the project will be
2814 built in. Relative to the workspace directory. (optional)
2815 * **installation-name** (`str`): The CMake installation to be used on
2816 this builder. Use one defined in your Jenkins global configuration
2817 page (default "InSearchPath").
2818 * **build-tool-invocations** (`list`): list of build tool invocations
2819 that will happen during the build:
2820
2821 :Build tool invocations:
2822 * **use-cmake** (`str`) -- Whether to run the actual build tool
2823 directly (by expanding ``$CMAKE_BUILD_TOOL``) or to have
2824 cmake run the build tool (by invoking ``cmake --build
2825 <dir>``) (default false).
2826 * **arguments** (`str`) -- Specify arguments to pass to the
2827 build tool or cmake (separated by spaces). Arguments may
2828 contain spaces if they are enclosed in double
2829 quotes. (optional)
2830 * **environment-variables** (`str`) -- Specify extra
2831 environment variables to pass to the build tool as
2832 key-value pairs here. Each entry must be on its own line,
2833 for example:
2834
2835 ``DESTDIR=${WORKSPACE}/artifacts/dir``
2836
2837 ``KEY=VALUE``
2838
2839 :Version 1.x: Parameters available only to versions 1.x of the plugin
2840
2841 * **build-dir** (`str`): The directory where the project will be built
2842 in. Relative to the workspace directory. (optional)
2843 * **install-dir** (`str`): The directory where the project will be
2844 installed in, relative to the workspace directory. (optional)
2845 * **build-type** (`list`): Sets the "build type" option. A custom type
2846 different than the default ones specified on the CMake plugin can
2847 also be set, which will be automatically used in the "Other Build
2848 Type" option of the plugin. (default "Debug")
2849
2850 :Default types present in the CMake plugin:
2851 * **Debug**
2852 * **Release**
2853 * **RelWithDebInfo**
2854 * **MinSizeRel**
2855
2856 * **make-command** (`str`): The make command (default "make").
2857 * **install-command** (`arg`): The install command (default "make
2858 install").
2859 * **custom-cmake-path** (`str`): Path to cmake executable. (optional)
2860 * **clean-install-dir** (`bool`): If true, delete the install dir
2861 before each build (default false).
2862
2863 Example (Versions 2.x):
2864
2865 .. literalinclude::
2866 ../../tests/builders/fixtures/cmake/version-2.0/complete-2.x.yaml
2867 :language: yaml
2868
2869 Example (Versions 1.x):
2870
2871 .. literalinclude::
2872 ../../tests/builders/fixtures/cmake/version-1.10/complete-1.x.yaml
2873 :language: yaml
2874 """
2875
2876 BUILD_TYPES = ["Debug", "Release", "RelWithDebInfo", "MinSizeRel"]
2877 cmake = XML.SubElement(xml_parent, "hudson.plugins.cmake.CmakeBuilder")
2878
2879 mapping = [
2880 ("source-dir", "sourceDir", None), # Required parameter
2881 ("generator", "generator", "Unix Makefiles"),
2882 ("clean-build-dir", "cleanBuild", False),
2883 ]
2884 helpers.convert_mapping_to_xml(cmake, data, mapping, fail_required=True)
2885
2886 plugin_ver = registry.get_plugin_version("CMake plugin")
2887
2888 if plugin_ver >= "2.0":
2889 mapping_20 = [
2890 ("preload-script", "preloadScript", None), # Optional parameter
2891 ("working-dir", "workingDir", ""),
2892 ("build-type", "buildType", "Debug"),
2893 ("installation-name", "installationName", "InSearchPath"),
2894 ("other-arguments", "toolArgs", ""),
2895 ]
2896 helpers.convert_mapping_to_xml(cmake, data, mapping_20, fail_required=False)
2897
2898 tool_steps = XML.SubElement(cmake, "toolSteps")
2899
2900 for step_data in data.get("build-tool-invocations", []):
2901 step = XML.SubElement(tool_steps, "hudson.plugins.cmake.BuildToolStep")
2902 step_mapping = [
2903 ("use-cmake", "withCmake", False),
2904 ("arguments", "args", ""),
2905 ("environment-variables", "vars", ""),
2906 ]
2907 helpers.convert_mapping_to_xml(
2908 step, step_data, step_mapping, fail_required=True
2909 )
2910
2911 else:
2912 mapping_10 = [
2913 ("preload-script", "preloadScript", ""),
2914 ("build-dir", "buildDir", ""),
2915 ("install-dir", "installDir", ""),
2916 ("make-command", "makeCommand", "make"),
2917 ("install-command", "installCommand", "make install"),
2918 ("other-arguments", "cmakeArgs", ""),
2919 ("custom-cmake-path", "projectCmakePath", ""),
2920 ("clean-install-dir", "cleanInstallDir", False),
2921 ]
2922 helpers.convert_mapping_to_xml(cmake, data, mapping_10, fail_required=True)
2923
2924 # The options buildType and otherBuildType work together on the CMake
2925 # plugin:
2926 # * If the passed value is one of the predefined values, set buildType
2927 # to it and otherBuildType to blank;
2928 # * Otherwise, set otherBuildType to the value, and buildType to
2929 # "Debug". The CMake plugin will ignore the buildType option.
2930 #
2931 # It is strange and confusing that the plugin author chose to do
2932 # something like that instead of simply passing a string "buildType"
2933 # option, so this was done to simplify it for the JJB user.
2934 build_type = XML.SubElement(cmake, "buildType")
2935 build_type.text = data.get("build-type", BUILD_TYPES[0])
2936 other_build_type = XML.SubElement(cmake, "otherBuildType")
2937
2938 if build_type.text not in BUILD_TYPES:
2939 other_build_type.text = build_type.text
2940 build_type.text = BUILD_TYPES[0]
2941 else:
2942 other_build_type.text = ""
2943
2944 # The plugin generates this tag, but there doesn't seem to be anything
2945 # that can be configurable by it. Let's keep it to maintain
2946 # compatibility:
2947 XML.SubElement(cmake, "builderImpl")
2948
2949
2950 def dsl(registry, xml_parent, data):
2951 r"""yaml: dsl
2952 Process Job DSL
2953
2954 Requires the Jenkins :jenkins-plugins:`Job DSL plugin <job-dsl>`.
2955
2956 :arg str script-text: dsl script which is Groovy code (Required if targets
2957 is not specified)
2958 :arg str targets: Newline separated list of DSL scripts, located in the
2959 Workspace. Can use wildcards like 'jobs/\*/\*/\*.groovy' (Required
2960 if script-text is not specified)
2961 :arg str ignore-existing: Ignore previously generated jobs and views
2962 :arg str removed-job-action: Specifies what to do when a previously
2963 generated job is not referenced anymore, can be 'IGNORE', 'DISABLE',
2964 or 'DELETE' (default 'IGNORE')
2965 :arg str removed-view-action: Specifies what to do when a previously
2966 generated view is not referenced anymore, can be 'IGNORE' or 'DELETE'.
2967 (default 'IGNORE')
2968 :arg str lookup-strategy: Determines how relative job names in DSL
2969 scripts are interpreted, can be 'JENKINS_ROOT' or 'SEED_JOB'.
2970 (default 'JENKINS_ROOT')
2971 :arg str additional-classpath: Newline separated list of additional
2972 classpath entries for the Job DSL scripts. All entries must be
2973 relative to the workspace root, e.g. build/classes/main. (optional)
2974 :arg bool sandbox: Execute script inside of groovy sandbox (default false)
2975
2976 Example:
2977
2978 .. literalinclude:: /../../tests/builders/fixtures/dsl001.yaml
2979 :language: yaml
2980 .. literalinclude:: /../../tests/builders/fixtures/dsl002.yaml
2981 :language: yaml
2982
2983 """
2984
2985 dsl = XML.SubElement(xml_parent, "javaposse.jobdsl.plugin.ExecuteDslScripts")
2986
2987 if "target" in data:
2988 if "targets" not in data:
2989 logger.warning(
2990 "Converting from old format of 'target' to new "
2991 "name 'targets', please update your job "
2992 "definitions."
2993 )
2994 data["targets"] = data["target"]
2995 else:
2996 logger.warning(
2997 "Ignoring old argument 'target' in favour of new "
2998 "format argument 'targets', please remove old "
2999 "format."
3000 )
3001
3002 if data.get("script-text"):
3003 XML.SubElement(dsl, "scriptText").text = data.get("script-text")
3004 XML.SubElement(dsl, "usingScriptText").text = "true"
3005 elif data.get("targets"):
3006 XML.SubElement(dsl, "targets").text = data.get("targets")
3007 XML.SubElement(dsl, "usingScriptText").text = "false"
3008 else:
3009 raise MissingAttributeError(["script-text", "target"])
3010
3011 XML.SubElement(dsl, "sandbox").text = str(data.get("sandbox", "false")).lower()
3012
3013 XML.SubElement(dsl, "ignoreExisting").text = str(
3014 data.get("ignore-existing", False)
3015 ).lower()
3016
3017 supportedJobActions = ["IGNORE", "DISABLE", "DELETE"]
3018 removedJobAction = data.get("removed-job-action", supportedJobActions[0])
3019 if removedJobAction not in supportedJobActions:
3020 raise InvalidAttributeError(
3021 "removed-job-action", removedJobAction, supportedJobActions
3022 )
3023 XML.SubElement(dsl, "removedJobAction").text = removedJobAction
3024
3025 supportedViewActions = ["IGNORE", "DELETE"]
3026 removedViewAction = data.get("removed-view-action", supportedViewActions[0])
3027 if removedViewAction not in supportedViewActions:
3028 raise InvalidAttributeError(
3029 "removed-view-action", removedViewAction, supportedViewActions
3030 )
3031 XML.SubElement(dsl, "removedViewAction").text = removedViewAction
3032
3033 supportedLookupActions = ["JENKINS_ROOT", "SEED_JOB"]
3034 lookupStrategy = data.get("lookup-strategy", supportedLookupActions[0])
3035 if lookupStrategy not in supportedLookupActions:
3036 raise InvalidAttributeError(
3037 "lookup-strategy", lookupStrategy, supportedLookupActions
3038 )
3039 XML.SubElement(dsl, "lookupStrategy").text = lookupStrategy
3040
3041 XML.SubElement(dsl, "additionalClasspath").text = data.get("additional-classpath")
3042
3043
3044 def github_notifier(registry, xml_parent, data):
3045 """yaml: github-notifier
3046 Set pending build status on Github commit.
3047
3048 Requires the Jenkins :jenkins-plugins:`Github Plugin <github>`.
3049
3050 Example:
3051
3052 .. literalinclude:: /../../tests/builders/fixtures/github-notifier.yaml
3053 :language: yaml
3054 """
3055 XML.SubElement(xml_parent, "com.cloudbees.jenkins.GitHubSetCommitStatusBuilder")
3056
3057
3058 def scan_build(registry, xml_parent, data):
3059 """yaml: scan-build
3060 This plugin allows you configure a build step that will execute the Clang
3061 scan-build static analysis tool against an XCode project.
3062
3063 The scan-build report has to be generated in the directory
3064 ``${WORKSPACE}/clangScanBuildReports`` for the publisher to find it.
3065
3066 Requires the Jenkins :jenkins-plugins:`Clang Scan-Build Plugin
3067 <clang-scanbuild>`.
3068
3069 :arg str target: Provide the exact name of the XCode target you wish to
3070 have compiled and analyzed (required)
3071 :arg str target-sdk: Set the simulator version of a currently installed SDK
3072 (default iphonesimulator)
3073 :arg str config: Provide the XCode config you wish to execute scan-build
3074 against (default Debug)
3075 :arg str clang-install-name: Name of clang static analyzer to use (default
3076 '')
3077 :arg str xcode-sub-path: Path of XCode project relative to the workspace
3078 (default '')
3079 :arg str workspace: Name of workspace (default '')
3080 :arg str scheme: Name of scheme (default '')
3081 :arg str scan-build-args: Additional arguments to clang scan-build
3082 (default --use-analyzer Xcode)
3083 :arg str xcode-build-args: Additional arguments to XCode (default
3084 -derivedDataPath $WORKSPACE/build)
3085 :arg str report-folder: Folder where generated reports are located
3086 (>=1.7) (default clangScanBuildReports)
3087
3088 Full Example:
3089
3090 .. literalinclude:: /../../tests/builders/fixtures/scan-build-full.yaml
3091 :language: yaml
3092
3093 Minimal Example:
3094
3095 .. literalinclude::
3096 /../../tests/builders/fixtures/scan-build-minimal.yaml
3097 :language: yaml
3098 """
3099 p = XML.SubElement(
3100 xml_parent, "jenkins.plugins.clangscanbuild.ClangScanBuildBuilder"
3101 )
3102 p.set("plugin", "clang-scanbuild")
3103
3104 mappings = [
3105 ("target", "target", None),
3106 ("target-sdk", "targetSdk", "iphonesimulator"),
3107 ("config", "config", "Debug"),
3108 ("clang-install-name", "clangInstallationName", ""),
3109 ("xcode-sub-path", "xcodeProjectSubPath", "myProj/subfolder"),
3110 ("workspace", "workspace", ""),
3111 ("scheme", "scheme", ""),
3112 ("scan-build-args", "scanbuildargs", "--use-analyzer Xcode"),
3113 ("xcode-build-args", "xcodebuildargs", "-derivedDataPath $WORKSPACE/build"),
3114 ("report-folder", "outputFolderName", "clangScanBuildReports"),
3115 ]
3116 helpers.convert_mapping_to_xml(p, data, mappings, fail_required=True)
3117
3118
3119 def ssh_builder(registry, xml_parent, data):
3120 """yaml: ssh-builder
3121 Executes command on remote host
3122
3123 Requires the Jenkins :jenkins-plugins:`SSH plugin <ssh>`.
3124
3125 :arg str ssh-user-ip: user@ip:ssh_port of machine that was defined
3126 in jenkins according to SSH plugin instructions
3127 :arg str command: command to run on remote server
3128
3129 Example:
3130
3131 .. literalinclude:: /../../tests/builders/fixtures/ssh-builder.yaml
3132 :language: yaml
3133 """
3134 builder = XML.SubElement(xml_parent, "org.jvnet.hudson.plugins.SSHBuilder")
3135
3136 mapping = [("ssh-user-ip", "siteName", None), ("command", "command", None)]
3137 helpers.convert_mapping_to_xml(builder, data, mapping, fail_required=True)
3138
3139
3140 def sonar(registry, xml_parent, data):
3141 """yaml: sonar
3142 Invoke standalone Sonar analysis.
3143
3144 Requires the Jenkins `Sonar Plugin
3145 <https://docs.sonarsource.com/sonarqube/latest/analyzing-source-code/scanners/jenkins-extension-sonarqube/>`_.
3146
3147 :arg str sonar-name: Name of the Sonar installation.
3148 :arg str sonar-scanner: Name of the Sonar Scanner.
3149 :arg str task: Task to run. (default '')
3150 :arg str project: Path to Sonar project properties file. (default '')
3151 :arg str properties: Sonar configuration properties. (default '')
3152 :arg str java-opts: Java options for Sonnar Runner. (default '')
3153 :arg str additional-arguments: additional command line arguments
3154 (default '')
3155 :arg str jdk: JDK to use (inherited from the job if omitted). (optional)
3156
3157 Example:
3158
3159 .. literalinclude:: /../../tests/builders/fixtures/sonar.yaml
3160 :language: yaml
3161 """
3162 sonar = XML.SubElement(xml_parent, "hudson.plugins.sonar.SonarRunnerBuilder")
3163 sonar.set("plugin", "sonar")
3164 XML.SubElement(sonar, "installationName").text = data["sonar-name"]
3165 mappings = [
3166 ("scanner-name", "sonarScannerName", ""),
3167 ("task", "task", ""),
3168 ("project", "project", ""),
3169 ("properties", "properties", ""),
3170 ("java-opts", "javaOpts", ""),
3171 ("additional-arguments", "additionalArguments", ""),
3172 ]
3173 helpers.convert_mapping_to_xml(sonar, data, mappings, fail_required=True)
3174 if "jdk" in data:
3175 XML.SubElement(sonar, "jdk").text = data["jdk"]
3176
3177
3178 def xcode(registry, xml_parent, data):
3179 """yaml: xcode
3180 This step allows you to execute an xcode build step.
3181
3182 Requires the Jenkins :jenkins-plugins:`Xcode Plugin <xcode-plugin>`.
3183
3184 :arg str developer-profile: the jenkins credential id for a
3185 ios developer profile. (optional)
3186 :arg bool clean-build: if true will delete the build directories
3187 before invoking the build. (default false)
3188 :arg bool clean-test-reports: UNKNOWN. (default false)
3189 :arg bool archive: if true will generate an xcarchive of the specified
3190 scheme. A workspace and scheme are are also needed for archives.
3191 (default false)
3192 :arg str configuration: This is the name of the configuration
3193 as defined in the Xcode project. (default 'Release')
3194 :arg str configuration-directory: The value to use for
3195 CONFIGURATION_BUILD_DIR setting. (default '')
3196 :arg str target: Leave empty for all targets. (default '')
3197 :arg str sdk: Leave empty for default SDK. (default '')
3198 :arg str symroot: Leave empty for default SYMROOT. (default '')
3199 :arg str project-path: Relative path within the workspace
3200 that contains the xcode project file(s). (default '')
3201 :arg str project-file: Only needed if there is more than one
3202 project file in the Xcode Project Directory. (default '')
3203 :arg str build-arguments: Extra commandline arguments provided
3204 to the xcode builder. (default '')
3205 :arg str schema: Only needed if you want to compile for a
3206 specific schema instead of a target. (default '')
3207 :arg str workspace: Only needed if you want to compile a
3208 workspace instead of a project. (default '')
3209 :arg str profile: The relative path to the mobileprovision to embed,
3210 leave blank for no embedded profile. (default '')
3211 :arg str codesign-id: Override the code signing identity specified
3212 in the project. (default '')
3213 :arg bool allow-failing: if true will prevent this build step from
3214 failing if xcodebuild exits with a non-zero return code. (default
3215 false)
3216 :arg str version-technical: The value to use for CFBundleVersion.
3217 Leave blank to use project's technical number. (default '')
3218 :arg str version-marketing: The value to use for
3219 CFBundleShortVersionString. Leave blank to use project's
3220 marketing number. (default '')
3221 :arg str ipa-export-method: The export method of the .app to generate the
3222 .ipa file. Should be one in 'development', 'ad-hoc', 'enterprise',
3223 or 'app-store'. (default '')
3224 :arg str ipa-version: A pattern for the ipa file name. You may use
3225 ${VERSION} and ${BUILD_DATE} (yyyy.MM.dd) in this string.
3226 (default '')
3227 :arg str ipa-output: The output directory for the .ipa file,
3228 relative to the build directory. (default '')
3229 :arg bool compile-bitcode: recompile from Bitcode when exporting the
3230 application to IPA. (default true)
3231 :arg bool upload-bitcode: include Bitcode when exporting applications to
3232 IPA. (default true)
3233 :arg bool upload-symbols: include symbols when exporting applications to
3234 IPA. (default true)
3235 :arg development-team-id: The ID of the Apple development team to use to
3236 sign the IPA (default '')
3237 :arg str keychain-name: The globally configured keychain to unlock for
3238 this build. (default '')
3239 :arg str keychain-path: The path of the keychain to use to sign the IPA.
3240 (default '')
3241 :arg str keychain-password: The password to use to unlock the keychain.
3242 (default '')
3243 :arg str keychain-unlock: Unlocks the keychain during use.
3244 (default false)
3245 :arg str bundle-id: The bundle identifier (App ID) for this provisioning
3246 profile (default '')
3247 :arg str provisioning-profile-uuid: The UUID of the provisioning profile
3248 associated to this bundle identifier. (default '')
3249
3250 Example:
3251
3252 .. literalinclude:: /../../tests/builders/fixtures/xcode.yaml
3253 :language: yaml
3254 """
3255
3256 if data.get("developer-profile"):
3257 profile = XML.SubElement(xml_parent, "au.com.rayh." "DeveloperProfileLoader")
3258 mapping = [("developer-profile", "id", None)]
3259 helpers.convert_mapping_to_xml(profile, data, mapping, fail_required=False)
3260
3261 xcode = XML.SubElement(xml_parent, "au.com.rayh.XCodeBuilder")
3262
3263 mappings = [
3264 ("clean-build", "cleanBeforeBuild", False),
3265 ("clean-test-reports", "cleanTestReports", False),
3266 ("archive", "generateArchive", False),
3267 ("configuration", "configuration", "Release"),
3268 ("configuration-directory", "configurationBuildDir", ""),
3269 ("target", "target", ""),
3270 ("sdk", "sdk", ""),
3271 ("symroot", "symRoot", ""),
3272 ("project-path", "xcodeProjectPath", ""),
3273 ("project-file", "xcodeProjectFile", ""),
3274 ("build-arguments", "xcodebuildArguments", ""),
3275 ("schema", "xcodeSchema", ""),
3276 ("workspace", "xcodeWorkspaceFile", ""),
3277 ("profile", "embeddedProfileFile", ""),
3278 ("codesign-id", "codeSigningIdentity", ""),
3279 ("allow-failing", "allowFailingBuildResults", False),
3280 ]
3281 helpers.convert_mapping_to_xml(xcode, data, mappings, fail_required=True)
3282
3283 version = XML.SubElement(xcode, "provideApplicationVersion")
3284 version_technical = XML.SubElement(xcode, "cfBundleVersionValue")
3285 version_marketing = XML.SubElement(xcode, "cfBundleShortVersionStringValue")
3286
3287 if data.get("version-technical") or data.get("version-marketing"):
3288 version.text = "true"
3289 version_technical.text = data.get("version-technical", "")
3290 version_marketing.text = data.get("version-marketing", "")
3291 else:
3292 version.text = "false"
3293
3294 XML.SubElement(xcode, "buildIpa").text = str(
3295 bool(data.get("ipa-version")) or False
3296 ).lower()
3297
3298 valid_ipa_export_methods = ["", "ad-hoc", "app-store", "development"]
3299 mapping = [
3300 ("ipa-export-method", "ipaExportMethod", "", valid_ipa_export_methods),
3301 ("ipa-version", "ipaName", ""),
3302 ("ipa-output", "ipaOutputDirectory", ""),
3303 ("development-team-id", "developmentTeamID", ""),
3304 ("keychain-name", "keychainName", ""),
3305 ("keychain-path", "keychainPath", ""),
3306 ("keychain-password", "keychainPwd", ""),
3307 ("keychain-unlock", "unlockKeychain", False),
3308 ("compile-bitcode", "compileBitcode", True),
3309 ("upload-bitcode", "uploadBitcode", True),
3310 ("upload-symbols", "uploadSymbols", True),
3311 ]
3312 helpers.convert_mapping_to_xml(xcode, data, mapping, fail_required=True)
3313
3314 has_provisioning_profiles = bool(data.get("provisioning-profiles"))
3315 XML.SubElement(xcode, "manualSigning").text = str(
3316 has_provisioning_profiles or False
3317 ).lower()
3318 if has_provisioning_profiles:
3319 provisioning_profiles_xml = XML.SubElement(xcode, "provisioningProfiles")
3320 mapping = [
3321 ("bundle-id", "provisioningProfileAppId", ""),
3322 ("provisioning-profile-uuid", "provisioningProfileUUID", ""),
3323 ]
3324 for provisioning_profile in data.get("provisioning-profiles"):
3325 provisioning_profile_xml = XML.SubElement(
3326 provisioning_profiles_xml, "au.com.rayh.ProvisioningProfile"
3327 )
3328 helpers.convert_mapping_to_xml(
3329 provisioning_profile_xml,
3330 provisioning_profile,
3331 mapping,
3332 fail_required=True,
3333 )
3334
3335
3336 def sonatype_clm(registry, xml_parent, data):
3337 """yaml: sonatype-clm
3338 Requires the Jenkins Sonatype CLM Plugin.
3339
3340 WARNING: This plugin appears to be deprecated. There does not seem
3341 to be any place where it is available for download.
3342
3343 Try the :py:yamlfunction:`nexus-artifact-uploader` plugin instead.
3344
3345 :arg str value: Select CLM application from a list of available CLM
3346 applications or specify CLM Application ID (default list)
3347 :arg str application-name: Determines the policy elements to associate
3348 with this build. (required)
3349 :arg str username: Username on the Sonatype CLM server. Leave empty to
3350 use the username configured at global level. (default '')
3351 :arg str password: Password on the Sonatype CLM server. Leave empty to
3352 use the password configured at global level. (default '')
3353 :arg bool fail-on-clm-server-failure: Controls the build outcome if there
3354 is a failure in communicating with the CLM server. (default false)
3355 :arg str stage: Controls the stage the policy evaluation will be run
3356 against on the CLM server. Valid stages: build, stage-release, release,
3357 operate. (default 'build')
3358 :arg str scan-targets: Pattern of files to include for scanning.
3359 (default '')
3360 :arg str module-excludes: Pattern of files to exclude. (default '')
3361 :arg str advanced-options: Options to be set on a case-by-case basis as
3362 advised by Sonatype Support. (default '')
3363
3364 Minimal Example:
3365
3366 .. literalinclude::
3367 /../../tests/builders/fixtures/sonatype-clm-minimal.yaml
3368 :language: yaml
3369
3370 Full Example:
3371
3372 .. literalinclude::
3373 /../../tests/builders/fixtures/sonatype-clm-full.yaml
3374 :language: yaml
3375 """
3376 clm = XML.SubElement(xml_parent, "com.sonatype.insight.ci.hudson.PreBuildScan")
3377 clm.set("plugin", "sonatype-clm-ci")
3378 SUPPORTED_VALUES = ["list", "manual"]
3379 SUPPORTED_STAGES = ["build", "stage-release", "release", "operate"]
3380
3381 application_select = XML.SubElement(clm, "applicationSelectType")
3382 application_mappings = [
3383 ("value", "value", "list", SUPPORTED_VALUES),
3384 ("application-name", "applicationId", None),
3385 ]
3386 helpers.convert_mapping_to_xml(
3387 application_select, data, application_mappings, fail_required=True
3388 )
3389
3390 path = XML.SubElement(clm, "pathConfig")
3391 path_mappings = [
3392 ("scan-targets", "scanTargets", ""),
3393 ("module-excludes", "moduleExcludes", ""),
3394 ("advanced-options", "scanProperties", ""),
3395 ]
3396 helpers.convert_mapping_to_xml(path, data, path_mappings, fail_required=True)
3397
3398 mappings = [
3399 ("fail-on-clm-server-failure", "failOnClmServerFailures", False),
3400 ("stage", "stageId", "build", SUPPORTED_STAGES),
3401 ("username", "username", ""),
3402 ("password", "password", ""),
3403 ]
3404 helpers.convert_mapping_to_xml(clm, data, mappings, fail_required=True)
3405
3406
3407 def beaker(registry, xml_parent, data):
3408 """yaml: beaker
3409 Execute a beaker build step.
3410
3411 Requires the Jenkins :jenkins-plugins:`Beaker Builder Plugin
3412 <beaker-builder>`.
3413
3414 :arg str content: Run job from string
3415 (Alternative: you can choose a path instead)
3416 :arg str path: Run job from file
3417 (Alternative: you can choose a content instead)
3418 :arg bool download-logs: Download Beaker log files (default false)
3419
3420 Example:
3421
3422 .. literalinclude:: ../../tests/builders/fixtures/beaker-path.yaml
3423 :language: yaml
3424
3425 .. literalinclude:: ../../tests/builders/fixtures/beaker-content.yaml
3426 :language: yaml
3427 """
3428 beaker = XML.SubElement(
3429 xml_parent, "org.jenkinsci.plugins.beakerbuilder." "BeakerBuilder"
3430 )
3431 jobSource = XML.SubElement(beaker, "jobSource")
3432 if "content" in data and "path" in data:
3433 raise JenkinsJobsException("Use just one of 'content' or 'path'")
3434 elif "content" in data:
3435 jobSourceClass = "org.jenkinsci.plugins.beakerbuilder.StringJobSource"
3436 jobSource.set("class", jobSourceClass)
3437 XML.SubElement(jobSource, "jobContent").text = data["content"]
3438 elif "path" in data:
3439 jobSourceClass = "org.jenkinsci.plugins.beakerbuilder.FileJobSource"
3440 jobSource.set("class", jobSourceClass)
3441 XML.SubElement(jobSource, "jobPath").text = data["path"]
3442 else:
3443 raise JenkinsJobsException("Use one of 'content' or 'path'")
3444
3445 XML.SubElement(beaker, "downloadFiles").text = str(
3446 data.get("download-logs", False)
3447 ).lower()
3448
3449
3450 def cloudformation(registry, xml_parent, data):
3451 """yaml: cloudformation
3452 Create cloudformation stacks before running a build and optionally
3453 delete them at the end.
3454
3455 Requires the Jenkins :jenkins-plugins:`AWS Cloudformation Plugin
3456 <jenkins-cloudformation-plugin>`.
3457
3458 :arg list name: The names of the stacks to create (required)
3459 :arg str description: Description of the stack (optional)
3460 :arg str recipe: The cloudformation recipe file (required)
3461 :arg list parameters: List of key/value pairs to pass
3462 into the recipe, will be joined together into a comma separated
3463 string (optional)
3464 :arg int timeout: Number of seconds to wait before giving up creating
3465 a stack (default 0)
3466 :arg str access-key: The Amazon API Access Key (required)
3467 :arg str secret-key: The Amazon API Secret Key (required)
3468 :arg int sleep: Number of seconds to wait before continuing to the
3469 next step (default 0)
3470 :arg str region: The region to run cloudformation in (required)
3471
3472 :region values:
3473 * **us-east-1**
3474 * **us-west-1**
3475 * **us-west-2**
3476 * **eu-central-1**
3477 * **eu-west-1**
3478 * **ap-southeast-1**
3479 * **ap-southeast-2**
3480 * **ap-northeast-1**
3481 * **sa-east-1**
3482
3483 Example:
3484
3485 .. literalinclude:: ../../tests/builders/fixtures/cloudformation.yaml
3486 :language: yaml
3487 """
3488 region_dict = helpers.cloudformation_region_dict()
3489 stacks = helpers.cloudformation_init(xml_parent, data, "CloudFormationBuildStep")
3490 for stack in data:
3491 helpers.cloudformation_stack(
3492 xml_parent, stack, "PostBuildStackBean", stacks, region_dict
3493 )
3494
3495
3496 def jms_messaging(registry, xml_parent, data):
3497 """yaml: jms-messaging
3498 The JMS Messaging Plugin provides the following functionality:
3499 - A build trigger to submit jenkins jobs upon receipt
3500 of a matching message.
3501 - A builder that may be used to submit a message to the topic
3502 upon the completion of a job
3503 - A post-build action that may be used to submit a message to the topic
3504 upon the completion of a job
3505
3506
3507 JMS Messaging provider types supported:
3508 - ActiveMQ
3509 - FedMsg
3510
3511 Requires the Jenkins :jenkins-plugins:`JMS Messaging Plugin Pipeline Plugin
3512 <jms-messaging>`.
3513
3514 :arg str override-topic: If you need to override the default topic.
3515 (default '')
3516 :arg str provider-name: Name of message provider setup in the
3517 global config. (default '')
3518 :arg str msg-type: A message type
3519 (default 'CodeQualityChecksDone')
3520 :arg str msg-props: Message header to publish. (default '')
3521 :arg str msg-content: Message body to publish. (default '')
3522
3523
3524 Full Example:
3525
3526 .. literalinclude::
3527 ../../tests/builders/fixtures/jms-messaging-full.yaml
3528 :language: yaml
3529
3530 Minimal Example:
3531
3532 .. literalinclude::
3533 ../../tests/builders/fixtures/jms-messaging-minimal.yaml
3534 :language: yaml
3535 """
3536 helpers.jms_messaging_common(
3537 xml_parent, "com.redhat.jenkins.plugins.ci." "CIMessageBuilder", data
3538 )
3539
3540
3541 def openshift_build_verify(registry, xml_parent, data):
3542 r"""yaml: openshift-build-verify
3543 Performs the equivalent of an 'oc get builds` command invocation for the
3544 provided buildConfig key provided; once the list of builds are obtained,
3545 the state of the latest build is inspected for up to a minute to see if
3546 it has completed successfully.
3547
3548 Requires the Jenkins :jenkins-plugins:`OpenShift Pipeline Plugin
3549 <openshift-pipeline>`.
3550
3551 :arg str api-url: this would be the value you specify if you leverage the
3552 --server option on the OpenShift `oc` command.
3553 (default '\https://openshift.default.svc.cluster.local')
3554 :arg str bld-cfg: The value here should be whatever was the output
3555 form `oc project` when you created the BuildConfig you
3556 want to run a Build on (default 'frontend')
3557 :arg str namespace: If you run `oc get bc` for the project listed in
3558 "namespace", that is the value you want to put here. (default 'test')
3559 :arg str auth-token: The value here is what you supply with the --token
3560 option when invoking the OpenShift `oc` command. (default '')
3561 :arg bool verbose: This flag is the toggle for
3562 turning on or off detailed logging in this plug-in. (default false)
3563
3564 Full Example:
3565
3566 .. literalinclude::
3567 ../../tests/builders/fixtures/openshift-build-verify001.yaml
3568 :language: yaml
3569
3570 Minimal Example:
3571
3572 .. literalinclude::
3573 ../../tests/builders/fixtures/openshift-build-verify002.yaml
3574 :language: yaml
3575 """
3576 osb = XML.SubElement(
3577 xml_parent, "com.openshift.jenkins.plugins.pipeline." "OpenShiftBuildVerifier"
3578 )
3579
3580 mapping = [
3581 # option, xml name, default value
3582 ("api-url", "apiURL", "https://openshift.default.svc.cluster.local"),
3583 ("bld-cfg", "bldCfg", "frontend"),
3584 ("namespace", "namespace", "test"),
3585 ("auth-token", "authToken", ""),
3586 ("verbose", "verbose", False),
3587 ]
3588 helpers.convert_mapping_to_xml(osb, data, mapping, fail_required=True)
3589
3590
3591 def openshift_builder(registry, xml_parent, data):
3592 r"""yaml: openshift-builder
3593 Perform builds in OpenShift for the job.
3594
3595 Requires the Jenkins :jenkins-plugins:`OpenShift Pipeline Plugin
3596 <openshift-pipeline>`.
3597
3598 :arg str api-url: this would be the value you specify if you leverage the
3599 --server option on the OpenShift `oc` command.
3600 (default '\https://openshift.default.svc.cluster.local')
3601 :arg str bld-cfg: The value here should be whatever was the output
3602 form `oc project` when you created the BuildConfig you want to run a
3603 Build on (default 'frontend')
3604 :arg str namespace: If you run `oc get bc` for the project listed in
3605 "namespace", that is the value you want to put here. (default 'test')
3606 :arg str auth-token: The value here is what you supply with the --token
3607 option when invoking the OpenShift `oc` command. (default '')
3608 :arg str commit-ID: The value here is what you supply with the
3609 --commit option when invoking the
3610 OpenShift `oc start-build` command. (default '')
3611 :arg bool verbose: This flag is the toggle for
3612 turning on or off detailed logging in this plug-in. (default false)
3613 :arg str build-name: TThe value here is what you supply with the
3614 --from-build option when invoking the
3615 OpenShift `oc start-build` command. (default '')
3616 :arg bool show-build-logs: Indicates whether the build logs get dumped
3617 to the console of the Jenkins build. (default false)
3618
3619
3620 Full Example:
3621
3622 .. literalinclude:: ../../tests/builders/fixtures/openshift-builder001.yaml
3623 :language: yaml
3624
3625 Minimal Example:
3626
3627 .. literalinclude:: ../../tests/builders/fixtures/openshift-builder002.yaml
3628 :language: yaml
3629 """
3630 osb = XML.SubElement(
3631 xml_parent, "com.openshift.jenkins.plugins.pipeline." "OpenShiftBuilder"
3632 )
3633
3634 mapping = [
3635 # option, xml name, default value
3636 ("api-url", "apiURL", "https://openshift.default.svc.cluster.local"),
3637 ("bld-cfg", "bldCfg", "frontend"),
3638 ("namespace", "namespace", "test"),
3639 ("auth-token", "authToken", ""),
3640 ("commit-ID", "commitID", ""),
3641 ("verbose", "verbose", False),
3642 ("build-name", "buildName", ""),
3643 ("show-build-logs", "showBuildLogs", False),
3644 ]
3645 helpers.convert_mapping_to_xml(osb, data, mapping, fail_required=True)
3646
3647
3648 def openshift_creator(registry, xml_parent, data):
3649 r"""yaml: openshift-creator
3650 Performs the equivalent of an oc create command invocation;
3651 this build step takes in the provided JSON or YAML text, and if it
3652 conforms to OpenShift schema, creates whichever
3653 OpenShift resources are specified.
3654
3655 Requires the Jenkins :jenkins-plugins:`OpenShift Pipeline Plugin
3656 <openshift-pipeline>`.
3657
3658 :arg str api-url: this would be the value you specify if you leverage the
3659 --server option on the OpenShift `oc` command.
3660 (default '\https://openshift.default.svc.cluster.local')
3661 :arg str jsonyaml: The JSON or YAML formatted text that conforms to
3662 the schema for defining the various OpenShift resources. (default '')
3663 :arg str namespace: If you run `oc get bc` for the project listed in
3664 "namespace", that is the value you want to put here. (default 'test')
3665 :arg str auth-token: The value here is what you supply with the --token
3666 option when invoking the OpenShift `oc` command. (default '')
3667 :arg bool verbose: This flag is the toggle for
3668 turning on or off detailed logging in this plug-in. (default false)
3669
3670 Full Example:
3671
3672 .. literalinclude::
3673 ../../tests/builders/fixtures/openshift-creator001.yaml
3674 :language: yaml
3675
3676 Minimal Example:
3677
3678 .. literalinclude::
3679 ../../tests/builders/fixtures/openshift-creator002.yaml
3680 :language: yaml
3681 """
3682 osb = XML.SubElement(
3683 xml_parent, "com.openshift.jenkins.plugins.pipeline." "OpenShiftCreator"
3684 )
3685
3686 mapping = [
3687 # option, xml name, default value
3688 ("api-url", "apiURL", "https://openshift.default.svc.cluster.local"),
3689 ("jsonyaml", "jsonyaml", ""),
3690 ("namespace", "namespace", "test"),
3691 ("auth-token", "authToken", ""),
3692 ("verbose", "verbose", False),
3693 ]
3694 helpers.convert_mapping_to_xml(osb, data, mapping, fail_required=True)
3695
3696
3697 def openshift_dep_verify(registry, xml_parent, data):
3698 r"""yaml: openshift-dep-verify
3699 Determines whether the expected set of DeploymentConfig's,
3700 ReplicationController's, and active replicas are present based on prior
3701 use of the scaler (2) and deployer (3) steps
3702
3703 Requires the Jenkins :jenkins-plugins:`OpenShift Pipeline Plugin
3704 <openshift-pipeline>`.
3705
3706 :arg str api-url: this would be the value you specify if you leverage the
3707 --server option on the OpenShift `oc` command.
3708 (default \https://openshift.default.svc.cluster.local\)
3709 :arg str dep-cfg: The value here should be whatever was the output
3710 form `oc project` when you created the BuildConfig you want to run a
3711 Build on (default frontend)
3712 :arg str namespace: If you run `oc get bc` for the project listed in
3713 "namespace", that is the value you want to put here. (default test)
3714 :arg int replica-count: The value here should be whatever the number
3715 of pods you want started for the deployment. (default 0)
3716 :arg str auth-token: The value here is what you supply with the --token
3717 option when invoking the OpenShift `oc` command. (default '')
3718 :arg bool verbose: This flag is the toggle for
3719 turning on or off detailed logging in this plug-in. (default false)
3720
3721 Full Example:
3722
3723 .. literalinclude::
3724 ../../tests/builders/fixtures/openshift-dep-verify001.yaml
3725 :language: yaml
3726
3727 Minimal Example:
3728
3729 .. literalinclude::
3730 ../../tests/builders/fixtures/openshift-dep-verify002.yaml
3731 :language: yaml
3732 """
3733 osb = XML.SubElement(
3734 xml_parent,
3735 "com.openshift.jenkins.plugins.pipeline." "OpenShiftDeploymentVerifier",
3736 )
3737
3738 mapping = [
3739 # option, xml name, default value
3740 ("api-url", "apiURL", "https://openshift.default.svc.cluster.local"),
3741 ("dep-cfg", "depCfg", "frontend"),
3742 ("namespace", "namespace", "test"),
3743 ("replica-count", "replicaCount", 0),
3744 ("auth-token", "authToken", ""),
3745 ("verbose", "verbose", False),
3746 ]
3747 helpers.convert_mapping_to_xml(osb, data, mapping, fail_required=True)
3748
3749
3750 def openshift_deployer(registry, xml_parent, data):
3751 r"""yaml: openshift-deployer
3752 Start a deployment in OpenShift for the job.
3753
3754 Requires the Jenkins :jenkins-plugins:`OpenShift Pipeline Plugin
3755 <openshift-pipeline>`.
3756
3757 :arg str api-url: this would be the value you specify if you leverage the
3758 --server option on the OpenShift `oc` command.
3759 (default '\https://openshift.default.svc.cluster.local')
3760 :arg str dep-cfg: The value here should be whatever was the output
3761 form `oc project` when you created the BuildConfig you want to run a
3762 Build on (default 'frontend')
3763 :arg str namespace: If you run `oc get bc` for the project listed in
3764 "namespace", that is the value you want to put here. (default 'test')
3765 :arg str auth-token: The value here is what you supply with the --token
3766 option when invoking the OpenShift `oc` command. (default '')
3767 :arg bool verbose: This flag is the toggle for
3768 turning on or off detailed logging in this plug-in. (default false)
3769
3770 Full Example:
3771
3772 .. literalinclude::
3773 ../../tests/builders/fixtures/openshift-deployer001.yaml
3774 :language: yaml
3775
3776 Minimal Example:
3777
3778 .. literalinclude::
3779 ../../tests/builders/fixtures/openshift-deployer002.yaml
3780 :language: yaml
3781 """
3782 osb = XML.SubElement(
3783 xml_parent, "com.openshift.jenkins.plugins.pipeline." "OpenShiftDeployer"
3784 )
3785
3786 mapping = [
3787 # option, xml name, default value
3788 ("api-url", "apiURL", "https://openshift.default.svc.cluster.local"),
3789 ("dep-cfg", "depCfg", "frontend"),
3790 ("namespace", "namespace", "test"),
3791 ("auth-token", "authToken", ""),
3792 ("verbose", "verbose", False),
3793 ]
3794 helpers.convert_mapping_to_xml(osb, data, mapping, fail_required=True)
3795
3796
3797 def openshift_img_tagger(registry, xml_parent, data):
3798 r"""yaml: openshift-img-tagger
3799 Performs the equivalent of an oc tag command invocation in order to
3800 manipulate tags for images in OpenShift ImageStream's
3801
3802 Requires the Jenkins :jenkins-plugins:`OpenShift Pipeline Plugin
3803 <openshift-pipeline>`.
3804
3805 :arg str api-url: this would be the value you specify if you leverage the
3806 --server option on the OpenShift `oc` command.
3807 (default '\https://openshift.default.svc.cluster.local')
3808 :arg str test-tag: The equivalent to the name supplied to a
3809 `oc get service` command line invocation.
3810 (default 'origin-nodejs-sample:latest')
3811 :arg str prod-tag: The equivalent to the name supplied to a
3812 `oc get service` command line invocation.
3813 (default 'origin-nodejs-sample:prod')
3814 :arg str namespace: If you run `oc get bc` for the project listed in
3815 "namespace", that is the value you want to put here. (default 'test')
3816 :arg str auth-token: The value here is what you supply with the --token
3817 option when invoking the OpenShift `oc` command. (default '')
3818 :arg bool verbose: This flag is the toggle for
3819 turning on or off detailed logging in this plug-in. (default false)
3820
3821 Full Example:
3822
3823 .. literalinclude::
3824 ../../tests/builders/fixtures/openshift-img-tagger001.yaml
3825 :language: yaml
3826
3827 Minimal Example:
3828
3829 .. literalinclude::
3830 ../../tests/builders/fixtures/openshift-img-tagger002.yaml
3831 :language: yaml
3832 """
3833 osb = XML.SubElement(
3834 xml_parent, "com.openshift.jenkins.plugins.pipeline." "OpenShiftImageTagger"
3835 )
3836
3837 mapping = [
3838 # option, xml name, default value
3839 ("api-url", "apiURL", "https://openshift.default.svc.cluster.local"),
3840 ("test-tag", "testTag", "origin-nodejs-sample:latest"),
3841 ("prod-tag", "prodTag", "origin-nodejs-sample:prod"),
3842 ("namespace", "namespace", "test"),
3843 ("auth-token", "authToken", ""),
3844 ("verbose", "verbose", False),
3845 ]
3846 helpers.convert_mapping_to_xml(osb, data, mapping, fail_required=True)
3847
3848
3849 def openshift_scaler(registry, xml_parent, data):
3850 r"""yaml: openshift-scaler
3851 Scale deployments in OpenShift for the job.
3852
3853 Requires the Jenkins :jenkins-plugins:`OpenShift Pipeline Plugin
3854 <openshift-pipeline>`.
3855
3856 :arg str api-url: this would be the value you specify if you leverage the
3857 --server option on the OpenShift `oc` command.
3858 (default '\https://openshift.default.svc.cluster.local')
3859 :arg str dep-cfg: The value here should be whatever was the output
3860 form `oc project` when you created the BuildConfig you want to run a
3861 Build on (default 'frontend')
3862 :arg str namespace: If you run `oc get bc` for the project listed in
3863 "namespace", that is the value you want to put here. (default 'test')
3864 :arg int replica-count: The value here should be whatever the number
3865 of pods you want started for the deployment. (default 0)
3866 :arg str auth-token: The value here is what you supply with the --token
3867 option when invoking the OpenShift `oc` command. (default '')
3868 :arg bool verbose: This flag is the toggle for
3869 turning on or off detailed logging in this plug-in. (default false)
3870
3871 Full Example:
3872
3873 .. literalinclude:: ../../tests/builders/fixtures/openshift-scaler001.yaml
3874 :language: yaml
3875
3876 Minimal Example:
3877
3878 .. literalinclude:: ../../tests/builders/fixtures/openshift-scaler002.yaml
3879 :language: yaml
3880 """
3881 osb = XML.SubElement(
3882 xml_parent, "com.openshift.jenkins.plugins.pipeline." "OpenShiftScaler"
3883 )
3884
3885 mapping = [
3886 # option, xml name, default value
3887 ("api-url", "apiURL", "https://openshift.default.svc.cluster.local"),
3888 ("dep-cfg", "depCfg", "frontend"),
3889 ("namespace", "namespace", "test"),
3890 ("replica-count", "replicaCount", 0),
3891 ("auth-token", "authToken", ""),
3892 ("verbose", "verbose", False),
3893 ]
3894 helpers.convert_mapping_to_xml(osb, data, mapping, fail_required=True)
3895
3896
3897 def openshift_svc_verify(registry, xml_parent, data):
3898 r"""yaml: openshift-svc-verify
3899 Verify a service is up in OpenShift for the job.
3900
3901 Requires the Jenkins :jenkins-plugins:`OpenShift Pipeline Plugin
3902 <openshift-pipeline>`.
3903
3904 :arg str api-url: this would be the value you specify if you leverage the
3905 --server option on the OpenShift `oc` command.
3906 (default '\https://openshift.default.svc.cluster.local')
3907 :arg str svc-name: The equivalent to the name supplied to a
3908 `oc get service` command line invocation. (default 'frontend')
3909 :arg str namespace: If you run `oc get bc` for the project listed in
3910 "namespace", that is the value you want to put here. (default 'test')
3911 :arg str auth-token: The value here is what you supply with the --token
3912 option when invoking the OpenShift `oc` command. (default '')
3913 :arg bool verbose: This flag is the toggle for
3914 turning on or off detailed logging in this plug-in. (default false)
3915
3916 Full Example:
3917
3918 .. literalinclude::
3919 ../../tests/builders/fixtures/openshift-svc-verify001.yaml
3920 :language: yaml
3921
3922 Minimal Example:
3923
3924 .. literalinclude::
3925 ../../tests/builders/fixtures/openshift-svc-verify002.yaml
3926 :language: yaml
3927 """
3928 osb = XML.SubElement(
3929 xml_parent, "com.openshift.jenkins.plugins.pipeline." "OpenShiftServiceVerifier"
3930 )
3931
3932 mapping = [
3933 # option, xml name, default value
3934 ("api-url", "apiURL", "https://openshift.default.svc.cluster.local"),
3935 ("svc-name", "svcName", "frontend"),
3936 ("namespace", "namespace", "test"),
3937 ("auth-token", "authToken", ""),
3938 ("verbose", "verbose", False),
3939 ]
3940 helpers.convert_mapping_to_xml(osb, data, mapping, fail_required=True)
3941
3942
3943 def runscope(registry, xml_parent, data):
3944 """yaml: runscope
3945 Execute a Runscope test.
3946
3947 Requires the Jenkins :jenkins-plugins:`Runscope Plugin <runscope>`.
3948
3949 :arg str test-trigger-url: Trigger URL for test. (required)
3950 :arg str access-token: OAuth Personal Access token. (required)
3951 :arg int timeout: Timeout for test duration in seconds. (default 60)
3952
3953 Minimal Example:
3954
3955 .. literalinclude:: /../../tests/builders/fixtures/runscope-minimal.yaml
3956 :language: yaml
3957
3958 Full Example:
3959
3960 .. literalinclude:: /../../tests/builders/fixtures/runscope-full.yaml
3961 :language: yaml
3962 """
3963 runscope = XML.SubElement(
3964 xml_parent, "com.runscope.jenkins.Runscope.RunscopeBuilder"
3965 )
3966 runscope.set("plugin", "runscope")
3967
3968 mapping = [
3969 ("test-trigger-url", "triggerEndPoint", None),
3970 ("access-token", "accessToken", None),
3971 ("timeout", "timeout", 60),
3972 ]
3973 helpers.convert_mapping_to_xml(runscope, data, mapping, fail_required=True)
3974
3975
3976 def description_setter(registry, xml_parent, data):
3977 """yaml: description-setter
3978 This plugin sets the description for each build,
3979 based upon a RegEx test of the build log file.
3980
3981 Requires the Jenkins :jenkins-plugins:`Description Setter Plugin
3982 <description-setter>`.
3983
3984 :arg str regexp: A RegEx which is used to scan the build log file
3985 (default '')
3986 :arg str description: The description to set on the build (optional)
3987
3988 Example:
3989
3990 .. literalinclude::
3991 /../../tests/builders/fixtures/description-setter001.yaml
3992 :language: yaml
3993 """
3994
3995 descriptionsetter = XML.SubElement(
3996 xml_parent, "hudson.plugins.descriptionsetter.DescriptionSetterBuilder"
3997 )
3998 mapping = [("regexp", "regexp", "")]
3999 if "description" in data:
4000 mapping.append(("description", "description", None))
4001 helpers.convert_mapping_to_xml(descriptionsetter, data, mapping, fail_required=True)
4002
4003
4004 def build_publish_docker_image(registry, xml_parent, data):
4005 """yaml: build-publish-docker-image
4006 Provides the ability to build projects with a Dockerfile and publish the
4007 resultant tagged image (repo) to the docker registry.
4008
4009 Requires the Jenkins :jenkins-plugins:`CloudBees Docker Build and Publish
4010 plugin <docker-build-publish>`.
4011
4012 :arg str docker-registry-url: URL to the Docker registry you are
4013 using (default '')
4014 :arg str image: Repository name to be applied to the resulting image
4015 in case of success (default '')
4016 :arg str docker-file-directory: Build step that sends a Dockerfile for
4017 building to docker host that used for this build run (default '')
4018 :arg bool push-on-success: Resulting docker image will be pushed to
4019 the registry (or registries) specified within the
4020 "Image" field (default false)
4021 :arg str push-credentials-id: Credentials to push to a private
4022 registry (default '')
4023 :arg bool clean-images: Option to clean local images (default false)
4024 :arg bool jenkins-job-delete: Attempt to remove images when jenkins
4025 deletes the run (default false)
4026 :arg str cloud: Cloud to use to build image (default '')
4027
4028 Minimal example:
4029
4030 .. literalinclude::
4031 /../../tests/builders/fixtures/build-publish-docker-image-minimal.yaml
4032
4033 Full example:
4034
4035 .. literalinclude::
4036 /../../tests/builders/fixtures/build-publish-docker-image-full.yaml
4037 """
4038 dbp = XML.SubElement(
4039 xml_parent,
4040 "com.nirima.jenkins.plugins.docker.builder" ".DockerBuilderPublisher",
4041 )
4042 dbp.set("plugin", "docker-plugin")
4043
4044 from_registry = XML.SubElement(dbp, "fromRegistry")
4045 from_registry.set("plugin", "docker-commons")
4046 from_registry_mapping = [("docker-registry-url", "url", "")]
4047 helpers.convert_mapping_to_xml(
4048 from_registry, data, from_registry_mapping, fail_required=False
4049 )
4050
4051 tags = XML.SubElement(dbp, "tags")
4052 XML.SubElement(tags, "string").text = data.get("image", "")
4053
4054 mapping = [
4055 ("docker-file-directory", "dockerFileDirectory", ""),
4056 ("push-on-success", "pushOnSuccess", False),
4057 ("push-credentials-id", "pushCredentialsId", ""),
4058 ("clean-images", "cleanImages", False),
4059 ("jenkins-job-delete", "cleanupWithJenkinsJobDelete", False),
4060 ("cloud", "cloud", ""),
4061 ]
4062 helpers.convert_mapping_to_xml(dbp, data, mapping, fail_required=False)
4063
4064
4065 def docker_build_publish(parse, xml_parent, data):
4066 """yaml: docker-build-publish
4067 Provides the ability to build projects with a Dockerfile, and publish the
4068 resultant tagged image (repo) to the docker registry.
4069
4070 Requires the Jenkins :jenkins-plugins:`Docker build publish Plugin
4071 <docker-build-publish>`.
4072
4073 :arg str repo-name: Name of repository to push to.
4074 :arg str repo-tag: Tag for image. (default '')
4075 :arg dict server: The docker daemon (optional)
4076
4077 * **uri** (str): Define the docker server to use. (optional)
4078 * **credentials-id** (str): ID of credentials to use to connect
4079 (optional)
4080 :arg dict registry: Registry to push to
4081
4082 * **url** (str) repository url to use (optional)
4083 * **credentials-id** (str): ID of credentials to use to connect
4084 (optional)
4085 :arg bool no-cache: If build should be cached. (default false)
4086 :arg bool no-force-pull: Don't update the source image before building when
4087 it exists locally. (default false)
4088 :arg bool skip-build: Do not build the image. (default false)
4089 :arg bool skip-decorate: Do not decorate the build name. (default false)
4090 :arg bool skip-tag-latest: Do not tag this build as latest. (default false)
4091 :arg bool skip-push: Do not push. (default false)
4092 :arg str file-path: Path of the Dockerfile. (default '')
4093 :arg str build-context: Project root path for the build, defaults to the
4094 workspace if not specified. (default '')
4095 :arg bool create-fingerprint: If enabled, the plugin will create
4096 fingerprints after the build of each image. (default false)
4097 :arg str build-args: Additional build arguments passed to
4098 docker build (default '')
4099 :arg bool force-tag: Force tag replacement when tag already
4100 exists (default false)
4101
4102 Minimal example:
4103
4104 .. literalinclude:: /../../tests/builders/fixtures/docker-builder001.yaml
4105
4106 Full example:
4107
4108 .. literalinclude:: /../../tests/builders/fixtures/docker-builder002.yaml
4109 """
4110 db = XML.SubElement(xml_parent, "com.cloudbees.dockerpublish.DockerBuilder")
4111 db.set("plugin", "docker-build-publish")
4112
4113 mapping = [
4114 ("repo-name", "repoName", None),
4115 ("repo-tag", "repoTag", ""),
4116 ("no-cache", "noCache", False),
4117 ("no-force-pull", "noForcePull", False),
4118 ("skip-build", "skipBuild", False),
4119 ("skip-decorate", "skipDecorate", False),
4120 ("skip-tag-latest", "skipTagLatest", False),
4121 ("skip-push", "skipPush", False),
4122 ("file-path", "dockerfilePath", ""),
4123 ("build-context", "buildContext", ""),
4124 ("create-fingerprint", "createFingerprint", False),
4125 ("build-args", "buildAdditionalArgs", ""),
4126 ("force-tag", "forceTag", False),
4127 ]
4128 helpers.convert_mapping_to_xml(db, data, mapping, fail_required=True)
4129
4130 mapping = []
4131 if "server" in data:
4132 server = XML.SubElement(db, "server")
4133 server.set("plugin", "docker-commons")
4134 server_data = data["server"]
4135 if "credentials-id" in server_data:
4136 mapping.append(("credentials-id", "credentialsId", None))
4137
4138 if "uri" in server_data:
4139 mapping.append(("uri", "uri", None))
4140 helpers.convert_mapping_to_xml(server, server_data, mapping, fail_required=True)
4141
4142 mappings = []
4143 if "registry" in data:
4144 registry = XML.SubElement(db, "registry")
4145 registry.set("plugin", "docker-commons")
4146 registry_data = data["registry"]
4147 if "credentials-id" in registry_data:
4148 mappings.append(("credentials-id", "credentialsId", None))
4149
4150 if "url" in registry_data:
4151 mappings.append(("url", "url", None))
4152 helpers.convert_mapping_to_xml(
4153 registry, registry_data, mappings, fail_required=True
4154 )
4155
4156
4157 def docker_pull_image(registry, xml_parent, data):
4158 """yaml: docker-pull-image
4159 Provides integration between Jenkins and Docker Hub, utilizing a
4160 Docker Hub hook to trigger one (or more) Jenkins job(s).
4161
4162 Requires the Jenkins :jenkins-plugins:`CloudBees Docker Hub Notification
4163 <dockerhub-notification>`.
4164
4165 :arg str image: Image ID on DockerHub (default '')
4166 :arg str docker-registry-url: URL to the Docker registry
4167 you are using (default '')
4168 :arg str credentials-id: Registry credentials (default '')
4169
4170 Minimal example:
4171
4172 .. literalinclude::
4173 /../../tests/builders/fixtures/docker-pull-image-minimal.yaml
4174
4175 Full example:
4176
4177 .. literalinclude::
4178 /../../tests/builders/fixtures/docker-pull-image-full.yaml
4179 """
4180 docker_pull_image = XML.SubElement(
4181 xml_parent,
4182 "org.jenkinsci.plugins.registry." "notification.DockerPullImageBuilder",
4183 )
4184 docker_pull_image.set("plugin", "dockerhub-notification")
4185 registry = XML.SubElement(docker_pull_image, "registry")
4186 registry.set("plugin", "docker-commons")
4187 mapping = [("image", "image", "")]
4188 helpers.convert_mapping_to_xml(
4189 docker_pull_image, data, mapping, fail_required=False
4190 )
4191 registry_mapping = [
4192 ("docker-registry-url", "url", ""),
4193 ("credentials-id", "credentialsId", ""),
4194 ]
4195 helpers.convert_mapping_to_xml(
4196 registry, data, registry_mapping, fail_required=False
4197 )
4198
4199
4200 def build_name_setter(registry, xml_parent, data):
4201 """yaml: build-name-setter
4202 Define Build Name Setter options which allows your build name to be
4203 updated during the build process.
4204
4205 Requires the Jenkins :jenkins-plugins:`Build Name Setter Plugin
4206 <build-name-setter>`.
4207
4208 :arg str name: Filename to use for Build Name Setter, only used if
4209 file bool is true. (default 'version.txt')
4210 :arg str template: Macro Template string, only used if macro
4211 bool is true. (default '#${BUILD_NUMBER}')
4212 :arg bool file: Read from named file (default false)
4213 :arg bool macro: Read from macro template (default false)
4214 :arg bool macro-first: Insert macro first (default false)
4215
4216 File Example:
4217
4218 .. literalinclude::
4219 /../../tests/builders/fixtures/build-name-setter001.yaml
4220 :language: yaml
4221
4222 Macro Example:
4223
4224 .. literalinclude::
4225 /../../tests/builders/fixtures/build-name-setter002.yaml
4226 :language: yaml
4227 """
4228 build_name_setter = XML.SubElement(
4229 xml_parent, "org.jenkinsci.plugins.buildnameupdater.BuildNameUpdater"
4230 )
4231 mapping = [
4232 ("name", "buildName", "version.txt"),
4233 ("template", "macroTemplate", "#${BUILD_NUMBER}"),
4234 ("file", "fromFile", False),
4235 ("macro", "fromMacro", False),
4236 ("macro-first", "macroFirst", False),
4237 ]
4238 helpers.convert_mapping_to_xml(build_name_setter, data, mapping, fail_required=True)
4239
4240
4241 def nexus_artifact_uploader(registry, xml_parent, data):
4242 """yaml: nexus-artifact-uploader
4243
4244 To upload result of a build as an artifact in Nexus without the need of
4245 Maven.
4246
4247 Requires the Jenkins :jenkins-plugins:`Nexus Artifact Uploader Plugin
4248 <nexus-artifact-uploader>`.
4249
4250 :arg str protocol: Protocol to use to connect to Nexus (default https)
4251 :arg str nexus_url: Nexus url (without protocol) (default '')
4252 :arg str nexus_user: Username to upload artifact to Nexus (default '')
4253 :arg str nexus_password: Password to upload artifact to Nexus
4254 (default '')
4255 :arg str group_id: GroupId to set for the artifact to upload
4256 (default '')
4257 :arg str artifact_id: ArtifactId to set for the artifact to upload
4258 (default '')
4259 :arg str version: Version to set for the artifact to upload
4260 (default '')
4261 :arg str packaging: Packaging to set for the artifact to upload
4262 (default '')
4263 :arg str type: Type to set for the artifact to upload (default '')
4264 :arg str classifier: Classifier to set for the artifact to upload
4265 (default '')
4266 :arg str repository: In which repository to upload the artifact
4267 (default '')
4268 :arg str file: File which will be the uploaded artifact (default '')
4269 :arg str credentials_id: Credentials to use (instead of password)
4270 (default '')
4271
4272 File Example:
4273
4274 .. literalinclude::
4275 /../../tests/builders/fixtures/nexus_artifact_uploader001.yaml
4276 :language: yaml
4277 """
4278 nexus_artifact_uploader = XML.SubElement(
4279 xml_parent, "sp.sd.nexusartifactuploader.NexusArtifactUploader"
4280 )
4281 mapping = [
4282 ("protocol", "protocol", "https"),
4283 ("nexus_url", "nexusUrl", ""),
4284 ("nexus_user", "nexusUser", ""),
4285 ("nexus_password", "nexusPassword", ""),
4286 ("group_id", "groupId", ""),
4287 ("artifact_id", "artifactId", ""),
4288 ("version", "version", ""),
4289 ("packaging", "packaging", ""),
4290 ("type", "type", ""),
4291 ("classifier", "classifier", ""),
4292 ("repository", "repository", ""),
4293 ("file", "file", ""),
4294 ("credentials_id", "credentialsId", ""),
4295 ]
4296 helpers.convert_mapping_to_xml(
4297 nexus_artifact_uploader, data, mapping, fail_required=True
4298 )
4299
4300
4301 def nexus_iq_policy_evaluator(registry, xml_parent, data):
4302 """yaml: nexus-iq-policy-evaluator
4303 Integrates the Nexus Lifecycle into a Jenkins job.
4304 This function triggers 'Invokes Nexus Policy Evaluation'.
4305
4306 Requires the Jenkins :jenkins-github:`Nexus Platform Plugin
4307 <nexus-platform-plugin>`.
4308
4309 :arg str stage: Controls the stage the policy evaluation will be
4310 run against on the Nexus IQ Server (required)
4311
4312 :stage values:
4313 * **build**
4314 * **stage-release**
4315 * **release**
4316 * **operate**
4317 :arg dict application-type: Specifies an IQ Application (default manual)
4318
4319 :application-type values:
4320 * **manual**
4321 * **selected**
4322 :arg str application-id: Specify the IQ Application ID (required)
4323 :arg list scan-patterns: List of Ant-style patterns relative to the
4324 workspace root that denote files/archives to be scanned (default [])
4325 :arg bool fail-build-network-error: Controls the build outcome if there
4326 is a failure in communicating with the Nexus IQ Server (default false)
4327
4328 Minimal Example:
4329
4330 .. literalinclude::
4331 /../../tests/builders/fixtures/nexus-iq-policy-evaluator-minimal.yaml
4332 :language: yaml
4333
4334 Full Example:
4335
4336 .. literalinclude::
4337 /../../tests/builders/fixtures/nexus-iq-policy-evaluator-full.yaml
4338 :language: yaml
4339 """
4340 nexus_iq_policy_evaluator = XML.SubElement(
4341 xml_parent, "org.sonatype.nexus.ci.iq.IqPolicyEvaluatorBuildStep"
4342 )
4343
4344 format_dict = {
4345 "stage": "com__sonatype__nexus__ci__iq__IqPolicyEvaluator____iqStage",
4346 "fone": "com__sonatype__nexus__ci__iq__IqPolicyEvaluator"
4347 "____failBuildOnNetworkError",
4348 }
4349
4350 valid_stages = ["build", "release", "stage-release", "operate"]
4351 mapping = [
4352 ("stage", format_dict.get("stage"), None, valid_stages),
4353 ("fail-build-network-error", format_dict.get("fone"), False),
4354 ]
4355 helpers.convert_mapping_to_xml(
4356 nexus_iq_policy_evaluator, data, mapping, fail_required=True
4357 )
4358
4359 application_type_label = data.get("application-type", "manual").lower()
4360 application_type_label_dict = {
4361 "manual": "org.sonatype.nexus.ci.iq.ManualApplication",
4362 "selected": "org.sonatype.nexus.ci.iq.SelectedApplication",
4363 }
4364 if application_type_label not in application_type_label_dict:
4365 raise InvalidAttributeError(
4366 application_type_label,
4367 application_type_label,
4368 application_type_label_dict.keys(),
4369 )
4370
4371 application_type_tag = XML.SubElement(
4372 nexus_iq_policy_evaluator,
4373 "com__sonatype__nexus__ci__iq__IqPolicyEvaluator____iqApplication",
4374 )
4375 application_type_tag.set(
4376 "class", application_type_label_dict[application_type_label]
4377 )
4378
4379 mapping = [("application-id", "applicationId", None)]
4380 helpers.convert_mapping_to_xml(
4381 application_type_tag, data, mapping, fail_required=True
4382 )
4383
4384 scan_pattern_list = data.get("scan-patterns", [])
4385 iq_scan_pattern_tag = XML.SubElement(
4386 nexus_iq_policy_evaluator,
4387 "com__sonatype__nexus__ci__iq" "__IqPolicyEvaluator____iqScanPatterns",
4388 )
4389
4390 for scan_pattern in scan_pattern_list:
4391 scan_pattern_tag = XML.SubElement(
4392 iq_scan_pattern_tag, "org.sonatype.nexus.ci.iq.ScanPattern"
4393 )
4394 XML.SubElement(scan_pattern_tag, "scanPattern").text = scan_pattern
4395
4396
4397 def nexus_repo_manager(registry, xml_parent, data):
4398 """yaml: nexus-repo-manager
4399 Allows for artifacts selected in Jenkins packages to be
4400 available in Nexus Repository Manager.
4401
4402 Requires the Jenkins :jenkins-github:`Nexus Platform Plugin
4403 <nexus-platform-plugin>`.
4404
4405 :arg str instance-id: The ID of the Nexus Instance (required)
4406 :arg str repo-id: The ID of the Nexus Repository (required)
4407
4408 Minimal Example:
4409
4410 .. literalinclude::
4411 /../../tests/builders/fixtures/nexus-repo-manager-minimal.yaml
4412 :language: yaml
4413 """
4414 nexus_repo_manager = XML.SubElement(
4415 xml_parent, "org.sonatype.nexus.ci." "nxrm.NexusPublisherBuildStep"
4416 )
4417 mapping = [
4418 ("instance-id", "nexusInstanceId", None),
4419 ("repo-id", "nexusRepositoryId", None),
4420 ]
4421 helpers.convert_mapping_to_xml(
4422 nexus_repo_manager, data, mapping, fail_required=True
4423 )
4424
4425
4426 def ansible_playbook(parser, xml_parent, data):
4427 """yaml: ansible-playbook
4428 This plugin allows you to execute Ansible tasks as a job build step.
4429
4430 Requires the Jenkins :jenkins-plugins:`Ansible Plugin <ansible>`.
4431
4432 :arg str playbook: Path to the ansible playbook file. The path can be
4433 absolute or relative to the job workspace. (required)
4434 :arg str inventory-type: The inventory file form (default `path`)
4435
4436 :inventory-type values:
4437 * **path**
4438 * **content**
4439 * **do-not-specify**
4440
4441 :arg dict inventory: Inventory data, depends on inventory-type
4442
4443 :inventory-type == path:
4444 * **path** (`str`) -- Path to inventory file.
4445
4446 :inventory-type == content:
4447 * **content** (`str`) -- Content of inventory file.
4448 * **dynamic** (`bool`) -- Dynamic inventory is used (default false)
4449
4450 :arg str hosts: Further limit selected hosts to an additional pattern
4451 (default '')
4452 :arg str tags-to-run: Only run plays and tasks tagged with these values
4453 (default '')
4454 :arg str tags-to-skip: Only run plays and tasks whose tags do not match
4455 these values (default '')
4456 :arg str task-to-start-at: Start the playbook at the task matching this
4457 name (default '')
4458 :arg int workers: Specify number of parallel processes to use (default 5)
4459 :arg str credentials-id: The ID of credentials for the SSH connections.
4460 Only private key authentication is supported (default '')
4461 :arg str vault-credentials-id: The ID of credentials for the vault
4462 decryption (default '')
4463 :arg bool sudo: Run operations with sudo. It works only when the remote
4464 user is sudoer with nopasswd option (default false)
4465 :arg str sudo-user: Desired sudo user. "root" is used when this field is
4466 empty. (default '')
4467 :arg bool unbuffered-output: Skip standard output buffering for the ansible
4468 process. The ansible output is directly rendered into the Jenkins
4469 console. This option can be useful for long running operations.
4470 (default true)
4471 :arg bool colorized-output: Check this box to allow ansible to render ANSI
4472 color codes in the Jenkins console. (default false)
4473 :arg bool disable-host-key-checking: Check this box to disable the
4474 validation of the hosts SSH server keys. (>= 1.0) (default false)
4475 :arg str additional-parameters: Any additional parameters to pass to the
4476 ansible command. (default '')
4477 :arg list variables: List of extra variables to be passed to ansible.
4478 (optional)
4479
4480 :variable item:
4481 * **name** (`str`) -- Name of variable (required)
4482 * **value** (`str`) -- Desired value (default '')
4483 * **hidden** (`bool`) -- Hide variable in build log (default false)
4484
4485 Outdated Options for versions >= 1.0 of plugin:
4486
4487 :arg bool host-key-checking: Outdated, replaced with disable-host-key-checking.
4488 Check this box to enforce the validation of the hosts SSH server keys.
4489 (< 1.0) (default true)
4490
4491 Example:
4492
4493 .. literalinclude::
4494 /../../tests/builders/fixtures/ansible-playbook001.yaml
4495 :language: yaml
4496
4497 OR
4498
4499 .. literalinclude::
4500 /../../tests/builders/fixtures/ansible-playbook002.yaml
4501 :language: yaml
4502
4503 Example(s) versions < 1.0:
4504
4505 .. literalinclude::
4506 /../../tests/builders/fixtures/ansible-playbook005.yaml
4507 :language: yaml
4508 """
4509 plugin = XML.SubElement(
4510 xml_parent, "org.jenkinsci.plugins.ansible.AnsiblePlaybookBuilder"
4511 )
4512 try:
4513 XML.SubElement(plugin, "playbook").text = str(data["playbook"])
4514 except KeyError as ex:
4515 raise MissingAttributeError(ex)
4516
4517 inventory_types = ("path", "content", "do-not-specify")
4518 inventory_type = str(data.get("inventory-type", inventory_types[0])).lower()
4519
4520 inventory = XML.SubElement(plugin, "inventory")
4521 inv_data = data.get("inventory", {})
4522 if inventory_type == "path":
4523 inventory.set("class", "org.jenkinsci.plugins.ansible.InventoryPath")
4524 try:
4525 path = inv_data["path"]
4526 except KeyError:
4527 raise MissingAttributeError("inventory['path']")
4528 XML.SubElement(inventory, "path").text = path
4529 elif inventory_type == "content":
4530 inventory.set("class", "org.jenkinsci.plugins.ansible.InventoryContent")
4531 try:
4532 content = inv_data["content"]
4533 except KeyError:
4534 raise MissingAttributeError("inventory['content']")
4535 XML.SubElement(inventory, "content").text = content
4536 XML.SubElement(inventory, "dynamic").text = str(
4537 inv_data.get("dynamic", False)
4538 ).lower()
4539 elif inventory_type == "do-not-specify":
4540 inventory.set("class", "org.jenkinsci.plugins.ansible.InventoryDoNotSpecify")
4541 else:
4542 raise InvalidAttributeError("inventory-type", inventory_type, inventory_types)
4543 XML.SubElement(plugin, "limit").text = data.get("hosts", "")
4544 XML.SubElement(plugin, "tags").text = data.get("tags-to-run", "")
4545 XML.SubElement(plugin, "skippedTags").text = data.get("tags-to-skip", "")
4546 XML.SubElement(plugin, "startAtTask").text = data.get("task-to-start-at", "")
4547 XML.SubElement(plugin, "credentialsId").text = data.get("credentials-id", "")
4548 XML.SubElement(plugin, "vaultCredentialsId").text = data.get(
4549 "vault-credentials-id", ""
4550 )
4551 if data.get("sudo", False):
4552 XML.SubElement(plugin, "sudo").text = "true"
4553 XML.SubElement(plugin, "sudoUser").text = data.get("sudo-user", "")
4554 else:
4555 XML.SubElement(plugin, "sudo").text = "false"
4556 if data.get("become", False):
4557 XML.SubElement(plugin, "become").text = "true"
4558 XML.SubElement(plugin, "becomeUser").text = data.get("become-user", "")
4559 else:
4560 XML.SubElement(plugin, "become").text = "false"
4561 XML.SubElement(plugin, "forks").text = str(data.get("workers", "5"))
4562 XML.SubElement(plugin, "unbufferedOutput").text = str(
4563 data.get("unbuffered-output", True)
4564 ).lower()
4565 XML.SubElement(plugin, "colorizedOutput").text = str(
4566 data.get("colorized-output", False)
4567 ).lower()
4568 XML.SubElement(plugin, "disableHostKeyChecking").text = str(
4569 data.get("disable-host-key-checking", False)
4570 ).lower()
4571 XML.SubElement(plugin, "hostKeyChecking").text = str(
4572 data.get("host-key-checking", True)
4573 ).lower()
4574 XML.SubElement(plugin, "additionalParameters").text = str(
4575 data.get("additional-parameters", "")
4576 )
4577 # Following option is not available from UI
4578 XML.SubElement(plugin, "copyCredentialsInWorkspace").text = "false"
4579 variables = data.get("variables", [])
4580 if variables:
4581 if not is_sequence(variables):
4582 raise InvalidAttributeError(
4583 "variables", variables, "list(dict(name, value, hidden))"
4584 )
4585 variables_elm = XML.SubElement(plugin, "extraVars")
4586 for idx, values in enumerate(variables):
4587 if not hasattr(values, "keys"):
4588 raise InvalidAttributeError(
4589 "variables[%s]" % idx, values, "dict(name, value, hidden)"
4590 )
4591 try:
4592 var_name = values["name"]
4593 except KeyError:
4594 raise MissingAttributeError("variables[%s]['name']" % idx)
4595 value_elm = XML.SubElement(
4596 variables_elm, "org.jenkinsci.plugins.ansible.ExtraVar"
4597 )
4598 XML.SubElement(value_elm, "key").text = var_name
4599 XML.SubElement(value_elm, "value").text = values.get("value", "")
4600 XML.SubElement(value_elm, "hidden").text = str(
4601 values.get("hidden", False)
4602 ).lower()
4603
4604
4605 def nodejs(parser, xml_parent, data):
4606 """yaml: nodejs
4607 This plugin allows you to execute NodeJS scripts as a job build step.
4608
4609 Requires the Jenkins :jenkins-plugins:`NodeJS Plugin <nodejs>`.
4610
4611 :arg str name: NodeJS installation name
4612 :arg str script: NodeJS script (required)
4613 :arg str config-id: ID of npmrc config file, which is the
4614 last field (a 32-digit hexadecimal code) of the path of URL visible
4615 after you clicked the file under Jenkins Managed Files.
4616
4617 Minimal Example:
4618
4619 .. literalinclude::
4620 ../../tests/builders/fixtures/nodejs-minimal.yaml
4621 :language: yaml
4622
4623 Full Example:
4624
4625 .. literalinclude::
4626 ../../tests/builders/fixtures/nodejs-full.yaml
4627 :language: yaml
4628 """
4629 nodejs = XML.SubElement(
4630 xml_parent, "jenkins.plugins.nodejs.NodeJSCommandInterpreter"
4631 )
4632 mapping = [("script", "command", None)]
4633
4634 mapping_opt = [
4635 ("name", "nodeJSInstallationName", None),
4636 ("config-id", "configId", None),
4637 ]
4638
4639 helpers.convert_mapping_to_xml(nodejs, data, mapping, fail_required=True)
4640 helpers.convert_mapping_to_xml(nodejs, data, mapping_opt, fail_required=False)
4641
4642
4643 def xunit(registry, xml_parent, data):
4644 """yaml: xunit
4645 Process tests results.
4646
4647 Requires the Jenkins :jenkins-plugins:`xUnit Plugin <xunit>`.
4648
4649 :arg str thresholdmode: Whether thresholds represents an absolute number
4650 of tests or a percentage. Either 'number' or 'percent'. (default
4651 'number')
4652 :arg list thresholds: Thresholds for both 'failed' and 'skipped' tests.
4653
4654 :threshold (`dict`): Threshold values to set, where missing, xUnit
4655 should default to an internal value of 0. Each test threshold
4656 should contain the following:
4657
4658 * **unstable** (`int`)
4659 * **unstablenew** (`int`)
4660 * **failure** (`int`)
4661 * **failurenew** (`int`)
4662
4663 :arg int test-time-margin: Give the report time margin value in ms, before
4664 to fail if not new unless the option **requireupdate** is set for the
4665 configured framework. (default 3000)
4666 :arg list types: Frameworks to configure, and options. Supports the
4667 following: ``aunit``, ``boosttest``, ``checktype``, ``cpptest``,
4668 ``cppunit``, ``ctest``, ``dotnettest``, ``embunit``, ``fpcunit``,
4669 ``gtest``, ``junit``, ``mstest``, ``nunit``, ``phpunit``, ``tusar``,
4670 ``unittest``, and ``valgrind``.
4671
4672 The 'custom' type is not supported.
4673
4674 :type (`dict`): each type can be configured using the following:
4675
4676 * **pattern** (`str`): An Ant pattern to look for Junit result
4677 files, relative to the workspace root (default '')
4678 * **requireupdate** (`bool`): fail the build whenever fresh tests
4679 results have not been found (default true).
4680 * **deleteoutput** (`bool`): delete temporary JUnit files
4681 (default true).
4682 * **skip-if-no-test-files** (`bool`): Skip parsing this xUnit type
4683 report if there are no test reports files (default false).
4684 * **stoponerror** (`bool`): Fail the build whenever an error occur
4685 during a result file processing (default true).
4686
4687 Minimal Example:
4688
4689 .. literalinclude::
4690 /../../tests/builders/fixtures/xunit-minimal.yaml
4691 :language: yaml
4692
4693 Full Example:
4694
4695 .. literalinclude::
4696 /../../tests/builders/fixtures/xunit-full.yaml
4697 :language: yaml
4698
4699 """
4700 plugin_ver = registry.get_plugin_version("xunit")
4701
4702 logger = logging.getLogger(__name__)
4703 xunit = XML.SubElement(xml_parent, "org.jenkinsci.plugins.xunit.XUnitBuilder")
4704 xunit.set("plugin", "xunit")
4705
4706 # Map our internal types to the XML element names used by Jenkins plugin
4707 types_to_plugin_types = {
4708 "aunit": "AUnitJunitHudsonTestType",
4709 "boosttest": "BoostTestJunitHudsonTestType",
4710 "checktype": "CheckType",
4711 "cpptest": "CppTestJunitHudsonTestType",
4712 "cppunit": "CppUnitJunitHudsonTestType",
4713 "ctest": "CTestType",
4714 "dotnettest": "XUnitDotNetTestType", # since plugin v1.93
4715 "embunit": "EmbUnitType", # since plugin v1.84
4716 "fpcunit": "FPCUnitJunitHudsonTestType",
4717 "gtest": "GoogleTestType",
4718 "junit": "JUnitType",
4719 "mstest": "MSTestJunitHudsonTestType",
4720 "nunit": "NUnitJunitHudsonTestType",
4721 "phpunit": "PHPUnitJunitHudsonTestType",
4722 "tusar": "TUSARJunitHudsonTestType",
4723 "unittest": "UnitTestJunitHudsonTestType",
4724 "valgrind": "ValgrindJunitHudsonTestType",
4725 # FIXME should implement the 'custom' type
4726 }
4727 implemented_types = types_to_plugin_types.keys() # shortcut
4728
4729 # Unit framework we are going to generate xml for
4730 supported_types = []
4731
4732 for configured_type in data["types"]:
4733 type_name = next(iter(configured_type.keys()))
4734 if type_name not in implemented_types:
4735 logger.warning("Requested xUnit type '%s' is not yet supported", type_name)
4736 else:
4737 # Append for generation
4738 supported_types.append(configured_type)
4739
4740 # Generate XML for each of the supported framework types
4741 # Note: versions 3+ are now using the 'tools' sub-element instead of 'types'
4742 if plugin_ver < "3.0.0":
4743 types_name = "types"
4744 else:
4745 types_name = "tools"
4746
4747 xmltypes = XML.SubElement(xunit, types_name)
4748 mappings = [
4749 ("pattern", "pattern", ""),
4750 ("requireupdate", "failIfNotNew", True),
4751 ("deleteoutput", "deleteOutputFiles", True),
4752 ("skip-if-no-test-files", "skipNoTestFiles", False),
4753 ("stoponerror", "stopProcessingIfError", True),
4754 ]
4755 for supported_type in supported_types:
4756 framework_name = next(iter(supported_type.keys()))
4757 xmlframework = XML.SubElement(xmltypes, types_to_plugin_types[framework_name])
4758
4759 helpers.convert_mapping_to_xml(
4760 xmlframework, supported_type[framework_name], mappings, fail_required=True
4761 )
4762
4763 xmlthresholds = XML.SubElement(xunit, "thresholds")
4764 for t in data.get("thresholds", []):
4765 if not ("failed" in t or "skipped" in t):
4766 logger.warning("Unrecognized threshold, should be 'failed' or 'skipped'")
4767 continue
4768 elname = (
4769 "org.jenkinsci.plugins.xunit.threshold.%sThreshold"
4770 % next(iter(t.keys())).title()
4771 )
4772 el = XML.SubElement(xmlthresholds, elname)
4773 for threshold_name, threshold_value in next(iter(t.values())).items():
4774 # Normalize and craft the element name for this threshold
4775 elname = "%sThreshold" % threshold_name.lower().replace("new", "New")
4776 XML.SubElement(el, elname).text = str(threshold_value)
4777
4778 # Whether to use percent of exact number of tests.
4779 # Thresholdmode is either:
4780 # - 1 : absolute (number of tests), default.
4781 # - 2 : relative (percentage of tests)
4782 thresholdmode = "1"
4783 if "percent" == data.get("thresholdmode", "number"):
4784 thresholdmode = "2"
4785 XML.SubElement(xunit, "thresholdMode").text = thresholdmode
4786
4787 extra_config = XML.SubElement(xunit, "extraConfiguration")
4788 XML.SubElement(extra_config, "testTimeMargin").text = str(
4789 data.get("test-time-margin", "3000")
4790 )