summaryrefslogtreecommitdiffstats
path: root/scripts/compose_pki_migrate_packages
Commit message (Expand)AuthorAgeFilesLines
* update to b3Ade Lee2012-11-121-1/+1
* Update to b2 releaseAde Lee2012-10-301-1/+1
* Update release to b1Ade Lee2012-10-081-1/+1
* Updated release to a2Ade Lee2012-10-011-1/+1
* Removed unnecessary pki folder.Endi Sukma Dewata2012-03-261-0/+194
> 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352
# Copyright 2012 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.


"""
Wrappers can alter the way the build is run as well as the build output.

**Component**: wrappers
  :Macro: wrapper
  :Entry Point: jenkins_jobs.wrappers

"""

import logging
import pkg_resources
import xml.etree.ElementTree as XML

from jenkins_jobs.errors import InvalidAttributeError
from jenkins_jobs.errors import JenkinsJobsException
from jenkins_jobs.errors import MissingAttributeError
import jenkins_jobs.modules.base
from jenkins_jobs.modules.builders import create_builders
from jenkins_jobs.modules.helpers import artifactory_common_details
from jenkins_jobs.modules.helpers import artifactory_deployment_patterns
from jenkins_jobs.modules.helpers import artifactory_env_vars_patterns
from jenkins_jobs.modules.helpers import artifactory_optional_props
from jenkins_jobs.modules.helpers import artifactory_repository
from jenkins_jobs.modules.helpers import config_file_provider_builder
from jenkins_jobs.modules.helpers import convert_mapping_to_xml

logger = logging.getLogger(__name__)

MIN_TO_SEC = 60


def docker_custom_build_env(parser, xml_parent, data):
    """yaml: docker-custom-build-env
    Allows the definition of a build environment for a job using a Docker
    container.
    Requires the Jenkins :jenkins-wiki:`CloudBees Docker Custom Build
    Environment Plugin<CloudBees+Docker+Custom+Build+Environment+Plugin>`.

    :arg str image-type: Docker image type. Valid values and their
        additional attributes described in the image_types_ table
    :arg str docker-tool: The name of the docker installation to use
        (default 'Default')
    :arg str host: URI to the docker host you are using
    :arg str credentials-id: Argument to specify the ID of credentials to use
        for docker host (optional)
    :arg str registry-credentials-id: Argument to specify the ID of
        credentials to use for docker registry (optional)
    :arg list volumes: Volumes to bind mound from slave host into container

        :volume: * **host-path** (`str`) Path on host
                 * **path** (`str`) Path inside container

    :arg bool verbose: Log docker commands executed by plugin on build log
        (default false)
    :arg bool privileged: Run in privileged mode (default false)
    :arg bool force-pull: Force pull (default false)
    :arg str group: The user to run build has to be the same as the Jenkins
        slave user so files created in workspace have adequate owner and
        permission set
    :arg str command: Container start command (default '/bin/cat')
    :arg str net: Network bridge (default 'bridge')

    .. _image_types:

    ================== ====================================================
    Image Type         Description
    ================== ====================================================
    dockerfile         Build docker image from a Dockerfile in project
                       workspace. With this option, project can define the
                       build environment as a Dockerfile stored in SCM with
                       project source code

                         :context-path: (str) Path to docker context
                           (default '.')
                         :dockerfile: (str) Use an alternate Dockerfile to
                           build the container hosting this build
                           (default 'Dockerfile')
    pull               Pull specified docker image from Docker repository

                         :image: (str) Image id/tag
    ================== ====================================================

    Example:

    .. literalinclude::
        /../../tests/wrappers/fixtures/docker-custom-build-env001.yaml
       :language: yaml
    """
    core_prefix = 'com.cloudbees.jenkins.plugins.okidocki.'
    entry_xml = XML.SubElement(
        xml_parent, core_prefix + 'DockerBuildWrapper')
    entry_xml.set('plugin', 'docker-custom-build-environment')

    selectorobj = XML.SubElement(entry_xml, 'selector')
    image_type = data['image-type']
    if image_type == 'dockerfile':
        selectorobj.set('class', core_prefix + 'DockerfileImageSelector')
        XML.SubElement(selectorobj, 'contextPath').text = data.get(
            'context-path', '.')
        XML.SubElement(selectorobj, 'dockerfile').text = data.get(
            'dockerfile', 'Dockerfile')
    elif image_type == 'pull':
        selectorobj.set('class', core_prefix + 'PullDockerImageSelector')
        XML.SubElement(selectorobj, 'image').text = data.get(
            'image', '')

    XML.SubElement(entry_xml, 'dockerInstallation').text = data.get(
        'docker-tool', 'Default')

    host = XML.SubElement(entry_xml, 'dockerHost')
    host.set('plugin', 'docker-commons')
    if data.get('host'):
        XML.SubElement(host, 'uri').text = data['host']
    if data.get('credentials-id'):
        XML.SubElement(host, 'credentialsId').text = data['credentials-id']
    XML.SubElement(entry_xml, 'dockerRegistryCredentials').text = data.get(
        'registry-credentials-id', '')

    volumesobj = XML.SubElement(entry_xml, 'volumes')
    volumes = data.get('volumes', [])
    if not volumes:
        volumesobj.set('class', 'empty-list')
    else:
        for volume in volumes:
            volumeobj = XML.SubElement(
                volumesobj, 'com.cloudbees.jenkins.plugins.okidocki.Volume')
            XML.SubElement(volumeobj, 'hostPath').text = volume['volume'].get(
                'host-path', '')
            XML.SubElement(volumeobj, 'path').text = volume['volume'].get(
                'path', '')

    XML.SubElement(entry_xml, 'forcePull').text = str(data.get(
        'force-pull', False)).lower()
    XML.SubElement(entry_xml, 'privileged').text = str(data.get(
        'privileged', False)).lower()
    XML.SubElement(entry_xml, 'verbose').text = str(data.get(
        'verbose', False)).lower()
    XML.SubElement(entry_xml, 'group').text = data.get('group', '')
    XML.SubElement(entry_xml, 'command').text = data.get('command', '/bin/cat')
    XML.SubElement(entry_xml, 'net').text = data.get('net', 'bridge')


