Debian Codegraph @

jenkins_jobs/modules/parameters.py

raw
1 # Copyright 2012 Hewlett-Packard Development Company, L.P.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14
15
16 """
17 The Parameters module allows you to specify build parameters for a job.
18
19 **Component**: parameters
20 :Macro: parameter
21 :Entry Point: jenkins_jobs.parameters
22
23 Example::
24
25 job:
26 name: test_job
27
28 parameters:
29 - string:
30 name: FOO
31 default: bar
32 description: "A parameter named FOO, defaults to 'bar'."
33 """
34
35 import xml.etree.ElementTree as XML
36
37 from jenkins_jobs.loc_loader import LocList
38 from jenkins_jobs.errors import JenkinsJobsException
39 from jenkins_jobs.errors import MissingAttributeError
40 from jenkins_jobs.errors import InvalidAttributeError
41 import jenkins_jobs.modules.base
42 import jenkins_jobs.modules.helpers as helpers
43
44
45 def base_param(registry, xml_parent, data, do_default, ptype):
46 pdef = XML.SubElement(xml_parent, ptype)
47 XML.SubElement(pdef, "name").text = data["name"]
48 XML.SubElement(pdef, "description").text = data.get("description", "")
49 if do_default:
50 default = data.get("default", None)
51 if default is not None:
52 XML.SubElement(pdef, "defaultValue").text = str(default)
53 else:
54 XML.SubElement(pdef, "defaultValue")
55 return pdef
56
57
58 def string_param(registry, xml_parent, data):
59 """yaml: string
60 A string parameter.
61
62 :arg str name: the name of the parameter
63 :arg str default: the default value of the parameter (optional)
64 :arg str description: a description of the parameter (optional)
65 :arg bool trim: strip whitespaces from the begnning and end
66 of the string (optional, default: false)
67
68 Example::
69
70 parameters:
71 - string:
72 name: FOO
73 default: bar
74 description: "A parameter named FOO, defaults to 'bar'."
75 trim: true
76 """
77 pdef = base_param(
78 registry, xml_parent, data, True, "hudson.model.StringParameterDefinition"
79 )
80
81 mapping = [("trim", "trim", False)]
82 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
83
84
85 def promoted_param(registry, xml_parent, data):
86 """yaml: promoted build
87 A promoted build parameter.
88
89 Requires the Jenkins :jenkins-plugins:`Promoted Builds Plugin
90 <promoted-builds>`.
91
92 :arg str name: the name of the parameter (required)
93 :arg str project-name: the job from which the user can pick runs (required)
94 :arg str promotion-name: promotion process to choose from (optional)
95 :arg str description: a description of the parameter (optional)
96
97 Example:
98
99 .. literalinclude::
100 /../../tests/parameters/fixtures/promoted-build-param001.yaml
101 :language: yaml
102
103 """
104 pdef = base_param(
105 registry,
106 xml_parent,
107 data,
108 False,
109 "hudson.plugins.promoted__builds.parameters."
110 "PromotedBuildParameterDefinition",
111 )
112 try:
113 XML.SubElement(pdef, "projectName").text = data["project-name"]
114 except KeyError:
115 raise MissingAttributeError("project-name")
116
117 XML.SubElement(pdef, "promotionProcessName").text = data.get("promotion-name", None)
118
119
120 def password_param(registry, xml_parent, data):
121 """yaml: password
122 A password parameter.
123
124 :arg str name: the name of the parameter
125 :arg str default: the default value of the parameter (optional)
126 :arg str description: a description of the parameter (optional)
127
128 Example::
129
130 parameters:
131 - password:
132 name: FOO
133 default: 1HSC0Ts6E161FysGf+e1xasgsHkgleLh09JUTYnipPvw=
134 description: "A parameter named FOO."
135 """
136 base_param(
137 registry, xml_parent, data, True, "hudson.model.PasswordParameterDefinition"
138 )
139
140
141 def bool_param(registry, xml_parent, data):
142 """yaml: bool
143 A boolean parameter.
144
145 :arg str name: the name of the parameter
146 :arg str default: the default value of the parameter (optional)
147 :arg str description: a description of the parameter (optional)
148
149 Example::
150
151 parameters:
152 - bool:
153 name: FOO
154 default: false
155 description: "A parameter named FOO, defaults to 'false'."
156 """
157 data["default"] = str(data.get("default", False)).lower()
158 base_param(
159 registry, xml_parent, data, True, "hudson.model.BooleanParameterDefinition"
160 )
161
162
163 def file_param(registry, xml_parent, data):
164 """yaml: file
165 A file parameter.
166
167 :arg str name: the target location for the file upload
168 :arg str description: a description of the parameter (optional)
169
170 Example::
171
172 parameters:
173 - file:
174 name: test.txt
175 description: "Upload test.txt."
176 """
177 base_param(
178 registry, xml_parent, data, False, "hudson.model.FileParameterDefinition"
179 )
180
181
182 def text_param(registry, xml_parent, data):
183 """yaml: text
184 A text parameter.
185
186 :arg str name: the name of the parameter
187 :arg str default: the default value of the parameter (optional)
188 :arg str description: a description of the parameter (optional)
189
190 Example::
191
192 parameters:
193 - text:
194 name: FOO
195 default: bar
196 description: "A parameter named FOO, defaults to 'bar'."
197 """
198 base_param(registry, xml_parent, data, True, "hudson.model.TextParameterDefinition")
199
200
201 def label_param(registry, xml_parent, data):
202 """yaml: label
203 A node label parameter.
204
205 :arg str name: the name of the parameter
206 :arg str default: the default value of the parameter (optional)
207 :arg str description: a description of the parameter (optional)
208 :arg bool all-nodes: to run job on all nodes matching label
209 in parallel (default: false)
210 :arg str matching-label: to run all nodes matching label
211 'success', 'unstable' or 'allCases' (optional)
212 :arg str node-eligibility: all nodes, ignore temporary nodes or
213 ignore temporary offline nodes (optional, default all nodes)
214
215 Example:
216
217 .. literalinclude:: /../../tests/parameters/fixtures/node-label001.yaml
218 :language: yaml
219
220 """
221
222 pdef = base_param(
223 registry,
224 xml_parent,
225 data,
226 True,
227 "org.jvnet.jenkins.plugins.nodelabelparameter." "LabelParameterDefinition",
228 )
229
230 valid_types = ["allCases", "success", "unstable"]
231 mapping = [
232 ("all-nodes", "allNodesMatchingLabel", False),
233 ("matching-label", "triggerIfResult", "allCases", valid_types),
234 ]
235 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
236
237 eligibility_label = data.get("node-eligibility", "all").lower()
238 eligibility_label_dict = {
239 "all": "org.jvnet.jenkins.plugins."
240 "nodelabelparameter.node."
241 "AllNodeEligibility",
242 "ignore-offline": "org.jvnet.jenkins.plugins."
243 "nodelabelparameter.node."
244 "IgnoreOfflineNodeEligibility",
245 "ignore-temp-offline": "org.jvnet.jenkins.plugins."
246 "nodelabelparameter.node."
247 "IgnoreTempOfflineNodeEligibility",
248 }
249 if eligibility_label not in eligibility_label_dict:
250 raise InvalidAttributeError(
251 eligibility_label, eligibility_label, eligibility_label_dict.keys()
252 )
253
254 XML.SubElement(pdef, "nodeEligibility").set(
255 "class", eligibility_label_dict[eligibility_label]
256 )
257
258
259 def node_param(registry, xml_parent, data):
260 """yaml: node
261 Defines a list of nodes where this job could potentially be executed on.
262 Restrict where this project can be run, If your using a node or label
263 parameter to run your job on a particular node, you should not use the
264 option "Restrict where this project can be run" in the job configuration
265 - it will not have any effect to the selection of your node anymore!
266
267 :arg str name: the name of the parameter
268 :arg str description: a description of the parameter (optional)
269 :arg list default-slaves: The nodes used when job gets triggered
270 by anything else other than manually
271 :arg list allowed-slaves: The nodes available for selection
272 when job gets triggered manually. Empty means 'All'.
273 :arg bool ignore-offline-nodes: Ignore nodes not online or not having
274 executors (default false)
275 :arg bool allowed-multiselect: Allow multi node selection for concurrent
276 builds - this option only makes sense (and must be selected!) in
277 case the job is configured with: "Execute concurrent builds if
278 necessary". With this configuration the build will be executed on all
279 the selected nodes in parallel. (default false)
280
281 Example:
282
283 .. literalinclude:: /../../tests/parameters/fixtures/node-param001.yaml
284 :language: yaml
285
286 """
287 pdef = base_param(
288 registry,
289 xml_parent,
290 data,
291 False,
292 "org.jvnet.jenkins.plugins.nodelabelparameter." "NodeParameterDefinition",
293 )
294 default = XML.SubElement(pdef, "defaultSlaves")
295 if "default-slaves" in data:
296 for slave in data["default-slaves"]:
297 XML.SubElement(default, "string").text = slave
298 allowed = XML.SubElement(pdef, "allowedSlaves")
299 if "allowed-slaves" in data:
300 for slave in data["allowed-slaves"]:
301 XML.SubElement(allowed, "string").text = slave
302 XML.SubElement(pdef, "ignoreOfflineNodes").text = str(
303 data.get("ignore-offline-nodes", False)
304 ).lower()
305
306 if data.get("allowed-multiselect", False):
307 XML.SubElement(
308 pdef, "triggerIfResult"
309 ).text = "allowMultiSelectionForConcurrentBuilds"
310 else:
311 XML.SubElement(pdef, "triggerIfResult").text = "multiSelectionDisallowed"
312 XML.SubElement(pdef, "allowMultiNodeSelection").text = str(
313 data.get("allowed-multiselect", False)
314 ).lower()
315 XML.SubElement(pdef, "triggerConcurrentBuilds").text = str(
316 data.get("allowed-multiselect", False)
317 ).lower()
318
319
320 def choice_param(registry, xml_parent, data):
321 """yaml: choice
322 A single selection parameter.
323
324 :arg str name: the name of the parameter
325 :arg list choices: the available choices, first one is the default one.
326 :arg str description: a description of the parameter (optional)
327
328 Example::
329
330 parameters:
331 - choice:
332 name: project
333 choices:
334 - nova
335 - glance
336 description: "On which project to run?"
337 """
338 pdef = base_param(
339 registry, xml_parent, data, False, "hudson.model.ChoiceParameterDefinition"
340 )
341 choices = XML.SubElement(pdef, "choices", {"class": "java.util.Arrays$ArrayList"})
342 a = XML.SubElement(choices, "a", {"class": "string-array"})
343 for choice in data["choices"]:
344 XML.SubElement(a, "string").text = choice
345
346
347 def credentials_param(registry, xml_parent, data):
348 """yaml: credentials
349 A credentials selection parameter.
350
351 Requires the Jenkins :jenkins-plugins:`Credentials Plugin <credentials>`.
352
353 :arg str name: the name of the parameter
354 :arg str type: credential type (optional, default 'any')
355
356 :Allowed Values: * **any** Any credential type (default)
357 * **usernamepassword** Username with password
358 * **sshkey** SSH Username with private key
359 * **secretfile** Secret file
360 * **secrettext** Secret text
361 * **certificate** Certificate
362
363 :arg bool required: whether this parameter is required (optional, default
364 false)
365 :arg str default: default credentials ID (optional)
366 :arg str description: a description of the parameter (optional)
367
368 Example:
369
370 .. literalinclude:: \
371 /../../tests/parameters/fixtures/credentials-param001.yaml
372 :language: yaml
373
374 """
375 cred_impl_types = {
376 "any": "com.cloudbees.plugins.credentials.common.StandardCredentials",
377 "usernamepassword": "com.cloudbees.plugins.credentials.impl."
378 + "UsernamePasswordCredentialsImpl",
379 "sshkey": "com.cloudbees.jenkins.plugins.sshcredentials.impl."
380 + "BasicSSHUserPrivateKey",
381 "secretfile": "org.jenkinsci.plugins.plaincredentials.impl."
382 + "FileCredentialsImpl",
383 "secrettext": "org.jenkinsci.plugins.plaincredentials.impl."
384 + "StringCredentialsImpl",
385 "certificate": "com.cloudbees.plugins.credentials.impl."
386 + "CertificateCredentialsImpl",
387 }
388
389 cred_type = data.get("type", "any").lower()
390 if cred_type not in cred_impl_types:
391 raise InvalidAttributeError("type", cred_type, cred_impl_types.keys())
392
393 pdef = base_param(
394 registry,
395 xml_parent,
396 data,
397 False,
398 "com.cloudbees.plugins.credentials." + "CredentialsParameterDefinition",
399 )
400 XML.SubElement(pdef, "defaultValue").text = data.get("default", "")
401 XML.SubElement(pdef, "credentialType").text = cred_impl_types[cred_type]
402 XML.SubElement(pdef, "required").text = str(data.get("required", False)).lower()
403
404
405 def run_param(registry, xml_parent, data):
406 """yaml: run
407 A run parameter.
408
409 :arg str name: the name of the parameter
410 :arg str project-name: the name of job from which the user can pick runs
411 :arg str description: a description of the parameter (optional)
412
413 Example:
414
415 .. literalinclude:: /../../tests/parameters/fixtures/run-param001.yaml
416 :language: yaml
417
418 """
419 pdef = base_param(
420 registry, xml_parent, data, False, "hudson.model.RunParameterDefinition"
421 )
422 mapping = [("project-name", "projectName", None)]
423 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
424
425
426 @helpers.check_mutual_exclusive_data_args(
427 2, "value", "property-file", "groovy-script", "groovy-script-file"
428 )
429 @helpers.check_mutual_exclusive_data_args(
430 2, "default-value", "default-property-file", "default-groovy-script"
431 )
432 @helpers.check_mutual_exclusive_data_args(
433 2,
434 "value-description",
435 "description-property-file",
436 "description-groovy-script",
437 "description-groovy-script-file",
438 )
439 @helpers.check_mutual_exclusive_data_args(2, "javascript", "javascript-file")
440 def extended_choice_param(registry, xml_parent, data):
441 """yaml: extended-choice
442 Creates an extended choice parameter where values can be read from a file
443
444 Requires the Jenkins :jenkins-plugins:`Extended Choice Parameter Plugin
445 <extended-choice-parameter>`.
446
447 :arg str name: name of the parameter
448 :arg str description: description of the parameter
449 (optional, default '')
450 :arg str property-file: location of property file to read from
451 (optional, default '')
452 :arg str property-key: key for the property-file (optional, default '')
453 :arg bool quote-value: whether to put quotes around the property
454 when passing to Jenkins (optional, default false)
455 :arg str visible-items: number of items to show in the list
456 (optional, default 5)
457 :arg str type: type of select, can be single-select, multi-select,
458 multi-level-single-select, multi-level-multi-select,
459 radio, checkbox, textbox, json (optional, default single-select)
460 :arg str value: comma separated list of values for the single select
461 or multi-select box (optional, default '')
462 :arg str default-value: used to set the initial selection of the
463 single-select or multi-select box (optional, default '')
464 :arg str value-description: comma separated list of value descriptions
465 for the single select or multi-select box (optional, default '')
466 :arg str default-property-file: location of property file when default
467 value needs to come from a property file (optional, default '')
468 :arg str default-property-key: key for the default property file
469 (optional, default '')
470 :arg str description-property-file: location of property file when value
471 description needs to come from a property file (optional, default '')
472 :arg str description-property-key: key for the value description
473 property file (optional, default '')
474 :arg str multi-select-delimiter: value between selections when the
475 parameter is a multi-select (optional, default ',')
476 :arg str groovy-script: the groovy script contents (optional, default ',')
477 :arg str groovy-script-file: location of groovy script file to generate
478 parameters (optional, default '')
479 :arg str bindings: variable bindings for the groovy script
480 (optional, default '')
481 :arg str classpath: the classpath for the groovy script
482 (optional, default ',')
483 :arg str default-groovy-script: the default groovy
484 script contents (optional, default '')
485 :arg str default-groovy-classpath: the default classpath for the
486 groovy script (optional, default '')
487 :arg str description-groovy-script: location of groovy script when value
488 description needs to come from a groovy script (optional, default '')
489 :arg str description-groovy-script-file: location of groovy script file when value
490 description needs to come from a groovy script (optional, default '')
491 :arg str description-groovy-classpath: classpath for the value description
492 groovy script (optional, default '')
493 :arg str javascript: the javascript script contents (optional, default '')
494 :arg str javascript-file: location of javasript script file to generate
495 parameters (optional, default '')
496 :arg bool save-json-parameter-to-file: if json parameter should be saved
497 to file (optional, default False)
498
499 Minimal Example:
500
501 .. literalinclude:: \
502 /../../tests/parameters/fixtures/extended-choice-param-minimal.yaml
503 :language: yaml
504
505 Full Example:
506
507 .. literalinclude:: \
508 /../../tests/parameters/fixtures/extended-choice-param-full.yaml
509 :language: yaml
510 """
511 pdef = base_param(
512 registry,
513 xml_parent,
514 data,
515 False,
516 "com.cwctravel.hudson.plugins."
517 "extended__choice__parameter."
518 "ExtendedChoiceParameterDefinition",
519 )
520
521 choicedict = {
522 "single-select": "PT_SINGLE_SELECT",
523 "multi-select": "PT_MULTI_SELECT",
524 "multi-level-single-select": "PT_MULTI_LEVEL_SINGLE_SELECT",
525 "multi-level-multi-select": "PT_MULTI_LEVEL_MULTI_SELECT",
526 "radio": "PT_RADIO",
527 "checkbox": "PT_CHECKBOX",
528 "textbox": "PT_TEXTBOX",
529 "json": "PT_JSON",
530 "PT_SINGLE_SELECT": "PT_SINGLE_SELECT",
531 "PT_MULTI_SELECT": "PT_MULTI_SELECT",
532 "PT_MULTI_LEVEL_SINGLE_SELECT": "PT_MULTI_LEVEL_SINGLE_SELECT",
533 "PT_MULTI_LEVEL_MULTI_SELECT": "PT_MULTI_LEVEL_MULTI_SELECT",
534 "PT_RADIO": "PT_RADIO",
535 "PT_CHECKBOX": "PT_CHECKBOX",
536 "PT_TEXTBOX": "PT_TEXTBOX",
537 "PT_JSON": "PT_JSON",
538 }
539 mapping = [
540 ("value", "value", ""),
541 ("visible-items", "visibleItemCount", 5),
542 ("multi-select-delimiter", "multiSelectDelimiter", ","),
543 ("quote-value", "quoteValue", False),
544 ("default-value", "defaultValue", ""),
545 ("value-description", "descriptionPropertyValue", ""),
546 ("type", "type", "single-select", choicedict),
547 ("property-file", "propertyFile", ""),
548 ("property-key", "propertyKey", ""),
549 ("default-property-file", "defaultPropertyFile", ""),
550 ("default-property-key", "defaultPropertyKey", ""),
551 ("description-property-file", "descriptionPropertyFile", ""),
552 ("description-property-key", "descriptionPropertyKey", ""),
553 ("bindings", "bindings", ""),
554 ("groovy-script", "groovyScript", ""),
555 ("groovy-script-file", "groovyScriptFile", ""),
556 ("classpath", "groovyClasspath", ""),
557 ("default-groovy-script", "defaultGroovyScript", ""),
558 ("default-groovy-classpath", "defaultGroovyClasspath", ""),
559 ("description-groovy-script", "descriptionGroovyScript", ""),
560 ("description-groovy-script-file", "descriptionGroovyScriptFile", ""),
561 ("description-groovy-classpath", "descriptionGroovyClasspath", ""),
562 ("javascript", "javascript", ""),
563 ("javascript-file", "javascriptFile", ""),
564 ("save-json-parameter-to-file", "saveJSONParameterToFile", False),
565 ]
566 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
567
568
569 def validating_string_param(registry, xml_parent, data):
570 """yaml: validating-string
571 A validating string parameter
572
573 Requires the Jenkins :jenkins-plugins:`Validating String Plugin
574 <validating-string-parameter>`.
575
576 :arg str name: the name of the parameter
577 :arg str default: the default value of the parameter (optional)
578 :arg str description: a description of the parameter (optional)
579 :arg str regex: a regular expression to validate the string
580 :arg str msg: a message to display upon failed validation
581
582 Example::
583
584 parameters:
585 - validating-string:
586 name: FOO
587 default: bar
588 description: "A parameter named FOO, defaults to 'bar'."
589 regex: [A-Za-z]*
590 msg: Your entered value failed validation
591 """
592 pdef = base_param(
593 registry,
594 xml_parent,
595 data,
596 True,
597 "hudson.plugins.validating__string__parameter."
598 "ValidatingStringParameterDefinition",
599 )
600 mapping = [("regex", "regex", None), ("msg", "failedValidationMessage", None)]
601 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
602
603
604 def svn_tags_param(registry, xml_parent, data):
605 """yaml: svn-tags
606 A svn tag parameter
607
608 Requires the Jenkins :jenkins-plugins:`Parameterized Trigger Plugin
609 <parameterized-trigger>`.
610
611 :arg str name: the name of the parameter
612 :arg str url: the url to list tags from
613 :arg str credentials-id: Credentials ID to use for authentication
614 (default '')
615 :arg str filter: the regular expression to filter tags (default '')
616 :arg str default: the default value of the parameter (default '')
617 :arg str description: a description of the parameter (default '')
618 :arg int max-tags: the number of tags to display (default '100')
619 :arg bool sort-newest-first: sort tags from newest to oldest (default true)
620 :arg bool sort-z-to-a: sort tags in reverse alphabetical order
621 (default false)
622
623 Example::
624
625 parameters:
626 - svn-tags:
627 name: BRANCH_NAME
628 default: release
629 description: A parameter named BRANCH_NAME default is release
630 url: http://svn.example.org/repo
631 filter: [A-za-z0-9]*
632 """
633 pdef = base_param(
634 registry,
635 xml_parent,
636 data,
637 True,
638 "hudson.scm.listtagsparameter." "ListSubversionTagsParameterDefinition",
639 )
640 mapping = [
641 ("url", "tagsDir", None),
642 ("credentials-id", "credentialsId", ""),
643 ("filter", "tagsFilter", ""),
644 ("max-tags", "maxTags", "100"),
645 ("sort-newest-first", "reverseByDate", True),
646 ("sort-z-to-a", "reverseByName", False),
647 ("", "uuid", "1-1-1-1-1"),
648 ]
649 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
650
651
652 def dynamic_choice_param(registry, xml_parent, data):
653 """yaml: dynamic-choice
654 Dynamic Choice Parameter
655
656 Requires the Jenkins :jenkins-plugins:`Jenkins Dynamic Parameter Plug-in
657 <dynamicparameter>`.
658
659 :arg str name: the name of the parameter
660 :arg str description: a description of the parameter (optional)
661 :arg str script: Groovy expression which generates the potential choices.
662 :arg bool remote: the script will be executed on the slave where the build
663 is started (default false)
664 :arg str classpath: class path for script (optional)
665 :arg bool read-only: user can't modify parameter once populated
666 (default false)
667
668 Example::
669
670 parameters:
671 - dynamic-choice:
672 name: OPTIONS
673 description: "Available options"
674 script: "['optionA', 'optionB']"
675 remote: false
676 read-only: false
677 """
678 dynamic_param_common(registry, xml_parent, data, "ChoiceParameterDefinition")
679
680
681 def dynamic_string_param(registry, xml_parent, data):
682 """yaml: dynamic-string
683 Dynamic Parameter
684
685 Requires the Jenkins :jenkins-plugins:`Jenkins Dynamic Parameter Plug-in
686 <dynamicparameter>`.
687
688 :arg str name: the name of the parameter
689 :arg str description: a description of the parameter (optional)
690 :arg str script: Groovy expression which generates the potential choices
691 :arg bool remote: the script will be executed on the slave where the build
692 is started (default false)
693 :arg str classpath: class path for script (optional)
694 :arg bool read-only: user can't modify parameter once populated
695 (default false)
696
697 Example::
698
699 parameters:
700 - dynamic-string:
701 name: FOO
702 description: "A parameter named FOO, defaults to 'bar'."
703 script: "bar"
704 remote: false
705 read-only: false
706 """
707 dynamic_param_common(registry, xml_parent, data, "StringParameterDefinition")
708
709
710 def dynamic_choice_scriptler_param(registry, xml_parent, data):
711 """yaml: dynamic-choice-scriptler
712 Dynamic Choice Parameter (Scriptler)
713
714 Requires the Jenkins :jenkins-plugins:`Jenkins Dynamic Parameter Plug-in
715 <dynamicparameter>`.
716
717 :arg str name: the name of the parameter
718 :arg str description: a description of the parameter (optional)
719 :arg str script-id: Groovy script which generates the default value
720 :arg list parameters: parameters to corresponding script
721
722 :Parameter: * **name** (`str`) Parameter name
723 * **value** (`str`) Parameter value
724 :arg bool remote: the script will be executed on the slave where the build
725 is started (default false)
726 :arg bool read-only: user can't modify parameter once populated
727 (default false)
728
729 Example::
730
731 parameters:
732 - dynamic-choice-scriptler:
733 name: OPTIONS
734 description: "Available options"
735 script-id: "scriptid.groovy"
736 parameters:
737 - name: param1
738 value: value1
739 - name: param2
740 value: value2
741 remote: false
742 read-only: false
743 """
744 dynamic_scriptler_param_common(
745 registry, xml_parent, data, "ScriptlerChoiceParameterDefinition"
746 )
747
748
749 def dynamic_string_scriptler_param(registry, xml_parent, data):
750 """yaml: dynamic-string-scriptler
751 Dynamic Parameter (Scriptler)
752
753 Requires the Jenkins :jenkins-plugins:`Jenkins Dynamic Parameter Plug-in
754 <dynamicparameter>`.
755
756 :arg str name: the name of the parameter
757 :arg str description: a description of the parameter (optional)
758 :arg str script-id: Groovy script which generates the default value
759 :arg list parameters: parameters to corresponding script
760
761 :Parameter: * **name** (`str`) Parameter name
762 * **value** (`str`) Parameter value
763 :arg bool remote: the script will be executed on the slave where the build
764 is started (default false)
765 :arg bool read-only: user can't modify parameter once populated
766 (default false)
767
768 Example::
769
770 parameters:
771 - dynamic-string-scriptler:
772 name: FOO
773 description: "A parameter named FOO, defaults to 'bar'."
774 script-id: "scriptid.groovy"
775 parameters:
776 - name: param1
777 value: value1
778 - name: param2
779 value: value2
780 remote: false
781 read-only: false
782 """
783 dynamic_scriptler_param_common(
784 registry, xml_parent, data, "ScriptlerStringParameterDefinition"
785 )
786
787
788 def dynamic_param_common(registry, xml_parent, data, ptype):
789 pdef = base_param(
790 registry,
791 xml_parent,
792 data,
793 False,
794 "com.seitenbau.jenkins.plugins.dynamicparameter." + ptype,
795 )
796 XML.SubElement(pdef, "__remote").text = str(data.get("remote", False)).lower()
797 XML.SubElement(pdef, "__script").text = data.get("script", None)
798 localBaseDir = XML.SubElement(
799 pdef, "__localBaseDirectory", {"serialization": "custom"}
800 )
801 filePath = XML.SubElement(localBaseDir, "hudson.FilePath")
802 default = XML.SubElement(filePath, "default")
803 XML.SubElement(filePath, "boolean").text = "true"
804 XML.SubElement(
805 default, "remote"
806 ).text = "/var/lib/jenkins/dynamic_parameter/classpath"
807 XML.SubElement(pdef, "__remoteBaseDirectory").text = "dynamic_parameter_classpath"
808 XML.SubElement(pdef, "__classPath").text = data.get("classpath", None)
809 XML.SubElement(pdef, "readonlyInputField").text = str(
810 data.get("read-only", False)
811 ).lower()
812
813
814 def dynamic_scriptler_param_common(registry, xml_parent, data, ptype):
815 pdef = base_param(
816 registry,
817 xml_parent,
818 data,
819 False,
820 "com.seitenbau.jenkins.plugins.dynamicparameter." "scriptler." + ptype,
821 )
822 parametersXML = XML.SubElement(pdef, "__parameters")
823 parameters = data.get("parameters", [])
824 if parameters:
825 mapping = [("name", "name", None), ("value", "value", None)]
826 for parameter in parameters:
827 parameterXML = XML.SubElement(
828 parametersXML,
829 "com.seitenbau.jenkins.plugins."
830 "dynamicparameter.scriptler."
831 "ScriptlerParameterDefinition_"
832 "-ScriptParameter",
833 )
834 helpers.convert_mapping_to_xml(
835 parameterXML, parameter, mapping, fail_required=True
836 )
837 mapping = [
838 ("script-id", "__scriptlerScriptId", None),
839 ("remote", "__remote", False),
840 ("read-only", "readonlyInputField", False),
841 ]
842 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
843
844
845 def matrix_combinations_param(registry, xml_parent, data):
846 """yaml: matrix-combinations
847 Matrix combinations parameter
848
849 Requires the Jenkins :jenkins-plugins:`Matrix Combinations Plugin
850 <matrix-combinations-parameter>`.
851
852 :arg str name: the name of the parameter
853 :arg str description: a description of the parameter (optional)
854 :arg str filter: Groovy expression to use filter the combination by
855 default (optional)
856
857 Example:
858
859 .. literalinclude:: \
860 /../../tests/parameters/fixtures/matrix-combinations-param001.yaml
861 :language: yaml
862
863 """
864 element_name = (
865 "hudson.plugins.matrix__configuration__parameter."
866 "MatrixCombinationsParameterDefinition"
867 )
868 pdef = XML.SubElement(xml_parent, element_name)
869
870 mapping = [
871 ("name", "name", None),
872 ("description", "description", ""),
873 ("filter", "defaultCombinationFilter", ""),
874 ]
875 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
876
877 return pdef
878
879
880 def copyartifact_build_selector_param(registry, xml_parent, data):
881 """yaml: copyartifact-build-selector
882
883 Control via a build parameter, which build the copyartifact plugin should
884 copy when it is configured to use 'build-param'.
885
886 Requires the Jenkins :jenkins-plugins:`Copy Artifact plugin <copyartifact>`.
887
888 :arg str name: name of the build parameter to store the selection in
889 :arg str description: a description of the parameter (optional)
890 :arg str which-build: which to provide as the default value in the UI. See
891 ``which-build`` param of :py:mod:`~builders.copyartifact` from the
892 builders module for the available values as well as options available
893 that control additional behaviour for the selected value.
894
895 Example:
896
897 .. literalinclude::
898 /../../tests/parameters/fixtures/copyartifact-build-selector001.yaml
899 :language: yaml
900
901 """
902
903 t = XML.SubElement(
904 xml_parent, "hudson.plugins.copyartifact." "BuildSelectorParameter"
905 )
906 mapping = [("name", "name", None), ("description", "description", "")]
907 helpers.convert_mapping_to_xml(t, data, mapping, fail_required=True)
908
909 helpers.copyartifact_build_selector(t, data, "defaultSelector")
910
911
912 def maven_metadata_param(registry, xml_parent, data):
913 """yaml: maven-metadata
914 This parameter allows the resolution of maven artifact versions
915 by contacting the repository and reading the maven-metadata.xml.
916
917 Requires the Jenkins :jenkins-plugins:`Maven Metadata Plugin
918 <maven-metadata-plugin>`.
919
920 :arg str name: Name of the parameter
921 :arg str description: Description of the parameter (optional)
922 :arg str repository-base-url: URL from where you retrieve your artifacts
923 (default '')
924 :arg str repository-username: Repository's username if authentication is
925 required. (default '')
926 :arg str repository-password: Repository's password if authentication is
927 required. (default '')
928 :arg str artifact-group-id: Unique project identifier (default '')
929 :arg str artifact-id: Name of the artifact without version (default '')
930 :arg str packaging: Artifact packaging option. Could be something such as
931 jar, zip, pom.... (default '')
932 :arg str versions-filter: Specify a regular expression which will be used
933 to filter the versions which are actually displayed when triggering a
934 new build. (default '')
935 :arg str default-value: For features such as SVN polling a default value
936 is required. If job will only be started manually, this field is not
937 necessary. (default '')
938 :arg str maximum-versions-to-display: The maximum number of versions to
939 display in the drop-down. Any non-number value as well as 0 or negative
940 values will default to all. (default 10)
941 :arg str sorting-order: ascending or descending
942 (default descending)
943
944 Example:
945
946 .. literalinclude::
947 /../../tests/parameters/fixtures/maven-metadata-param001.yaml
948 :language: yaml
949
950 """
951 pdef = base_param(
952 registry,
953 xml_parent,
954 data,
955 False,
956 "eu.markov.jenkins.plugin.mvnmeta." "MavenMetadataParameterDefinition",
957 )
958 mapping = [
959 ("repository-base-url", "repoBaseUrl", ""),
960 ("artifact-group-id", "groupId", ""),
961 ("artifact-id", "artifactId", ""),
962 ("packaging", "packaging", ""),
963 ("default-value", "defaultValue", ""),
964 ("versions-filter", "versionFilter", ""),
965 ]
966 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
967
968 sort_order = data.get("sorting-order", "descending").lower()
969 sort_dict = {"descending": "DESC", "ascending": "ASC"}
970
971 if sort_order not in sort_dict:
972 raise InvalidAttributeError(sort_order, sort_order, sort_dict.keys())
973
974 XML.SubElement(pdef, "sortOrder").text = sort_dict[sort_order]
975 mapping = [
976 ("maximum-versions-to-display", "maxVersions", 10),
977 ("repository-username", "username", ""),
978 ("repository-password", "password", ""),
979 ]
980 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
981
982
983 def hidden_param(parser, xml_parent, data):
984 """yaml: hidden
985 Allows you to use parameters hidden from the build with parameter page.
986
987 Requires the Jenkins :jenkins-plugins:`Hidden Parameter Plugin
988 <hidden-parameter>`.
989
990 :arg str name: the name of the parameter
991 :arg str default: the default value of the parameter (optional)
992 :arg str description: a description of the parameter (optional)
993
994 Example:
995
996 .. literalinclude::
997 /../../tests/parameters/fixtures/hidden-param001.yaml
998 :language: yaml
999
1000 """
1001 base_param(
1002 parser, xml_parent, data, True, "com.wangyin.parameter.WHideParameterDefinition"
1003 )
1004
1005
1006 def random_string_param(registry, xml_parent, data):
1007 """yaml: random-string
1008 This parameter generates a random string and passes it to the
1009 build, preventing Jenkins from combining queued builds.
1010
1011 Requires the Jenkins :jenkins-plugins:`Random String Parameter Plugin
1012 <random-string-parameter>`.
1013
1014 :arg str name: Name of the parameter
1015 :arg str description: Description of the parameter (default '')
1016 :arg str failed-validation-message: Failure message to display for invalid
1017 input (default '')
1018
1019 Example:
1020
1021 .. literalinclude::
1022 /../../tests/parameters/fixtures/random-string-param001.yaml
1023 :language: yaml
1024 """
1025 pdef = XML.SubElement(
1026 xml_parent,
1027 "hudson.plugins.random__string__parameter." "RandomStringParameterDefinition",
1028 )
1029 if "name" not in data:
1030 raise JenkinsJobsException("random-string must have a name parameter.")
1031
1032 mapping = [
1033 ("name", "name", None),
1034 ("description", "description", ""),
1035 ("failed-validation-message", "failedValidationMessage", ""),
1036 ]
1037 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
1038
1039
1040 def git_parameter_param(registry, xml_parent, data):
1041 """yaml: git-parameter
1042 This parameter allows you to select a git tag, branch or revision number as
1043 parameter in Parametrized builds.
1044
1045 Requires the Jenkins :jenkins-plugins:`Git Parameter Plugin
1046 <git-parameter>`.
1047
1048 :arg str name: Name of the parameter
1049 :arg str description: Description of the parameter (default '')
1050 :arg str type: The type of the list of parameters (default 'PT_TAG')
1051
1052 :Allowed Values: * **PT_TAG** list of all commit tags in repository -
1053 returns Tag Name
1054 * **PT_BRANCH** list of all branches in repository -
1055 returns Branch Name
1056 * **PT_BRANCH_TAG** list of all commit tags and all
1057 branches in repository - returns Tag Name or Branch
1058 Name
1059 * **PT_REVISION** list of all revision sha1 in repository
1060 followed by its author and date - returns Tag SHA1
1061 * **PT_PULL_REQUEST**
1062
1063 :arg str branch: Name of branch to look in. Used only if listing
1064 revisions. (default '')
1065 :arg str branchFilter: Regex used to filter displayed branches. If blank,
1066 the filter will default to ".*". Remote branches will be listed with
1067 the remote name first. E.g., "origin/master" (default '.*')
1068 :arg str tagFilter: Regex used to filter displayed branches. If blank, the
1069 filter will default to ".*". Remote branches will be listed with the
1070 remote name first. E.g., "origin/master" (default '*')
1071 :arg str sortMode: Mode of sorting. (default 'NONE')
1072
1073 :Allowed Values: * **NONE**
1074 * **DESCENDING**
1075 * **ASCENDING**
1076 * **ASCENDING_SMART**
1077 * **DESCENDING_SMART**
1078
1079 :arg str defaultValue: This value is returned when list is empty. (default
1080 '')
1081 :arg str selectedValue: Which value is selected, after loaded parameters.
1082 If you choose 'default', but default value is not present on the list,
1083 nothing is selected. (default 'NONE')
1084
1085 :Allowed Values: * **NONE**
1086 * **TOP**
1087 * **DEFAULT**
1088
1089 :arg str useRepository: If in the task is defined multiple repositories
1090 parameter specifies which the repository is taken into account. If the
1091 parameter is not defined, is taken first defined repository. The
1092 parameter is a regular expression which is compared with a URL
1093 repository. (default '')
1094 :arg bool quickFilterEnabled: When this option is enabled will show a text
1095 field. Parameter is filtered on the fly. (default false)
1096
1097 Minimal Example:
1098
1099 .. literalinclude::
1100 /../../tests/parameters/fixtures/git-parameter-param-minimal.yaml
1101 :language: yaml
1102
1103 Full Example:
1104
1105 .. literalinclude::
1106 /../../tests/parameters/fixtures/git-parameter-param-full.yaml
1107 :language: yaml
1108 """
1109 pdef = XML.SubElement(
1110 xml_parent,
1111 "net.uaznia.lukanus.hudson.plugins.gitparameter." "GitParameterDefinition",
1112 )
1113
1114 valid_types = [
1115 "PT_TAG",
1116 "PT_BRANCH",
1117 "PT_BRANCH_TAG",
1118 "PT_REVISION",
1119 "PT_PULL_REQUEST",
1120 ]
1121
1122 valid_sort_modes = [
1123 "NONE",
1124 "ASCENDING",
1125 "ASCENDING_SMART",
1126 "DESCENDING",
1127 "DESCENDING_SMART",
1128 ]
1129
1130 valid_selected_values = ["NONE", "TOP", "DEFAULT"]
1131
1132 mapping = [
1133 ("name", "name", None),
1134 ("description", "description", ""),
1135 ("type", "type", "PT_TAG", valid_types),
1136 ("branch", "branch", ""),
1137 ("tagFilter", "tagFilter", "*"),
1138 ("branchFilter", "branchFilter", ".*"),
1139 ("sortMode", "sortMode", "NONE", valid_sort_modes),
1140 ("defaultValue", "defaultValue", ""),
1141 ("selectedValue", "selectedValue", "NONE", valid_selected_values),
1142 ("useRepository", "useRepository", ""),
1143 ("quickFilterEnabled", "quickFilterEnabled", False),
1144 ]
1145 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
1146
1147
1148 def param_separator(registry, xml_parent, data):
1149 """yaml: parameter-separator
1150 A parameter separator.
1151
1152 :arg str name: name of the separator (default "", the plugin will assign a randomly generated UUID if not specified)
1153 :arg str separator-style: the style of the separator. Uses CSS. (default "")
1154 :arg str section-header-text: the section header text of the separator (default "")
1155 :arg str section-header-style: the section header style (CSS) of the separator. Uses CSS. (default "")
1156
1157 Example::
1158
1159 parameters:
1160 - parameter-separator:
1161 name: lorem
1162 separator-style: FOO
1163 section-header: bar
1164 section-header-style: font-weight:bold;z-index:10000
1165 """
1166 element_name = "jenkins.plugins.parameter__separator.ParameterSeparatorDefinition"
1167 pdef = XML.SubElement(xml_parent, element_name)
1168 XML.SubElement(pdef, "description") # To create empty description tag
1169 mapping = [
1170 ("name", "name", ""),
1171 ("section-header", "sectionHeader", ""),
1172 ("section-header-style", "sectionHeaderStyle", ""),
1173 ("separator-style", "separatorStyle", ""),
1174 ]
1175 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
1176
1177
1178 def __handle_unochoice_script(data, pdef, script_type, main_script_xml):
1179
1180 if script_type == "script":
1181 secure_script_xml = XML.SubElement(main_script_xml, "secureScript")
1182 elif script_type == "fallback-script":
1183 secure_script_xml = XML.SubElement(main_script_xml, "secureFallbackScript")
1184
1185 sub_script_xml = XML.SubElement(secure_script_xml, "script")
1186 groovy_sandbox_xml = XML.SubElement(secure_script_xml, "sandbox")
1187
1188 script = data.get(script_type, {})
1189 sub_script_xml.text = script.get("groovy", "")
1190 groovy_sandbox_xml.text = str(script.get("use-groovy-sandbox", True)).lower()
1191
1192 if "script-additional-classpath" in script:
1193 classpath_xml = XML.SubElement(secure_script_xml, "classpath")
1194 for additional_classpath in script.get("script-additional-classpath"):
1195 entry_xml = XML.SubElement(classpath_xml, "entry")
1196 url_xml = XML.SubElement(entry_xml, "url")
1197 url_xml.text = additional_classpath
1198
1199
1200 def active_choices_param(registry, xml_parent, data):
1201 """yaml: active-choices
1202 Active Choices Parameter
1203
1204 Requires the Jenkins :jenkins-plugins:`Active Choices Plug-in
1205 <uno-choice>`.
1206
1207 :arg str name: Name of the parameter (required).
1208 :arg str description: Description of the parameter.
1209 :arg list script: Use a Groovy script to define the parameter.
1210
1211 :Parameter: * **groovy** (`str`) Groovy DSL Script
1212 * **use-groovy-sandbox** (`bool`) To run this
1213 Groovy script in a sandbox with limited abilities
1214 (default True)
1215 * **script-additional-classpath** (`list`) Additional
1216 classpath entries accessible from the script.
1217 :arg list fallback-script: Use a Fallback script. If the script
1218 (specified above) fails, the fallback script will be used as a fallback.
1219
1220 :Parameter: * **groovy** (`str`) Groovy DSL Script
1221 * **use-groovy-sandbox** (`bool`) To run this Groovy
1222 script in a sandbox with limited abilities.
1223 (default True)
1224 * **script-additional-classpath** (`list`) Additional
1225 classpath entries accessible from the script.
1226 :arg bool enable-filters: If enabled a text box will appear next to
1227 this element and will permit the user to filter its entries. The
1228 list values never get re-evaluated (default False).
1229 :arg int filter-starts-at: How many characters a user must enter
1230 before the filter is applied (default 1).
1231 :arg str choice-type: type of the choices. (default 'single-select')
1232
1233 :Allowed Values: * **single-select**
1234 * **multi-select**
1235 * **radio-buttons**
1236 * **checkboxes**
1237
1238 Minimal Example:
1239
1240 .. literalinclude::
1241 /../../tests/yamlparser/job_fixtures/active-choices-param001.yaml
1242 :language: yaml
1243
1244 Full Example:
1245
1246 .. literalinclude::
1247 /../../tests/yamlparser/job_fixtures/active-choices-param002.yaml
1248 :language: yaml
1249 """
1250 element_name = "org.biouno.unochoice.ChoiceParameter"
1251 pdef = XML.SubElement(xml_parent, element_name)
1252
1253 __active_choice_param_internal(pdef, data)
1254
1255
1256 def active_choices_reactive_param(registry, xml_parent, data):
1257 """yaml: active-choices-reactive
1258 Active Choices Reactive Parameter
1259
1260 Requires the Jenkins :jenkins-plugins:`Active Choices Plug-in
1261 <uno-choice>`.
1262
1263 :arg str name: Name of the parameter (required).
1264 :arg str description: Description of the parameter.
1265 :arg list script: Use a Groovy script to define the parameter.
1266
1267 :Parameter: * **groovy** (`str`) Groovy DSL Script
1268 * **use-groovy-sandbox** (`bool`) To run this
1269 Groovy script in a sandbox with limited abilities
1270 (default True)
1271 * **script-additional-classpath** (`list`) Additional
1272 classpath entries accessible from the script.
1273 :arg list fallback-script: Use a Fallback script. If the script
1274 (specified above) fails, the fallback script will be used as a fallback.
1275
1276 :Parameter: * **groovy** (`str`) Groovy DSL Script
1277 * **use-groovy-sandbox** (`bool`) To run this Groovy
1278 script in a sandbox with limited abilities.
1279 (default True)
1280 * **script-additional-classpath** (`list`) Additional
1281 classpath entries accessible from the script.
1282 :arg bool enable-filters: If enabled a text box will appear next to
1283 this element and will permit the user to filter its entries. The
1284 list values never get re-evaluated (default False).
1285 :arg int filter-starts-at: How many characters a user must enter
1286 before the filter is applied (default 1).
1287 :arg str choice-type: type of the choices. (default 'single-select')
1288
1289 :Allowed Values: * **single-select**
1290 * **multi-select**
1291 * **radio-buttons**
1292 * **checkboxes**
1293 :arg str referenced-parameters: Comma separated list of other job
1294 parameters referenced in the uno-choice script
1295
1296 Minimal Example:
1297
1298 .. literalinclude::
1299 /../../tests/yamlparser/job_fixtures/active-choices-reactive-param001.yaml
1300 :language: yaml
1301
1302 Full Example:
1303
1304 .. literalinclude::
1305 /../../tests/yamlparser/job_fixtures/active-choices-reactive-param002.yaml
1306 :language: yaml
1307 """
1308
1309 element_name = "org.biouno.unochoice.CascadeChoiceParameter"
1310 pdef = XML.SubElement(xml_parent, element_name)
1311
1312 __active_choice_param_internal(pdef, data)
1313
1314 mapping = [
1315 ("referenced-parameters", "referencedParameters", ""),
1316 ("random-name", "randomName", "choice-param-{0}".format(data["name"]).lower()),
1317 ("visible-items", "visibleItemCount", 1),
1318 ]
1319 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=False)
1320 XML.SubElement(pdef, "parameters", {"class": "linked-hash-map"})
1321
1322
1323 def __active_choice_param_internal(xml_parent, data):
1324 valid_choice_types_dict = {
1325 "single-select": "PT_SINGLE_SELECT",
1326 "multi-select": "PT_MULTI_SELECT",
1327 "radio-buttons": "PT_RADIO",
1328 "checkboxes": "PT_CHECKBOX",
1329 }
1330
1331 mapping = [
1332 ("name", "name", None),
1333 ("description", "description", ""),
1334 ("choice-type", "choiceType", "single-select", valid_choice_types_dict),
1335 ("enable-filters", "filterable", False),
1336 ("filter-starts-at", "filterLength", 1),
1337 ("_project-name", "projectName", None),
1338 ("_project-full-name", "projectFullName", None),
1339 ]
1340
1341 main_script_xml = XML.SubElement(xml_parent, "script")
1342 main_script_xml.set("class", "org.biouno.unochoice.model.GroovyScript")
1343 __handle_unochoice_script(data, xml_parent, "fallback-script", main_script_xml)
1344 __handle_unochoice_script(data, xml_parent, "script", main_script_xml)
1345
1346 helpers.convert_mapping_to_xml(xml_parent, data, mapping, fail_required=True)
1347
1348
1349 def dynamic_reference_param(registry, xml_parent, data):
1350 """yaml: dynamic-reference
1351 Active Choices Reactive Reference Parameter
1352
1353 Requires the Jenkins :jenkins-plugins:`Active Choices Plug-in
1354 <uno-choice>`.
1355
1356 :arg str name: Name of the parameter (required).
1357 :arg str description: Description of the parameter.
1358 :arg list script: Use a Groovy script to define the parameter.
1359
1360 :Parameter: * **groovy** (`str`) Groovy DSL Script
1361 * **use-groovy-sandbox** (`bool`) To run this
1362 Groovy script in a sandbox with limited abilities
1363 (default True)
1364 * **script-additional-classpath** (`list`) Additional
1365 classpath entries accessible from the script.
1366 :arg list fallback-script: Use a Fallback script. If the script
1367 (specified above) fails, the fallback script will be used as a fallback.
1368
1369 :Parameter: * **groovy** (`str`) Groovy DSL Script
1370 * **use-groovy-sandbox** (`bool`) To run this Groovy
1371 script in a sandbox with limited abilities.
1372 (default True)
1373 * **script-additional-classpath** (`list`) Additional
1374 classpath entries accessible from the script.
1375 :arg bool omit-value-field: By default Dynamic Reference Parameters always
1376 include a hidden input for the value. If your script creates an input
1377 HTML element, you can check this option and the value input field will
1378 be omitted (default False).
1379 :arg str referenced-parameters: Comma separated list of other job
1380 parameters referenced in the uno-choice script. When any of the
1381 referenced parameters are updated, the Groovy script will
1382 re-evaluate the choice list using the updated values of referenced
1383 parameters.
1384 :arg str choice-type: type of the choices. (default 'input-text-box')
1385
1386 :Allowed Values: * **input-text-box**
1387 * **numbered-list**
1388 * **bullet-items-list**
1389 * **formatted-html**
1390 * **formatted-hidden-html**
1391
1392 Minimal Example:
1393
1394 .. literalinclude::
1395 /../../tests/yamlparser/job_fixtures/dynamic-reference-param001.yaml
1396 :language: yaml
1397
1398 Full Example:
1399
1400 .. literalinclude::
1401 /../../tests/yamlparser/job_fixtures/dynamic-reference-param002.yaml
1402 :language: yaml
1403 """
1404 element_name = "org.biouno.unochoice.DynamicReferenceParameter"
1405 pdef = XML.SubElement(xml_parent, element_name)
1406
1407 valid_choice_types_dict = {
1408 "input-text-box": "ET_TEXT_BOX",
1409 "numbered-list": "ET_ORDERED_LIST",
1410 "bullet-items-list": "ET_UNORDERED_LIST",
1411 "formatted-html": "ET_FORMATTED_HTML",
1412 "formatted-hidden-html": "ET_FORMATTED_HIDDEN_HTML",
1413 }
1414
1415 mapping = [
1416 ("name", "name", None),
1417 ("description", "description", ""),
1418 ("choice-type", "choiceType", "input-text-box", valid_choice_types_dict),
1419 ("_project-name", "projectName", None),
1420 ("_project-full-name", "projectFullName", None),
1421 ("referenced-parameters", "referencedParameters", ""),
1422 ("omit-value-field", "omitValueField", False),
1423 ]
1424
1425 main_script_xml = XML.SubElement(pdef, "script")
1426 main_script_xml.set("class", "org.biouno.unochoice.model.GroovyScript")
1427 __handle_unochoice_script(data, pdef, "fallback-script", main_script_xml)
1428 __handle_unochoice_script(data, pdef, "script", main_script_xml)
1429
1430 XML.SubElement(pdef, "parameters") # Empty parameters tag
1431
1432 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
1433
1434
1435 def persistent_string_param(registry, xml_parent, data):
1436 """yaml: persistent-string
1437 A persistent string parameter.
1438
1439 Requires the Jenkins :jenkins-plugins:`Persistent Parameter Plugin
1440 <persistent-parameter>`.
1441
1442 :arg str name: the name of the parameter
1443 :arg str default: the default value of the parameter (optional)
1444 :arg str description: a description of the parameter (optional)
1445 :arg bool trim: strip whitespaces from the begnning and end
1446 of the string (optional, default: false)
1447 :arg bool successfulOnly: if true, then the value of the parameter
1448 gets persisted only between successful builds
1449 (optional, default: false)
1450
1451 Example::
1452
1453 parameters:
1454 - persistent-string:
1455 name: FOO
1456 default: bar
1457 description: "A parameter named FOO, defaults to 'bar'."
1458 trim: false
1459 successfulOnly: false
1460 """
1461 pdef = base_param(
1462 registry,
1463 xml_parent,
1464 data,
1465 True,
1466 "com.gem.persistentparameter.PersistentStringParameterDefinition",
1467 )
1468
1469 mapping = [("trim", "trim", False), ("successfulOnly", "successfulOnly", False)]
1470 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
1471
1472
1473 def persistent_bool_param(registry, xml_parent, data):
1474 """yaml: persistent-bool
1475 A persistent boolean parameter.
1476
1477 Requires the Jenkins :jenkins-plugins:`Persistent Parameter Plugin
1478 <persistent-parameter>`.
1479
1480 :arg str name: the name of the parameter
1481 :arg str default: the default value of the parameter (optional)
1482 :arg str description: a description of the parameter (optional)
1483 :arg bool successfulOnly: if true, then the value of the parameter
1484 gets persisted only between successful builds
1485 (optional, default: false)
1486
1487 Example::
1488
1489 parameters:
1490 - persistent-bool:
1491 name: FOO
1492 default: false
1493 description: "A persistent parameter named FOO, defaults to 'false'."
1494 successfulOnly: false
1495 """
1496 data["default"] = str(data.get("default", False)).lower()
1497 pdef = base_param(
1498 registry,
1499 xml_parent,
1500 data,
1501 True,
1502 "com.gem.persistentparameter.PersistentBooleanParameterDefinition",
1503 )
1504
1505 mapping = [("successfulOnly", "successfulOnly", False)]
1506 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
1507
1508
1509 def persistent_text_param(registry, xml_parent, data):
1510 """yaml: persistent-text
1511 A persistent text parameter.
1512
1513 Requires the Jenkins :jenkins-plugins:`Persistent Parameter Plugin
1514 <persistent-parameter>`.
1515
1516 :arg str name: the name of the parameter
1517 :arg str default: the default value of the parameter (optional)
1518 :arg str description: a description of the parameter (optional)
1519 :arg bool trim: strip whitespaces from the begnning and end
1520 of the string (optional, default: false)
1521 :arg bool successfulOnly: if true, then the value of the parameter
1522 gets persisted only between successful builds
1523 (optional, default: false)
1524
1525 Example::
1526
1527 parameters:
1528 - persistent-text:
1529 name: FOO
1530 default: bar
1531 description: "A persistent parameter named FOO, defaults to 'bar'."
1532 successfulOnly: false
1533 """
1534
1535 pdef = base_param(
1536 registry,
1537 xml_parent,
1538 data,
1539 True,
1540 "com.gem.persistentparameter.PersistentTextParameterDefinition",
1541 )
1542
1543 mapping = [("trim", "trim", False), ("successfulOnly", "successfulOnly", False)]
1544 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
1545
1546
1547 def persistent_choice_param(registry, xml_parent, data):
1548 """yaml: persistent-choice
1549 A persistent single selection parameter.
1550
1551 Requires the Jenkins :jenkins-plugins:`Persistent Parameter Plugin
1552 <persistent-parameter>`.
1553
1554 :arg str name: the name of the parameter
1555 :arg list choices: the available choices, first one is the default one.
1556 :arg str description: a description of the parameter (optional)
1557 :arg bool successfulOnly: if true, then the value of the parameter
1558 gets persisted only between successful builds
1559 (optional, default: false)
1560
1561 Example::
1562
1563 parameters:
1564 - persistent-choice:
1565 name: project
1566 choices:
1567 - nova
1568 - glance
1569 description: "On which project to run?"
1570 successfulOnly: false
1571 """
1572 pdef = base_param(
1573 registry,
1574 xml_parent,
1575 data,
1576 False,
1577 "com.gem.persistentparameter.PersistentChoiceParameterDefinition",
1578 )
1579 choices = XML.SubElement(pdef, "choices", {"class": "java.util.Arrays$ArrayList"})
1580 a = XML.SubElement(choices, "a", {"class": "string-array"})
1581 for choice in data["choices"]:
1582 XML.SubElement(a, "string").text = choice
1583
1584 mapping = [("successfulOnly", "successfulOnly", False)]
1585 helpers.convert_mapping_to_xml(pdef, data, mapping, fail_required=True)
1586
1587
1588 class Parameters(jenkins_jobs.modules.base.Base):
1589 sequence = 21
1590
1591 component_type = "parameter"
1592 component_list_type = "parameters"
1593
1594 @staticmethod
1595 def _extend_uno_choice_param_data(param, param_type, data):
1596 """Pass job name to the uno-choice plugin"""
1597 if param_type in (
1598 "active-choices",
1599 "active-choices-reactive",
1600 "dynamic-reference",
1601 ):
1602 # Extend uno-choice plugin parameter data with mandatory properties:
1603 # `project-name` and `project-full-name`
1604 param[param_type]["_project-name"] = data["name"].split("/")[-1]
1605 param[param_type]["_project-full-name"] = data["name"]
1606
1607 def gen_xml(self, xml_parent, data):
1608 properties = xml_parent.find("properties")
1609 if properties is None:
1610 properties = XML.SubElement(xml_parent, "properties")
1611
1612 parameters = data.get("parameters", [])
1613 hmodel = "hudson.model."
1614 if parameters:
1615 # The conditionals here are to work around the extended_choice
1616 # parameter also being definable in the properties module. This
1617 # usage has been deprecated but not removed. Because it may have
1618 # added these elements before us, we need to check if they already
1619 # exist, and only add them if they're missing.
1620 pdefp = properties.find(hmodel + "ParametersDefinitionProperty")
1621 if pdefp is None:
1622 pdefp = XML.SubElement(
1623 properties, hmodel + "ParametersDefinitionProperty"
1624 )
1625 pdefs = pdefp.find("parameterDefinitions")
1626 if pdefs is None:
1627 pdefs = XML.SubElement(pdefp, "parameterDefinitions")
1628 for idx, param in enumerate(parameters):
1629 if isinstance(parameters, LocList):
1630 param_pos = parameters.value_pos[idx]
1631 else:
1632 param_pos = None
1633 if not isinstance(param, dict):
1634 # Macro parameter without arguments
1635 param = {param: {}}
1636 param_type = next(iter(param))
1637 macro_dict = self.registry.macros.get("parameter", {})
1638 macro = macro_dict.get(param_type)
1639 if not macro:
1640 self._extend_uno_choice_param_data(param, param_type, data)
1641 else:
1642 # Process macro case.
1643 for macro_param in macro.elements:
1644 for macro_param_type in macro_param:
1645 self._extend_uno_choice_param_data(
1646 macro_param, macro_param_type, data
1647 )
1648 self.registry.dispatch(
1649 "parameter", pdefs, param, component_pos=param_pos
1650 )