def ci_skip(parser, xml_parent, data):
    """yaml: ci-skip
    Skip making a build for certain push.
    Just add [ci skip] into your commit's message to let Jenkins know,
    that you do not want to perform build for the next push.
    Requires the Jenkins :jenkins-wiki:`Ci Skip Plugin <Ci+Skip+Plugin>`.

    Example:

    .. literalinclude:: /../../tests/wrappers/fixtures/ci-skip001.yaml
    """
    rpobj = XML.SubElement(xml_parent, 'ruby-proxy-object')
    robj = XML.SubElement(rpobj, 'ruby-object', attrib={
        'pluginid': 'ci-skip',
        'ruby-class': 'Jenkins::Tasks::BuildWrapperProxy'
    })
    pluginid = XML.SubElement(robj, 'pluginid', {
        'pluginid': 'ci-skip', 'ruby-class': 'String'
    })
    pluginid.text = 'ci-skip'
    obj = XML.SubElement(robj, 'object', {
        'ruby-class': 'CiSkipWrapper', 'pluginid': 'ci-skip'
    })
    XML.SubElement(obj, 'ci__skip', {
        'pluginid': 'ci-skip', 'ruby-class': 'NilClass'
    })


def config_file_provider(parser, xml_parent, data):
    """yaml: config-file-provider
    Provide configuration files (i.e., settings.xml for maven etc.)
    which will be copied to the job's workspace.
    Requires the Jenkins :jenkins-wiki:`Config File Provider Plugin
    <Config+File+Provider+Plugin>`.

    :arg list files: List of managed config files made up of three
      parameters

      :files: * **file-id** (`str`) -- The identifier for the managed config
                file
              * **target** (`str`) -- Define where the file should be created
                (default '')
              * **variable** (`str`) -- Define an environment variable to be
                used (default '')

    Example:

    .. literalinclude:: \
    /../../tests/wrappers/fixtures/config-file-provider003.yaml
       :language: yaml
    """
    cfp = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.configfiles.'
                         'buildwrapper.ConfigFileBuildWrapper')
    cfp.set('plugin', 'config-file-provider')
    config_file_provider_builder(cfp, data)


def logfilesize(parser, xml_parent, data):
    """yaml: logfilesize
    Abort the build if its logfile becomes too big.
    Requires the Jenkins :jenkins-wiki:`Logfilesizechecker Plugin
    <Logfilesizechecker+Plugin>`.

    :arg bool set-own: Use job specific maximum log size instead of global
        config value (default false).
    :arg bool fail: Make builds aborted by this wrapper be marked as "failed"
        (default false).
    :arg int size: Abort the build if logfile size is bigger than this
        value (in MiB, default 128). Only applies if set-own is true.

    Full Example:

    .. literalinclude:: /../../tests/wrappers/fixtures/logfilesize-full.yaml

    Minimal Example:

    .. literalinclude:: /../../tests/wrappers/fixtures/logfilesize-minimal.yaml
    """
    lfswrapper = XML.SubElement(xml_parent,
                                'hudson.plugins.logfilesizechecker.'
                                'LogfilesizecheckerWrapper')
    lfswrapper.set("plugin", "logfilesizechecker")

    mapping = [
        ('set-own', 'setOwn', False),
        ('size', 'maxLogSize', 128),
        ('fail', 'failBuild', False),
    ]
    convert_mapping_to_xml(lfswrapper, data, mapping, fail_required=True)


def timeout(parser, xml_parent, data):
    """yaml: timeout
    Abort the build if it runs too long.
    Requires the Jenkins :jenkins-wiki:`Build Timeout Plugin
    <Build-timeout+Plugin>`.

    :arg bool fail: Mark the build as failed (default false)
    :arg bool abort: Mark the build as aborted (default false)
    :arg bool write-description: Write a message in the description
        (default false)
    :arg int timeout: Abort the build after this number of minutes (default 3)
    :arg str timeout-var: Export an environment variable to reference the
        timeout value (optional)
    :arg str type: Timeout type to use (default absolute)
    :type values:
        * **likely-stuck**
        * **no-activity**
        * **elastic**
        * **absolute**
        * **deadline**

    :arg int elastic-percentage: Percentage of the three most recent builds
        where to declare a timeout, only applies to **elastic** type.
        (default 0)
    :arg int elastic-number-builds: Number of builds to consider computing
        average duration, only applies to **elastic** type. (default 3)
    :arg int elastic-default-timeout: Timeout to use if there were no previous
        builds, only applies to **elastic** type. (default 3)

    :arg str deadline-time: Build terminate automatically at next deadline time
        (HH:MM:SS), only applies to **deadline** type. (default 0:00:00)
    :arg int deadline-tolerance: Period in minutes after deadline when a job
        should be immediately aborted, only applies to **deadline** type.
        (default 1)

    Example (Version < 1.14):

    .. literalinclude:: /../../tests/wrappers/fixtures/timeout/timeout001.yaml

    .. literalinclude:: /../../tests/wrappers/fixtures/timeout/timeout002.yaml

    .. literalinclude:: /../../tests/wrappers/fixtures/timeout/timeout003.yaml

    Example (Version >= 1.14):

    .. literalinclude::
        /../../tests/wrappers/fixtures/timeout/version-1.14/absolute001.yaml

    .. literalinclude::
        /../../tests/wrappers/fixtures/timeout/version-1.14/no-activity001.yaml

    .. literalinclude::
        /../../tests/wrappers/fixtures/timeout/version-1.14/likely-stuck001.yaml

    .. literalinclude::
        /../../tests/wrappers/fixtures/timeout/version-1.14/elastic001.yaml

    .. literalinclude::
        /../../tests/wrappers/fixtures/timeout/version-1.15/deadline001.yaml

    """
    prefix = 'hudson.plugins.build__timeout.'
    twrapper = XML.SubElement(xml_parent, prefix + 'BuildTimeoutWrapper')

    plugin_info = parser.registry.get_plugin_info(
        "Jenkins build timeout plugin")
    version = pkg_resources.parse_version(plugin_info.get("version", "0"))

    valid_strategies = ['absolute', 'no-activity', 'likely-stuck', 'elastic',
                        'deadline']

    if version >= pkg_resources.parse_version("1.14"):
        strategy = data.get('type', 'absolute')
        if strategy not in valid_strategies:
            InvalidAttributeError('type', strategy, valid_strategies)

        if strategy == "absolute":
            strategy_element = XML.SubElement(
                twrapper, 'strategy',
                {'class': "hudson.plugins.build_timeout."
                          "impl.AbsoluteTimeOutStrategy"})
            XML.SubElement(strategy_element, 'timeoutMinutes'
                           ).text = str(data.get('timeout', 3))
        elif strategy == "no-activity":
            strategy_element = XML.SubElement(
                twrapper, 'strategy',
                {'class': "hudson.plugins.build_timeout."
                          "impl.NoActivityTimeOutStrategy"})
            timeout_sec = int(data.get('timeout', 3)) * MIN_TO_SEC
            XML.SubElement(strategy_element,
                           'timeoutSecondsString').text = str(timeout_sec)
        elif strategy == "likely-stuck":
            strategy_element = XML.SubElement(
                twrapper, 'strategy',
                {'class': "hudson.plugins.build_timeout."
                          "impl.LikelyStuckTimeOutStrategy"})
            XML.SubElement(strategy_element,
                           'timeoutMinutes').text = str(data.get('timeout', 3))
        elif strategy == "elastic":
            strategy_element = XML.SubElement(
                twrapper, 'strategy',
                {'class': "hudson.plugins.build_timeout."
                          "impl.ElasticTimeOutStrategy"})
            XML.SubElement(strategy_element, 'timeoutPercentage'
                           ).text = str(data.get('elastic-percentage', 0))
            XML.SubElement(strategy_element, 'numberOfBuilds'
                           ).text = str(data.get('elastic-number-builds', 0))
            XML.SubElement(strategy_element, 'timeoutMinutesElasticDefault'
                           ).text = str(data.get('elastic-default-timeout', 3))

        elif strategy == "deadline":
            strategy_element = XML.SubElement(
                twrapper, 'strategy',
                {'class': "hudson.plugins.build_timeout."
                          "impl.DeadlineTimeOutStrategy"})
            deadline_time = str(data.get('deadline-time', '0:00:00'))
            XML.SubElement(strategy_element,
                           'deadlineTime').text = str(deadline_time)
            deadline_tolerance = int(data.get('deadline-tolerance', 1))
            XML.SubElement(strategy_element, 'deadlineToleranceInMinutes'
                           ).text = str(deadline_tolerance)

        actions = []

        for action in ['fail', 'abort']:
            if str(data.get(action, 'false')).lower() == 'true':
                actions.append(action)

        # Set the default action to "abort"
        if len(actions) == 0:
            actions.append("abort")

        description = data.get('write-description', None)
        if description is not None:
            actions.append('write-description')

        operation_list = XML.SubElement(twrapper, 'operationList')

        for action in actions:
            fmt_str = prefix + "operations.{0}Operation"
            if action == "abort":
                XML.SubElement(operation_list, fmt_str.format("Abort"))
            elif action == "fail":
                XML.SubElement(operation_list, fmt_str.format("Fail"))
            elif action == "write-description":
                write_description = XML.SubElement(
                    operation_list, fmt_str.format("WriteDescription"))
                XML.SubElement(write_description, "description"
                               ).text = description
            else:
                raise JenkinsJobsException("Unsupported BuiltTimeoutWrapper "
                                           "plugin action: {0}".format(action))
        timeout_env_var = data.get('timeout-var')
        if timeout_env_var:
            XML.SubElement(twrapper,
                           'timeoutEnvVar').text = str(timeout_env_var)
    else:
        XML.SubElement(twrapper,
                       'timeoutMinutes').text = str(data.get('timeout', 3))
        timeout_env_var = data.get('timeout-var')
        if timeout_env_var:
            XML.SubElement(twrapper,
                           'timeoutEnvVar').text = str(timeout_env_var)
        XML.SubElement(twrapper, 'failBuild'
                       ).text = str(data.get('fail', 'false')).lower()
        XML.SubElement(twrapper, 'writingDescription'
                       ).text = str(data.get('write-description', 'false')
                                    ).lower()
        XML.SubElement(twrapper, 'timeoutPercentage'
                       ).text = str(data.get('elastic-percentage', 0))
        XML.SubElement(twrapper, 'timeoutMinutesElasticDefault'
                       ).text = str(data.get('elastic-default-timeout', 3))

        tout_type = str(data.get('type', 'absolute')).lower()
        if tout_type == 'likely-stuck':
            tout_type = 'likelyStuck'
        XML.SubElement(twrapper, 'timeoutType').text = tout_type


def timestamps(parser, xml_parent, data):
    """yaml: timestamps
    Add timestamps to the console log.
    Requires the Jenkins :jenkins-wiki:`Timestamper Plugin <Timestamper>`.

    Example::

      wrappers:
        - timestamps
    """
    XML.SubElement(xml_parent,
                   'hudson.plugins.timestamper.TimestamperBuildWrapper')


def ansicolor(parser, xml_parent, data):
    """yaml: ansicolor
    Translate ANSI color codes to HTML in the console log.
    Requires the Jenkins :jenkins-wiki:`Ansi Color Plugin <AnsiColor+Plugin>`.

    :arg string colormap: (optional) color mapping to use

    Examples::

      wrappers:
        - ansicolor

      # Explicitly setting the colormap
      wrappers:
        - ansicolor:
            colormap: vga
    """
    cwrapper = XML.SubElement(
        xml_parent,
        'hudson.plugins.ansicolor.AnsiColorBuildWrapper')

    # Optional colormap
    colormap = data.get('colormap')
    if colormap:
        XML.SubElement(cwrapper, 'colorMapName').text = colormap


def build_keeper(parser, xml_parent, data):
    """yaml: build-keeper
    Keep builds based on specific policy.
    Requires the Jenkins :jenkins-wiki:`Build Keeper Plugin
    <Build+Keeper+Plugin>`.

    :arg str policy: Policy to keep builds.

        :policy values:
          * **by-day**
          * **keep-since**
          * **build-number**
          * **keep-first-failed**
    :arg int build-period: Number argument to calculate build to keep,
        depends on the policy. (default 0)
    :arg bool dont-keep-failed: Flag to indicate if to keep failed builds.
        (default false)
    :arg int number-of-fails: number of consecutive failed builds in order
        to mark first as keep forever, only applies to keep-first-failed
        policy (default 0)

    Example:

    .. literalinclude:: /../../tests/wrappers/fixtures/build-keeper0001.yaml

    .. literalinclude:: /../../tests/wrappers/fixtures/build-keeper0002.yaml

    """

    root = XML.SubElement(xml_parent,
                          'org.jenkins__ci.plugins.build__keeper.BuildKeeper')

    valid_policies = ('by-day', 'keep-since', 'build-number',
                      'keep-first-failed')
    policy = data.get('policy')
    build_period = str(data.get('build-period', 0))
    dont_keep_failed = str(data.get('dont-keep-failed', False)).lower()

    if policy == 'by-day':
        policy_element = XML.SubElement(root,
                                        'policy',
                                        {'class': 'org.jenkins_ci.plugins.'
                                         'build_keeper.ByDayPolicy'})
        XML.SubElement(policy_element, 'buildPeriod').text = build_period
        XML.SubElement(policy_element,
                       'dontKeepFailed').text = dont_keep_failed
    elif policy == 'keep-since':
        policy_element = XML.SubElement(root,
                                        'policy',
                                        {'class': 'org.jenkins_ci.plugins.'
                                         'build_keeper.KeepSincePolicy'})
        XML.SubElement(policy_element, 'buildPeriod').text = build_period
        XML.SubElement(policy_element,
                       'dontKeepFailed').text = dont_keep_failed
    elif policy == 'build-number':
        policy_element = XML.SubElement(root,
                                        'policy',
                                        {'class': 'org.jenkins_ci.plugins.'
                                         'build_keeper.BuildNumberPolicy'})
        XML.SubElement(policy_element, 'buildPeriod').text = build_period
        XML.SubElement(policy_element,
                       'dontKeepFailed').text = dont_keep_failed
    elif policy == 'keep-first-failed':
        policy_element = XML.SubElement(root,
                                        'policy',
                                        {'class': 'org.jenkins_ci.plugins.'
                                         'build_keeper.KeepFirstFailedPolicy'})
        XML.SubElement(policy_element, 'numberOfFails').text = str(
            data.get('number-of-fails', 0))
    else:
        InvalidAttributeError('policy', policy, valid_policies)


def live_screenshot(parser, xml_parent, data):
    """yaml: live-screenshot
    Show live screenshots of running jobs in the job list.
    Requires the Jenkins :jenkins-wiki:`Live-Screenshot Plugin
    <LiveScreenshot+Plugin>`.

    :arg str full-size: name of screenshot file (default 'screenshot.png')
    :arg str thumbnail: name of thumbnail file (default 'screenshot-thumb.png')

    File type must be .png and they must be located inside the $WORKDIR.

    Full Example:

    .. literalinclude::
       /../../tests/wrappers/fixtures/live-screenshot-full.yaml

    Minimal Example:

    .. literalinclude::
       /../../tests/wrappers/fixtures/live-screenshot-minimal.yaml
    """
    live = XML.SubElement(
        xml_parent,
        'org.jenkinsci.plugins.livescreenshot.LiveScreenshotBuildWrapper')
    live.set('plugin', 'livescreenshot')
    mapping = [
        ('full-size', 'fullscreenFilename', 'screenshot.png'),
        ('thumbnail', 'thumbnailFilename', 'screenshot-thumb.png'),
    ]
    convert_mapping_to_xml(live, data, mapping, fail_required=True)


def mask_passwords(parser, xml_parent, data):
    """yaml: mask-passwords
    Hide passwords in the console log.
    Requires the Jenkins :jenkins-wiki:`Mask Passwords Plugin
    <Mask+Passwords+Plugin>`.

    Example::

      wrappers:
        - mask-passwords
    """
    XML.SubElement(xml_parent,
                   'com.michelin.cio.hudson.plugins.maskpasswords.'
                   'MaskPasswordsBuildWrapper')


def workspace_cleanup(parser, xml_parent, data):
    """yaml: workspace-cleanup (pre-build)

    Requires the Jenkins :jenkins-wiki:`Workspace Cleanup Plugin
    <Workspace+Cleanup+Plugin>`.

    The post-build workspace-cleanup is available as a publisher.

    :arg list include: list of files to be included
    :arg list exclude: list of files to be excluded
    :arg bool dirmatch: Apply pattern to directories too (default false)
    :arg str check-parameter: boolean environment variable to check to
        determine whether to actually clean up
    :arg str external-deletion-command: external deletion command to run
        against files and directories

    Example:

    .. literalinclude::
        /../../tests/wrappers/fixtures/workspace-cleanup001.yaml
       :language: yaml
    """

    p = XML.SubElement(xml_parent,
                       'hudson.plugins.ws__cleanup.PreBuildCleanup')
    p.set("plugin", "ws-cleanup")
    if "include" in data or "exclude" in data:
        patterns = XML.SubElement(p, 'patterns')

    for inc in data.get("include", []):
        ptrn = XML.SubElement(patterns, 'hudson.plugins.ws__cleanup.Pattern')
        XML.SubElement(ptrn, 'pattern').text = inc
        XML.SubElement(ptrn, 'type').text = "INCLUDE"

    for exc in data.get("exclude", []):
        ptrn = XML.SubElement(patterns, 'hudson.plugins.ws__cleanup.Pattern')
        XML.SubElement(ptrn, 'pattern').text = exc
        XML.SubElement(ptrn, 'type').text = "EXCLUDE"

    deldirs = XML.SubElement(p, 'deleteDirs')
    deldirs.text = str(data.get("dirmatch", False)).lower()

    XML.SubElement(p, 'cleanupParameter').text = str(
        data.get('check-parameter', ''))

    XML.SubElement(p, 'externalDelete').text = str(
        data.get('external-deletion-command', ''))


def m2_repository_cleanup(parser, xml_parent, data):
    """yaml: m2-repository-cleanup
    Configure M2 Repository Cleanup
    Requires the Jenkins :jenkins-wiki:`M2 Repository Cleanup
    <M2+Repository+Cleanup+Plugin>`.

    :arg list patterns: List of patterns for artifacts to cleanup before
                        building. (optional)

    This plugin allows you to configure a maven2 job to clean some or all of
    the artifacts from the repository before it runs.

    Example:

        .. literalinclude:: \
../../tests/wrappers/fixtures/m2-repository-cleanup001.yaml
    """
    m2repo = XML.SubElement(
        xml_parent,
        'hudson.plugins.m2__repo__reaper.M2RepoReaperWrapper')
    m2repo.set("plugin", "m2-repo-reaper")
    patterns = data.get("patterns", [])
    XML.SubElement(m2repo, 'artifactPatterns').text = ",".join(patterns)
    p = XML.SubElement(m2repo, 'patterns')
    for pattern in patterns:
        XML.SubElement(p, 'string').text = pattern


def rvm_env(parser, xml_parent, data):
    """yaml: rvm-env
    Set the RVM implementation
    Requires the Jenkins :jenkins-wiki:`Rvm Plugin <RVM+Plugin>`.

    :arg str implementation: Type of implementation. Syntax is RUBY[@GEMSET],
                             such as '1.9.3' or 'jruby@foo'.

    Example::

      wrappers:
        - rvm-env:
            implementation: 1.9.3
    """
    rpo = XML.SubElement(xml_parent,
                         'ruby-proxy-object')

    ro_class = "Jenkins::Plugin::Proxies::BuildWrapper"
    ro = XML.SubElement(rpo,
                        'ruby-object',
                        {'ruby-class': ro_class,
                         'pluginid': 'rvm'})

    o = XML.SubElement(ro,
                       'object',
                       {'ruby-class': 'RvmWrapper',
                        'pluginid': 'rvm'})

    XML.SubElement(o,
                   'impl',
                   {'pluginid': 'rvm',
                    'ruby-class': 'String'}).text = data['implementation']

    XML.SubElement(ro,
                   'pluginid',
                   {'pluginid': 'rvm',
                    'ruby-class': 'String'}).text = "rvm"


def rbenv(parser, xml_parent, data):
    """yaml: rbenv
    Set the rbenv implementation.
    Requires the Jenkins :jenkins-wiki:`rbenv plugin <rbenv+plugin>`.

    All parameters are optional.

    :arg str ruby-version: Version of Ruby to use  (default 1.9.3-p484)
    :arg bool ignore-local-version: If true, ignore local Ruby
        version (defined in the ".ruby-version" file in workspace) even if it
        has been defined  (default false)
    :arg str preinstall-gem-list: List of gems to install
        (default 'bundler,rake')
    :arg str rbenv-root: RBENV_ROOT  (default $HOME/.rbenv)
    :arg str rbenv-repo: Which repo to clone rbenv from
        (default https://github.com/rbenv/rbenv)
    :arg str rbenv-branch: Which branch to clone rbenv from  (default master)
    :arg str ruby-build-repo: Which repo to clone ruby-build from
        (default https://github.com/rbenv/ruby-build)
    :arg str ruby-build-branch: Which branch to clone ruby-build from
        (default master)

    Example:

    .. literalinclude:: /../../tests/wrappers/fixtures/rbenv003.yaml
    """

    mapping = [
        # option, xml name, default value (text), attributes (hard coded)
        ("preinstall-gem-list", 'gem__list', 'bundler,rake'),
        ("rbenv-root", 'rbenv__root', '$HOME/.rbenv'),
        ("rbenv-repo", 'rbenv__repository',
            'https://github.com/rbenv/rbenv'),
        ("rbenv-branch", 'rbenv__revision', 'master'),
        ("ruby-build-repo", 'ruby__build__repository',
            'https://github.com/rbenv/ruby-build'),
        ("ruby-build-branch", 'ruby__build__revision', 'master'),
        ("ruby-version", 'version', '1.9.3-p484'),
    ]

    rpo = XML.SubElement(xml_parent,
                         'ruby-proxy-object')

    ro_class = "Jenkins::Tasks::BuildWrapperProxy"
    ro = XML.SubElement(rpo,
                        'ruby-object',
                        {'ruby-class': ro_class,
                         'pluginid': 'rbenv'})

    XML.SubElement(ro,
                   'pluginid',
                   {'pluginid': "rbenv",
                    'ruby-class': "String"}).text = "rbenv"

    o = XML.SubElement(ro,
                       'object',
                       {'ruby-class': 'RbenvWrapper',
                        'pluginid': 'rbenv'})

    for elem in mapping:
        (optname, xmlname, val) = elem[:3]
        xe = XML.SubElement(o,
                            xmlname,
                            {'ruby-class': "String",
                             'pluginid': "rbenv"})
        if optname and optname in data:
            val = data[optname]
        if type(val) == bool:
            xe.text = str(val).lower()
        else:
            xe.text = val

    ignore_local_class = 'FalseClass'

    if 'ignore-local-version' in data:
        ignore_local_string = str(data['ignore-local-version']).lower()
        if ignore_local_string == 'true':
            ignore_local_class = 'TrueClass'

    XML.SubElement(o,
                   'ignore__local__version',
                   {'ruby-class': ignore_local_class,
                    'pluginid': 'rbenv'})


def build_name(parser, xml_parent, data):
    """yaml: build-name
    Set the name of the build
    Requires the Jenkins :jenkins-wiki:`Build Name Setter Plugin
    <Build+Name+Setter+Plugin>`.

    :arg str name: Name for the build.  Typically you would use a variable
                   from Jenkins in the name.  The syntax would be ${FOO} for
                   the FOO variable.

    Example::

      wrappers:
        - build-name:
            name: Build-${FOO}
    """
    bsetter = XML.SubElement(xml_parent,
                             'org.jenkinsci.plugins.buildnamesetter.'
                             'BuildNameSetter')
    XML.SubElement(bsetter, 'template').text = data['name']


def port_allocator(parser, xml_parent, data):
    """yaml: port-allocator
    Assign unique TCP port numbers
    Requires the Jenkins :jenkins-wiki:`Port Allocator Plugin
    <Port+Allocator+Plugin>`.

    :arg str name: Deprecated, use names instead
    :arg list names: Variable list of names of the port or list of
        specific port numbers

    Example:

    .. literalinclude::  /../../tests/wrappers/fixtures/port-allocator002.yaml
    """
    pa = XML.SubElement(xml_parent,
                        'org.jvnet.hudson.plugins.port__allocator.'
                        'PortAllocator')
    ports = XML.SubElement(pa, 'ports')
    names = data.get('names')
    if not names:
        logger = logging.getLogger(__name__)
        logger.warn('port_allocator name is deprecated, use a names list '
                    ' instead')
        names = [data['name']]
    for name in names:
        dpt = XML.SubElement(ports,
                             'org.jvnet.hudson.plugins.port__allocator.'
                             'DefaultPortType')
        XML.SubElement(dpt, 'name').text = name


def locks(parser, xml_parent, data):
    """yaml: locks
    Control parallel execution of jobs.
    Requires the Jenkins :jenkins-wiki:`Locks and Latches Plugin
    <Locks+and+Latches+plugin>`.

    :arg: list of locks to use

    Example:

    .. literalinclude::  /../../tests/wrappers/fixtures/locks002.yaml
       :language: yaml
    """
    locks = data
    if locks:
        lw = XML.SubElement(xml_parent,
                            'hudson.plugins.locksandlatches.LockWrapper')
        locktop = XML.SubElement(lw, 'locks')
        for lock in locks:
            lockwrapper = XML.SubElement(locktop,
                                         'hudson.plugins.locksandlatches.'
                                         'LockWrapper_-LockWaitConfig')
            XML.SubElement(lockwrapper, 'name').text = lock


def copy_to_slave(parser, xml_parent, data):
    """yaml: copy-to-slave
    Copy files to slave before build
    Requires the Jenkins :jenkins-wiki:`Copy To Slave Plugin
    <Copy+To+Slave+Plugin>`.

    :arg list includes: list of file patterns to copy (optional)
    :arg list excludes: list of file patterns to exclude (optional)
    :arg bool flatten: flatten directory structure (default false)
    :arg str relative-to: base location of includes/excludes, must be home
        ($JENKINS_HOME), somewhereElse ($JENKINS_HOME/copyToSlave),
        userContent ($JENKINS_HOME/userContent) or workspace
        (default userContent)
    :arg bool include-ant-excludes: exclude ant's default excludes
        (default false)

    Minimal Example:

    .. literalinclude::  /../../tests/wrappers/fixtures/copy-to-slave001.yaml
       :language: yaml

    Full Example:

    .. literalinclude::  /../../tests/wrappers/fixtures/copy-to-slave002.yaml
       :language: yaml
    """
    p = 'com.michelin.cio.hudson.plugins.copytoslave.CopyToSlaveBuildWrapper'
    cs = XML.SubElement(xml_parent, p)

    XML.SubElement(cs, 'includes').text = ','.join(data.get('includes', ['']))
    XML.SubElement(cs, 'excludes').text = ','.join(data.get('excludes', ['']))
    XML.SubElement(cs, 'flatten').text = \
        str(data.get('flatten', False)).lower()
    XML.SubElement(cs, 'includeAntExcludes').text = \
        str(data.get('include-ant-excludes', False)).lower()

    rel = str(data.get('relative-to', 'userContent'))
    opt = ('home', 'somewhereElse', 'userContent', 'workspace')
    if rel not in opt:
        raise ValueError('relative-to must be one of %r' % opt)
    XML.SubElement(cs, 'relativeTo').text = rel

    # seems to always be false, can't find it in source code
    XML.SubElement(cs, 'hudsonHomeRelative').text = 'false'


def inject(parser, xml_parent, data):
    """yaml: inject
    Add or override environment variables to the whole build process
    Requires the Jenkins :jenkins-wiki:`EnvInject Plugin <EnvInject+Plugin>`.

    :arg str properties-file: path to the properties file (default '')
    :arg str properties-content: key value pair of properties (default '')
    :arg str script-file: path to the script file (default '')
    :arg str script-content: contents of a script (default '')

    Example::

      wrappers:
        - inject:
            properties-file: /usr/local/foo
            properties-content: PATH=/foo/bar
            script-file: /usr/local/foo.sh
            script-content: echo $PATH
    """
    eib = XML.SubElement(xml_parent, 'EnvInjectBuildWrapper')
    info = XML.SubElement(eib, 'info')
    jenkins_jobs.modules.base.add_nonblank_xml_subelement(
        info, 'propertiesFilePath', data.get('properties-file'))
    jenkins_jobs.modules.base.add_nonblank_xml_subelement(
        info, 'propertiesContent', data.get('properties-content'))
    jenkins_jobs.modules.base.add_nonblank_xml_subelement(
        info, 'scriptFilePath', data.get('script-file'))
    jenkins_jobs.modules.base.add_nonblank_xml_subelement(
        info, 'scriptContent', data.get('script-content'))
    XML.SubElement(info, 'loadFilesFromMaster').text = 'false'


def inject_ownership_variables(parser, xml_parent, data):
    """yaml: inject-ownership-variables
    Inject ownership variables to the build as environment variables.
    Requires the Jenkins :jenkins-wiki:`EnvInject Plugin <EnvInject+Plugin>`
    and Jenkins :jenkins-wiki:`Ownership plugin <Ownership+Plugin>`.

    :arg bool job-variables: inject job ownership variables to the job
        (default false)
    :arg bool node-variables: inject node ownership variables to the job
        (default false)

    Example:

    .. literalinclude:: /../../tests/wrappers/fixtures/ownership001.yaml

    """
    ownership = XML.SubElement(xml_parent, 'com.synopsys.arc.jenkins.plugins.'
                               'ownership.wrappers.OwnershipBuildWrapper')
    XML.SubElement(ownership, 'injectNodeOwnership').text = \
        str(data.get('node-variables', False)).lower()
    XML.SubElement(ownership, 'injectJobOwnership').text = \
        str(data.get('job-variables', False)).lower()


def inject_passwords(parser, xml_parent, data):
    """yaml: inject-passwords
    Inject passwords to the build as environment variables.
    Requires the Jenkins :jenkins-wiki:`EnvInject Plugin <EnvInject+Plugin>`.

    :arg bool global: inject global passwords to the job
    :arg bool mask-password-params: mask passsword parameters
    :arg list job-passwords: key value pair of job passwords

        :Parameter: * **name** (`str`) Name of password
                    * **password** (`str`) Encrypted password

    Example:

    .. literalinclude:: /../../tests/wrappers/fixtures/passwords001.yaml

    """
    eib = XML.SubElement(xml_parent, 'EnvInjectPasswordWrapper')
    XML.SubElement(eib, 'injectGlobalPasswords').text = \
        str(data.get('global', False)).lower()
    XML.SubElement(eib, 'maskPasswordParameters').text = \
        str(data.get('mask-password-params', False)).lower()
    entries = XML.SubElement(eib, 'passwordEntries')
    passwords = data.get('job-passwords', [])
    if passwords:
        for password in passwords:
            entry = XML.SubElement(entries, 'EnvInjectPasswordEntry')
            XML.SubElement(entry, 'name').text = password['name']
            XML.SubElement(entry, 'value').text = password['password']


def env_file(parser, xml_parent, data):
    """yaml: env-file
    Add or override environment variables to the whole build process
    Requires the Jenkins :jenkins-wiki:`Environment File Plugin
    <Envfile+Plugin>`.

    :arg str properties-file: path to the properties file (default '')

    Example::

      wrappers:
        - env-file:
            properties-file: ${WORKSPACE}/foo
    """
    eib = XML.SubElement(xml_parent,
                         'hudson.plugins.envfile.EnvFileBuildWrapper')
    jenkins_jobs.modules.base.add_nonblank_xml_subelement(
        eib, 'filePath', data.get('properties-file'))


def env_script(parser, xml_parent, data):
    """yaml: env-script
    Add or override environment variables to the whole build process.
    Requires the Jenkins :jenkins-wiki:`Environment Script Plugin
    <Environment+Script+Plugin>`.

    :arg script-content: The script to run (default '')
    :arg str script-type: The script type.

        :script-types supported:
            * **unix-script** (default)
            * **power-shell**
            * **batch-script**
    :arg only-run-on-parent: Only applicable for Matrix Jobs. If true, run only
      on the matrix parent job (default false)

    Example:

    .. literalinclude:: /../../tests/wrappers/fixtures/env-script001.yaml

    """
    el = XML.SubElement(xml_parent, 'com.lookout.jenkins.EnvironmentScript')
    XML.SubElement(el, 'script').text = data.get('script-content', '')

    valid_script_types = {
        'unix-script': 'unixScript',
        'power-shell': 'powerShell',
        'batch-script': 'batchScript',
    }
    script_type = data.get('script-type', 'unix-script')
    if script_type not in valid_script_types:
        raise InvalidAttributeError('script-type', script_type,
                                    valid_script_types)
    XML.SubElement(el, 'scriptType').text = valid_script_types[script_type]

    only_on_parent = str(data.get('only-run-on-parent', False)).lower()
    XML.SubElement(el, 'onlyRunOnParent').text = only_on_parent


def jclouds(parser, xml_parent, data):
    """yaml: jclouds
    Uses JClouds to provide slave launching on most of the currently
    usable Cloud infrastructures.
    Requires the Jenkins :jenkins-wiki:`JClouds Plugin <JClouds+Plugin>`.

    :arg bool single-use: Whether or not to terminate the slave after use
                          (default false).
    :arg list instances: The name of the jclouds template to create an
                         instance from, and its parameters.
    :arg str cloud-name: The name of the jclouds profile containing the
                         specified template.
    :arg int count: How many instances to create (default 1).
    :arg bool stop-on-terminate: Whether or not to suspend instead of terminate
                                 the instance (default false).

    Example::

      wrappers:
        - jclouds:
            single-use: True
            instances:
              - jenkins-dev-slave:
                  cloud-name: mycloud1
                  count: 1
                  stop-on-terminate: True
              - jenkins-test-slave:
                  cloud-name: mycloud2
                  count: 2
                  stop-on-terminate: False
    """
    buildWrapper = XML.SubElement(xml_parent,
                                  'jenkins.plugins.jclouds.compute.'
                                  'JCloudsBuildWrapper')
    instances = XML.SubElement(buildWrapper, 'instancesToRun')
    if 'instances' in data:
        for foo in data['instances']:
            for template, params in foo.items():
                instance = XML.SubElement(instances,
                                          'jenkins.plugins.jclouds.compute.'
                                          'InstancesToRun')
                XML.SubElement(instance, 'templateName').text = template
                XML.SubElement(instance, 'cloudName').text = \
                    params.get('cloud-name', '')
                XML.SubElement(instance, 'count').text = \
                    str(params.get('count', 1))
                XML.SubElement(instance, 'suspendOrTerminate').text = \
                    str(params.get('stop-on-terminate', False)).lower()
    if data.get('single-use'):
        XML.SubElement(xml_parent,
                       'jenkins.plugins.jclouds.compute.'
                       'JCloudsOneOffSlave')


def openstack(parser, xml_parent, data):
    """yaml: openstack
    Provision slaves from OpenStack on demand.  Requires the Jenkins
    :jenkins-wiki:`Openstack Cloud Plugin <Openstack+Cloud+Plugin>`.

    :arg list instances: List of instances to be launched at the beginning of
        the build.

        :instances:
            * **cloud-name** (`str`) -- The name of the cloud profile which
              contains the specified cloud instance template (required).
            * **template-name** (`str`) -- The name of the cloud instance
              template to create an instance from(required).
            * **manual-template** (`bool`) -- If True, instance template name
              will be put in 'Specify Template Name as String' option. Not
              specifying or specifying False, instance template name will be
              put in 'Select Template from List' option. To use parameter
              replacement, set this to True.  (default false)
            * **count** (`int`) -- How many instances to create (default 1).

    :arg bool single-use: Whether or not to terminate the slave after use
        (default false).

    Example:

    .. literalinclude:: /../../tests/wrappers/fixtures/openstack001.yaml
    """
    tag_prefix = 'jenkins.plugins.openstack.compute.'

    if 'instances' in data:
        clouds_build_wrapper = XML.SubElement(
            xml_parent, tag_prefix + 'JCloudsBuildWrapper')
        instances_wrapper = XML.SubElement(
            clouds_build_wrapper, 'instancesToRun')

        for instance in data['instances']:
            instances_to_run = XML.SubElement(
                instances_wrapper, tag_prefix + 'InstancesToRun')

            try:
                cloud_name = instance['cloud-name']
                template_name = instance['template-name']
            except KeyError as exception:
                raise MissingAttributeError(exception.args[0])

            XML.SubElement(instances_to_run, 'cloudName').text = cloud_name

            if instance.get('manual-template', False):
                XML.SubElement(instances_to_run,
                               'manualTemplateName').text = template_name
            else:
                XML.SubElement(instances_to_run,
                               'templateName').text = template_name

            XML.SubElement(instances_to_run, 'count').text = str(
                instance.get('count', 1))

    if data.get('single-use', False):
        XML.SubElement(xml_parent, tag_prefix + 'JCloudsOneOffSlave')


def build_user_vars(parser, xml_parent, data):
    """yaml: build-user-vars
    Set environment variables to the value of the user that started the build.
    Requires the Jenkins :jenkins-wiki:`Build User Vars Plugin
    <Build+User+Vars+Plugin>`.

    Example::

      wrappers:
        - build-user-vars
    """
    XML.SubElement(xml_parent, 'org.jenkinsci.plugins.builduser.BuildUser')


def release(parser, xml_parent, data):
    """yaml: release
    Add release build configuration
    Requires the Jenkins :jenkins-wiki:`Release Plugin <Release+Plugin>`.

    :arg bool keep-forever: Keep build forever (default true)
    :arg bool override-build-parameters: Enable build-parameter override
        (default false)
    :arg string version-template: Release version template (default '')
    :arg list parameters: Release parameters (see the :ref:`Parameters` module)
    :arg list pre-build: Pre-build steps (see the :ref:`Builders` module)
    :arg list post-build: Post-build steps (see :ref:`Builders`)
    :arg list post-success: Post successful-build steps (see :ref:`Builders`)
    :arg list post-failed: Post failed-build steps (see :ref:`Builders`)

    Example:

    .. literalinclude:: /../../tests/wrappers/fixtures/release001.yaml

    """
    relwrap = XML.SubElement(xml_parent,
                             'hudson.plugins.release.ReleaseWrapper')
    # For 'keep-forever', the sense of the XML flag is the opposite of
    # the YAML flag.
    no_keep_forever = 'false'
    if str(data.get('keep-forever', True)).lower() == 'false':
        no_keep_forever = 'true'
    XML.SubElement(relwrap, 'doNotKeepLog').text = no_keep_forever
    XML.SubElement(relwrap, 'overrideBuildParameters').text = str(
        data.get('override-build-parameters', False)).lower()
    XML.SubElement(relwrap, 'releaseVersionTemplate').text = data.get(
        'version-template', '')
    parameters = data.get('parameters', [])
    if parameters:
        pdef = XML.SubElement(relwrap, 'parameterDefinitions')
        for param in parameters:
            parser.registry.dispatch('parameter', parser, pdef, param)

    builder_steps = {
        'pre-build': 'preBuildSteps',
        'post-build': 'postBuildSteps',
        'post-success': 'postSuccessfulBuildSteps',
        'post-fail': 'postFailedBuildSteps',
    }
    for step in builder_steps.keys():
        for builder in data.get(step, []):
            parser.registry.dispatch('builder', parser,
                                     XML.SubElement(relwrap,
                                                    builder_steps[step]),
                                     builder)


def sauce_ondemand(parser, xml_parent, data):
    """yaml: sauce-ondemand
    Allows you to integrate Sauce OnDemand with Jenkins.  You can
    automate the setup and tear down of Sauce Connect and integrate
    the Sauce OnDemand results videos per test. Requires the Jenkins
    :jenkins-wiki:`Sauce OnDemand Plugin <Sauce+OnDemand+Plugin>`.

    :arg bool enable-sauce-connect: launches a SSH tunnel from their cloud
        to your private network (default false)
    :arg str sauce-host: The name of the selenium host to be used.  For
        tests run using Sauce Connect, this should be localhost.
        ondemand.saucelabs.com can also be used to conenct directly to
        Sauce OnDemand,  The value of the host will be stored in the
        SAUCE_ONDEMAND_HOST environment variable.  (default '')