summaryrefslogtreecommitdiffstats
path: root/test
diff options
context:
space:
mode:
Diffstat (limited to 'test')
-rwxr-xr-xtest/network/server/mongrel_test.rb25
1 files changed, 23 insertions, 2 deletions
diff --git a/test/network/server/mongrel_test.rb b/test/network/server/mongrel_test.rb
index 75568561b..b7a383872 100755
--- a/test/network/server/mongrel_test.rb
+++ b/test/network/server/mongrel_test.rb
@@ -3,6 +3,7 @@
$:.unshift("../../lib") if __FILE__ =~ /\.rb$/
require 'puppettest'
+require 'mocha'
class TestMongrelServer < PuppetTest::TestCase
confine "Missing mongrel" => Puppet.features.mongrel?
@@ -25,14 +26,34 @@ class TestMongrelServer < PuppetTest::TestCase
ip = Facter.value(:ipaddress)
params["REMOTE_ADDR"] = ip
+ params[Puppet[:ssl_client_header]] = ""
+ params[Puppet[:ssl_client_verify_header]] = "failure"
+ info = nil
+ Resolv.expects(:getname).with(ip).returns("host.domain.com").times(3)
+ assert_nothing_raised("Could not call client_info") do
+ info = mongrel.send(:client_info, obj)
+ end
+ assert(! info.authenticated?, "Client info object was marked valid even though headers were missing")
+ assert_equal(ip, info.ip, "Did not copy over ip correctly")
+
+ assert_equal("host.domain.com", info.name, "Did not copy over hostname correctly")
+
+ # Now add a valid auth header.
params[Puppet[:ssl_client_header]] = "/CN=host.domain.com"
+ assert_nothing_raised("Could not call client_info") do
+ info = mongrel.send(:client_info, obj)
+ end
+ assert(! info.authenticated?, "Client info object was marked valid even though the verify header was fals")
+ assert_equal(ip, info.ip, "Did not copy over ip correctly")
+ assert_equal("host.domain.com", info.name, "Did not copy over hostname correctly")
- info = nil
+ # Now change the verify header to be true
+ params[Puppet[:ssl_client_verify_header]] = "SUCCESS"
assert_nothing_raised("Could not call client_info") do
info = mongrel.send(:client_info, obj)
end
- assert(info.authenticated?, "Client info object was not marked valid even though the header was present")
+ assert(info.authenticated?, "Client info object was not marked valid even though all headers were correct")
assert_equal(ip, info.ip, "Did not copy over ip correctly")
assert_equal("host.domain.com", info.name, "Did not copy over hostname correctly")
> 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 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
# 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.


"""
Triggers define what causes a Jenkins job to start building.

**Component**: triggers
  :Macro: trigger
  :Entry Point: jenkins_jobs.triggers

Example::

  job:
    name: test_job

    triggers:
      - timed: '@daily'
"""

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

import six

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 import hudson_model
import jenkins_jobs.modules.helpers as helpers

logger = logging.getLogger(str(__name__))


def gerrit_handle_legacy_configuration(data):
    hyphenizer = re.compile("[A-Z]")

    def hyphenize(attr):
        """Convert strings like triggerOn to trigger-on.
        """
        return hyphenizer.sub(lambda x: "-%s" % x.group(0).lower(),
                              attr)

    def convert_dict(d, old_keys):
        for old_key in old_keys:
            if old_key in d:
                new_key = hyphenize(old_key)
                logger.warning(
                    "'%s' is deprecated and will be removed after "
                    "1.0.0, please use '%s' instead", old_key, new_key)
                d[new_key] = d[old_key]
                del d[old_key]

    convert_dict(data, [
        'triggerOnPatchsetUploadedEvent',
        'triggerOnChangeAbandonedEvent',
        'triggerOnChangeMergedEvent',
        'triggerOnChangeRestoredEvent',
        'triggerOnCommentAddedEvent',
        'triggerOnDraftPublishedEvent',
        'triggerOnRefUpdatedEvent',
        'triggerApprovalCategory',
        'triggerApprovalValue',
        'overrideVotes',
        'gerritBuildSuccessfulVerifiedValue',
        'gerritBuildFailedVerifiedValue',
        'failureMessage',
        'skipVote',
    ])

    for project in data.get('projects', []):
        convert_dict(project, [
            'projectCompareType',
            'projectPattern',
            'branchCompareType',
            'branchPattern',
        ])

    mapping_obj_type = type(data)

    old_format_events = mapping_obj_type(
        (key, should_register) for key, should_register in six.iteritems(data)
        if key.startswith('trigger-on-'))
    trigger_on = data.setdefault('trigger-on', [])
    if old_format_events:
        logger.warning(
            "The events: %s; which you used is/are deprecated. "
            "Please use 'trigger-on' instead.",
            ', '.join(old_format_events))

    if old_format_events and trigger_on:
        raise JenkinsJobsException(
            'Both, the new format (trigger-on) and old format (trigger-on-*) '
            'gerrit events format found. Please use either the new or the old '
            'format of trigger events definition.')

    trigger_on.extend(event_name[len('trigger-on-'):]
                      for event_name, should_register
                      in six.iteritems(old_format_events) if should_register)

    for idx, event in enumerate(trigger_on):
        if event == 'comment-added-event':
            trigger_on[idx] = events = mapping_obj_type()
            try:
                events['comment-added-event'] = mapping_obj_type((
                    ('approval-category', data['trigger-approval-category']),
                    ('approval-value', data['trigger-approval-value'])
                ))
            except KeyError:
                raise JenkinsJobsException(
                    'The comment-added-event trigger requires which approval '
                    'category and value you want to trigger the job. '
                    'It should be specified by the approval-category '
                    'and approval-value properties.')


def build_gerrit_triggers(xml_parent, data):
    available_simple_triggers = {
        'change-abandoned-event': 'PluginChangeAbandonedEvent',
        'change-merged-event': 'PluginChangeMergedEvent',
        'change-restored-event': 'PluginChangeRestoredEvent',
        'draft-published-event': 'PluginDraftPublishedEvent',
        'patchset-uploaded-event': 'PluginPatchsetCreatedEvent',
        'patchset-created-event': 'PluginPatchsetCreatedEvent',
        'ref-updated-event': 'PluginRefUpdatedEvent',
    }
    tag_namespace = 'com.sonyericsson.hudson.plugins.gerrit.trigger.'   \
        'hudsontrigger.events'

    trigger_on_events = XML.SubElement(xml_parent, 'triggerOnEvents')

    for event in data.get('trigger-on', []):
        if isinstance(event, six.string_types):
            tag_name = available_simple_triggers.get(event)
            if event == 'patchset-uploaded-event':
                logger.warning(
                    "'%s' is deprecated. Use 'patchset-created-event' "
                    "format instead.", event)

            if not tag_name:
                known = ', '.join(available_simple_triggers.keys() +
                                  ['comment-added-event',
                                   'comment-added-contains-event'])
                msg = ("The event '%s' under 'trigger-on' is not one of the "
                       "known: %s.") % (event, known)
                raise JenkinsJobsException(msg)
            XML.SubElement(trigger_on_events,
                           '%s.%s' % (tag_namespace, tag_name))
        else:
            if 'patchset-created-event' in event.keys():
                pce = event['patchset-created-event']
                pc = XML.SubElement(
                    trigger_on_events,
                    '%s.%s' % (tag_namespace, 'PluginPatchsetCreatedEvent'))
                mapping = [
                    ('exclude-drafts', 'excludeDrafts', False),
                    ('exclude-trivial-rebase', 'excludeTrivialRebase', False),
                    ('exclude-no-code-change', 'excludeNoCodeChange', False),
                ]
                helpers.convert_mapping_to_xml(
                    pc, pce, mapping, fail_required=True)

            if 'comment-added-event' in event.keys():
                comment_added_event = event['comment-added-event']
                cadded = XML.SubElement(
                    trigger_on_events,
                    '%s.%s' % (tag_namespace, 'PluginCommentAddedEvent'))
                mapping = [
                    ('approval-category', 'verdictCategory', None),
                    ('approval-value',
                        'commentAddedTriggerApprovalValue', None),
                ]
                helpers.convert_mapping_to_xml(cadded,
                    comment_added_event, mapping, fail_required=True)

            if 'comment-added-contains-event' in event.keys():
                comment_added_event = event['comment-added-contains-event']
                caddedc = XML.SubElement(
                    trigger_on_events,
                    '%s.%s' % (tag_namespace,
                               'PluginCommentAddedContainsEvent'))
                XML.SubElement(caddedc, 'commentAddedCommentContains').text = \
                    comment_added_event['comment-contains-value']


def build_gerrit_skip_votes(xml_parent, data):
    outcomes = [('successful', 'onSuccessful'),
                ('failed', 'onFailed'),
                ('unstable', 'onUnstable'),
                ('notbuilt', 'onNotBuilt')]

    skip_vote_node = XML.SubElement(xml_parent, 'skipVote')
    skip_vote = data.get('skip-vote', {})
    for result_kind, tag_name in outcomes:
        setting = skip_vote.get(result_kind, False)
        XML.SubElement(skip_vote_node, tag_name).text = str(setting).lower()


def gerrit(registry, xml_parent, data):
    """yaml: gerrit

    Trigger on a Gerrit event.
    Requires the Jenkins :jenkins-wiki:`Gerrit Trigger Plugin <Gerrit+Trigger>`
    version >= 2.6.0.

    :arg list trigger-on: Events to react on. Please use either the new
      **trigger-on**, or the old **trigger-on-*** events definitions. You
      cannot use both at once.

      .. _trigger_on:

      :Trigger on:

         * **patchset-created-event** (`dict`) -- Trigger upon patchset
           creation.

           :Patchset created:
               * **exclude-drafts** (`bool`) -- exclude drafts (default false)
               * **exclude-trivial-rebase** (`bool`) -- exclude trivial rebase
                 (default false)
               * **exclude-no-code-change** (`bool`) -- exclude no code change
                 (default false)

           Exclude drafts|trivial-rebase|no-code-change needs
           Gerrit Trigger v2.12.0

         * **patchset-uploaded-event** -- Trigger upon patchset creation
           (this is a alias for `patchset-created-event`).

           .. deprecated:: 1.1.0  Please use :ref:`trigger-on <trigger_on>`.

         * **change-abandoned-event** -- Trigger on patchset abandoned.
           Requires Gerrit Trigger Plugin version >= 2.8.0.
         * **change-merged-event** -- Trigger on change merged
         * **change-restored-event** -- Trigger on change restored. Requires
           Gerrit Trigger Plugin version >= 2.8.0
         * **draft-published-event** -- Trigger on draft published event.
         * **ref-updated-event** -- Trigger on ref-updated.
         * **comment-added-event** (`dict`) -- Trigger on comment added.

           :Comment added:
               * **approval-category** (`str`) -- Approval (verdict) category
                 (for example 'APRV', 'CRVW', 'VRIF' -- see `Gerrit access
                 control
                 <http://gerrit.googlecode.com/svn/documentation/2.1/
                 access-control.html#categories>`_

               * **approval-value** -- Approval value for the comment added.
         * **comment-added-contains-event** (`dict`) -- Trigger on comment
           added contains Regular Expression.

           :Comment added contains:
               * **comment-contains-value** (`str`) -- Comment contains
                 Regular Expression value.

    :arg bool trigger-on-patchset-uploaded-event: Trigger on patchset upload.

        .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.

    :arg bool trigger-on-change-abandoned-event: Trigger on change abandoned.
        Requires Gerrit Trigger Plugin version >= 2.8.0

        .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.

    :arg bool trigger-on-change-merged-event: Trigger on change merged

        .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.

    :arg bool trigger-on-change-restored-event: Trigger on change restored.
        Requires Gerrit Trigger Plugin version >= 2.8.0

        .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.

    :arg bool trigger-on-comment-added-event: Trigger on comment added

        .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.

    :arg bool trigger-on-draft-published-event: Trigger on draft published
        event

        .. deprecated:: 1.1.0  Please use :ref:`trigger-on <trigger_on>`.

    :arg bool trigger-on-ref-updated-event: Trigger on ref-updated

        .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.

    :arg str trigger-approval-category: Approval category for comment added

        .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.

    :arg int trigger-approval-value: Approval value for comment added

        .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.

    :arg bool override-votes: Override default vote values
    :arg int gerrit-build-started-verified-value: Started ''Verified'' value
    :arg int gerrit-build-successful-verified-value: Successful ''Verified''
        value
    :arg int gerrit-build-failed-verified-value: Failed ''Verified'' value
    :arg int gerrit-build-unstable-verified-value: Unstable ''Verified'' value
    :arg int gerrit-build-notbuilt-verified-value: Not built ''Verified''
        value
    :arg int gerrit-build-started-codereview-value: Started ''CodeReview''
        value
    :arg int gerrit-build-successful-codereview-value: Successful
        ''CodeReview'' value
    :arg int gerrit-build-failed-codereview-value: Failed ''CodeReview'' value
    :arg int gerrit-build-unstable-codereview-value: Unstable ''CodeReview''
        value
    :arg int gerrit-build-notbuilt-codereview-value: Not built ''CodeReview''
        value
    :arg str failure-message: Message to leave on failure (default '')
    :arg str successful-message: Message to leave on success (default '')
    :arg str unstable-message: Message to leave when unstable (default '')
    :arg str notbuilt-message: Message to leave when not built (default '')
    :arg str failure-message-file: Sets the filename within the workspace from
        which to retrieve the unsuccessful review message. (optional)
    :arg list projects: list of projects to match

      :Project: * **project-compare-type** (`str`) --  ''PLAIN'', ''ANT'' or
                  ''REG_EXP''
                * **project-pattern** (`str`) -- Project name pattern to match
                * **branch-compare-type** (`str`) -- ''PLAIN'', ''ANT'' or
                  ''REG_EXP'' (not used if `branches` list is specified)

                  .. deprecated:: 1.1.0  Please use :ref:`branches <branches>`.

                * **branch-pattern** (`str`) -- Branch name pattern to match
                  (not used if `branches` list is specified)

                  .. deprecated:: 1.1.0  Please use :ref:`branches <branches>`.

                .. _branches:

                * **branches** (`list`) -- List of branches to match
                  (optional)

                  :Branch: * **branch-compare-type** (`str`) -- ''PLAIN'',
                             ''ANT'' or ''REG_EXP'' (optional) (default
                             ''PLAIN'')
                           * **branch-pattern** (`str`) -- Branch name pattern
                             to match

                * **file-paths** (`list`) -- List of file paths to match
                  (optional)

                  :File Path: * **compare-type** (`str`) -- ''PLAIN'', ''ANT''
                                or ''REG_EXP'' (optional) (default ''PLAIN'')
                              * **pattern** (`str`) -- File path pattern to
                                match

                * **forbidden-file-paths** (`list`) -- List of file paths to
                  skip triggering (optional)

                  :Forbidden File Path: * **compare-type** (`str`) --
                                ''PLAIN'', ''ANT'' or ''REG_EXP'' (optional)
                                (default ''PLAIN'')
                              * **pattern** (`str`) -- File path pattern to
                                match

                * **topics** (`list`) -- List of topics to match
                  (optional)

                  :Topic: * **compare-type** (`str`) -- ''PLAIN'', ''ANT'' or
                            ''REG_EXP'' (optional) (default ''PLAIN'')
                          * **pattern** (`str`) -- Topic name pattern to
                            match

                * **disable-strict-forbidden-file-verification** (`bool`) --
                      Enabling this option will allow an event to trigger a
                      build if the event contains BOTH one or more wanted file
                      paths AND one or more forbidden file paths.  In other
                      words, with this option, the build will not get
                      triggered if the change contains only forbidden files,
                      otherwise it will get triggered. Requires plugin
                      version >= 2.16.0 (default false)

    :arg dict skip-vote: map of build outcomes for which Jenkins must skip
        vote. Requires Gerrit Trigger Plugin version >= 2.7.0

        :Outcome: * **successful** (`bool`)
                  * **failed** (`bool`)
                  * **unstable** (`bool`)
                  * **notbuilt** (`bool`)

    :arg bool silent:  When silent mode is on there will be no communication
        back to Gerrit, i.e. no build started/failed/successful approve
        messages etc. If other non-silent jobs are triggered by the same
        Gerrit event as this job, the result of this job's build will not be
        counted in the end result of the other jobs. (default false)
    :arg bool silent-start: Sets silent start mode to on or off. When silent
        start mode is on there will be no 'build started' messages sent back
        to Gerrit. (default false)
    :arg bool escape-quotes: escape quotes in the values of Gerrit change
        parameters (default true)
    :arg bool no-name-and-email: Do not pass compound 'name and email'
        parameters (default false)
    :arg bool readable-message: If parameters regarding multiline text,
        e.g. commit message, should be as human readable or not. If false,
        those parameters are Base64 encoded to keep environment variables
        clean. (default false)
    :arg str dependency-jobs: All jobs on which this job depends. If a commit
        should trigger both a dependency and this job, the dependency will be
        built first. Use commas to separate job names. Beware of cyclic
        dependencies. (optional)
    :arg str notification-level: Defines to whom email notifications should be
        sent. This can either be nobody ('NONE'), the change owner ('OWNER'),
        reviewers and change owner ('OWNER_REVIEWERS'), all interested users
        i.e. owning, reviewing, watching, and starring ('ALL') or server
        default ('SERVER_DEFAULT'). (default 'SERVER_DEFAULT')
    :arg bool dynamic-trigger-enabled: Enable/disable the dynamic trigger
        (default false)
    :arg str dynamic-trigger-url: if you specify this option, the Gerrit
        trigger configuration will be fetched from there on a regular interval
    :arg bool trigger-for-unreviewed-patches: trigger patchset-created events
        for changes that were uploaded while connection to Gerrit was down
        (default false). Requires Gerrit Trigger Plugin version >= 2.11.0
    :arg str custom-url: Custom URL for a message sent to Gerrit. Build
        details URL will be used if empty. (default '')
    :arg str server-name: Name of the server to trigger on, or ''__ANY__'' to
        trigger on any configured Gerrit server (default '__ANY__'). Requires
        Gerrit Trigger Plugin version >= 2.11.0

    You may select one or more Gerrit events upon which to trigger.
    You must also supply at least one project and branch, optionally
    more.  If you select the comment-added trigger, you should also
    indicate which approval category and value you want to trigger the
    job.

    Until version 0.4.0 of Jenkins Job Builder, camelCase keys were used to
    configure Gerrit Trigger Plugin, instead of hyphenated-keys.  While still
    supported, camedCase keys are deprecated and should not be used. Support
    for this will be removed after 1.0.0 is released.

    Example:

    .. literalinclude:: /../../tests/triggers/fixtures/gerrit004.yaml
       :language: yaml

    """

    def get_compare_type(xml_tag, compare_type):
        valid_compare_types = ['PLAIN',
                               'ANT',
                               'REG_EXP']

        if compare_type not in valid_compare_types:
            raise InvalidAttributeError(xml_tag, compare_type,
                                        valid_compare_types)
        return compare_type

    gerrit_handle_legacy_configuration(data)

    projects = data.get('projects', [])
    gtrig = XML.SubElement(xml_parent,
                           'com.sonyericsson.hudson.plugins.gerrit.trigger.'
                           'hudsontrigger.GerritTrigger')
    XML.SubElement(gtrig, 'spec')
    gprojects = XML.SubElement(gtrig, 'gerritProjects')
    for project in projects:
        gproj = XML.SubElement(gprojects,
                               'com.sonyericsson.hudson.plugins.gerrit.'
                               'trigger.hudsontrigger.data.GerritProject')
        XML.SubElement(gproj, 'compareType').text = get_compare_type(
            'project-compare-type', project.get(
                'project-compare-type', 'PLAIN'))
        XML.SubElement(gproj, 'pattern').text = project['project-pattern']

        branches = XML.SubElement(gproj, 'branches')
        project_branches = project.get('branches', [])

        if 'branch-compare-type' in project and 'branch-pattern' in project:
            warning = 'branch-compare-type and branch-pattern at project ' \
                      'level are deprecated and support will be removed ' \
                      'in a later version of Jenkins Job Builder; '
            if project_branches:
                warning += 'discarding values and using values from ' \
                           'branches section'
            else:
                warning += 'please use branches section instead'
            logger.warning(warning)
        if not project_branches:
            project_branches = [
                {'branch-compare-type': project.get(
                    'branch-compare-type', 'PLAIN'),
                 'branch-pattern': project['branch-pattern']}]
        for branch in project_branches:
            gbranch = XML.SubElement(
                branches, 'com.sonyericsson.hudson.plugins.'
                'gerrit.trigger.hudsontrigger.data.Branch')
            XML.SubElement(gbranch, 'compareType').text = get_compare_type(
                'branch-compare-type', branch.get(
                    'branch-compare-type', 'PLAIN'))
            XML.SubElement(gbranch, 'pattern').text = branch['branch-pattern']

        project_file_paths = project.get('file-paths', [])
        if project_file_paths:
            fps_tag = XML.SubElement(gproj, 'filePaths')
            for file_path in project_file_paths:
                fp_tag = XML.SubElement(fps_tag,
                                        'com.sonyericsson.hudson.plugins.'
                                        'gerrit.trigger.hudsontrigger.data.'
                                        'FilePath')
                XML.SubElement(fp_tag, 'compareType').text = get_compare_type(
                    'compare-type', file_path.get('compare-type', 'PLAIN'))
                XML.SubElement(fp_tag, 'pattern').text = file_path['pattern']

        project_forbidden_file_paths = project.get('forbidden-file-paths', [])
        if project_forbidden_file_paths:
            ffps_tag = XML.SubElement(gproj, 'forbiddenFilePaths')
            for forbidden_file_path in project_forbidden_file_paths:
                ffp_tag = XML.SubElement(ffps_tag,
                                         'com.sonyericsson.hudson.plugins.'
                                         'gerrit.trigger.hudsontrigger.data.'
                                         'FilePath')
                XML.SubElement(ffp_tag, 'compareType').text = get_compare_type(
                    'compare-type', forbidden_file_path.get('compare-type',
                                                            'PLAIN'))
                XML.SubElement(ffp_tag, 'pattern').text = \
                    forbidden_file_path['pattern']

        topics = project.get('topics', [])
        if topics:
            topics_tag = XML.SubElement(gproj, 'topics')
            for topic in topics:
                topic_tag = XML.SubElement(topics_tag,
                                           'com.sonyericsson.hudson.plugins.'
                                           'gerrit.trigger.hudsontrigger.data.'
                                           'Topic')
                XML.SubElement(topic_tag, 'compareType').text = \
                    get_compare_type('compare-type', topic.get('compare-type',
                                                               'PLAIN'))
                XML.SubElement(topic_tag, 'pattern').text = topic['pattern']

        XML.SubElement(gproj,
                       'disableStrictForbiddenFileVerification').text = str(
            project.get('disable-strict-forbidden-file-verification',
                        False)).lower()

    build_gerrit_skip_votes(gtrig, data)
    general_mappings = [
        ('silent', 'silentMode', False),
        ('silent-start', 'silentStartMode', False),
        ('escape-quotes', 'escapeQuotes', True),
        ('no-name-and-email', 'noNameAndEmailParameters', False),
        ('readable-message', 'readableMessage', False),
        ('dependency-jobs', 'dependencyJobsNames', ''),
    ]
    helpers.convert_mapping_to_xml(
        gtrig, data, general_mappings, fail_required=True)
    notification_levels = ['NONE', 'OWNER', 'OWNER_REVIEWERS', 'ALL',
                           'SERVER_DEFAULT']
    notification_level = data.get('notification-level', 'SERVER_DEFAULT')
    if notification_level not in notification_levels:
        raise InvalidAttributeError('notification-level', notification_level,
                                    notification_levels)
    if notification_level == 'SERVER_DEFAULT':
        XML.SubElement(gtrig, 'notificationLevel').text = ''
    else:
        XML.SubElement(gtrig, 'notificationLevel').text = notification_level
    XML.SubElement(gtrig, 'dynamicTriggerConfiguration').text = str(
        data.get('dynamic-trigger-enabled', False))
    XML.SubElement(gtrig, 'triggerConfigURL').text = str(
        data.get('dynamic-trigger-url', ''))
    XML.SubElement(gtrig, 'triggerInformationAction').text = str(
        data.get('trigger-information-action', ''))
    XML.SubElement(gtrig, 'allowTriggeringUnreviewedPatches').text = str(
        data.get('trigger-for-unreviewed-patches', False)).lower()
    build_gerrit_triggers(gtrig, data)
    override = str(data.get('override-votes', False)).lower()
    if override == 'true':
        for yamlkey, xmlkey in [('gerrit-build-started-verified-value',
                                 'gerritBuildStartedVerifiedValue'),
                                ('gerrit-build-successful-verified-value',
                                 'gerritBuildSuccessfulVerifiedValue'),
                                ('gerrit-build-failed-verified-value',
                                 'gerritBuildFailedVerifiedValue'),
                                ('gerrit-build-unstable-verified-value',
                                 'gerritBuildUnstableVerifiedValue'),
                                ('gerrit-build-notbuilt-verified-value',
                                 'gerritBuildNotBuiltVerifiedValue'),
                                ('gerrit-build-started-codereview-value',
                                 'gerritBuildStartedCodeReviewValue'),
                                ('gerrit-build-successful-codereview-value',
                                 'gerritBuildSuccessfulCodeReviewValue'),
                                ('gerrit-build-failed-codereview-value',
                                 'gerritBuildFailedCodeReviewValue'),
                                ('gerrit-build-unstable-codereview-value',
                                 'gerritBuildUnstableCodeReviewValue'),
                                ('gerrit-build-notbuilt-codereview-value',
                                 'gerritBuildNotBuiltCodeReviewValue')]:
            if data.get(yamlkey) is not None:
                # str(int(x)) makes input values like '+1' work
                XML.SubElement(gtrig, xmlkey).text = str(
                    int(data.get(yamlkey)))
    message_mappings = [
        ('start-message', 'buildStartMessage', ''),
        ('failure-message', 'buildFailureMessage', ''),
        ('successful-message', 'buildSuccessfulMessage', ''),
        ('unstable-message', 'buildUnstableMessage', ''),
        ('notbuilt-message', 'buildNotBuiltMessage', ''),
        ('failure-message-file', 'buildUnsuccessfulFilepath', ''),
        ('custom-url', 'customUrl', ''),
        ('server-name', 'serverName', '__ANY__'),
    ]
    helpers.convert_mapping_to_xml(
        gtrig, data, message_mappings, fail_required=True)


def dockerhub_notification(registry, xml_parent, data):
    """yaml: dockerhub-notification
    The job will get triggered when Docker Hub/Registry notifies
    that Docker image(s) used in this job has been rebuilt.

    Requires the Jenkins :jenkins-wiki:`CloudBees Docker Hub Notification
    <CloudBees+Docker+Hub+Notification>`.

    :arg bool referenced-image: Trigger the job based on repositories
        used by any compatible docker plugin in this job. (default true)
    :arg list repositories: Specified repositories to trigger the job.
            (default [])

    Minimal Example:

    .. literalinclude::
       /../../tests/triggers/fixtures/dockerhub-notification-minimal.yaml
       :language: yaml

    Full Example:

    .. literalinclude::
       /../../tests/triggers/fixtures/dockerhub-notification-full.yaml
       :language: yaml
    """
    dockerhub = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.'
                               'registry.notification.DockerHubTrigger')
    dockerhub.set('plugin', 'dockerhub-notification')

    option = XML.SubElement(dockerhub, 'options', {'class': 'vector'})

    if data.get('referenced-image'):
        XML.SubElement(option, 'org.jenkinsci.plugins.'
                       'registry.notification.'
                       'opt.impl.TriggerForAllUsedInJob')
    repos = data.get('repositories', [])
    if repos:
        specified_names = XML.SubElement(option,
                                         'org.jenkinsci.plugins.registry.'
                                         'notification.opt.impl.'
                                         'TriggerOnSpecifiedImageNames')

        repo_tag = XML.SubElement(specified_names, 'repoNames')
        for repo in repos:
            XML.SubElement(repo_tag, 'string').text = repo


def pollscm(registry, xml_parent, data):
    """yaml: pollscm
    Poll the SCM to determine if there has been a change.

    :Parameter: the polling interval (cron syntax)

    .. deprecated:: 1.3.0. Please use :ref:`cron <cron>`.

    .. _cron:

    :arg string cron: the polling interval (cron syntax, required)
    :arg bool ignore-post-commit-hooks: Ignore changes notified by SCM
        post-commit hooks. The subversion-plugin supports this since
        version 1.44. (default false)

    Example:

    .. literalinclude:: /../../tests/triggers/fixtures/pollscm002.yaml
       :language: yaml
    """

    try:
        cron = data['cron']
        ipch = str(data.get('ignore-post-commit-hooks', False)).lower()
    except KeyError as e:
        # ensure specific error on the attribute not being set is raised
        # for new format
        raise MissingAttributeError(e)
    except TypeError:
        # To keep backward compatibility
        logger.warning(
            "Your pollscm usage is deprecated, please use"
            " the syntax described in the documentation"
            " instead")
        cron = data
        ipch = 'false'

    if not cron and cron != '':
        raise InvalidAttributeError('cron', cron)

    scmtrig = XML.SubElement(xml_parent, 'hudson.triggers.SCMTrigger')
    XML.SubElement(scmtrig, 'spec').text = cron
    XML.SubElement(scmtrig, 'ignorePostCommitHooks').text = ipch


def build_content_type(xml_parent, entries, namespace, collection_suffix,
                       entry_suffix, prefix, collection_name, element_name):
    content_type = XML.SubElement(
        xml_parent, '{0}.{1}{2}'.format(namespace, prefix, collection_suffix))
    if entries:
        collection = XML.SubElement(content_type, collection_name)
        for entry in entries:
            content_entry = XML.SubElement(
                collection, '{0}.{1}{2}'.format(namespace, prefix,
                                                entry_suffix))
            XML.SubElement(content_entry, element_name).text = entry


def pollurl(registry, xml_parent, data):
    """yaml: pollurl
    Trigger when the HTTP response from a URL changes.
    Requires the Jenkins :jenkins-wiki:`URLTrigger Plugin <URLTrigger+Plugin>`.

    :arg string cron: cron syntax of when to run (default '')
    :arg string polling-node: Restrict where the polling should run.
                              (optional)
    :arg list urls: List of URLs to monitor

      :URL: * **url** (`str`) -- URL to monitor for changes (required)
            * **proxy** (`bool`) -- Activate the Jenkins proxy (default false)
            * **timeout** (`int`) -- Connect/read timeout in seconds
              (default 300)
            * **username** (`string`) -- User name for basic authentication
              (optional)
            * **password** (`string`) -- Password for basic authentication
              (optional)
            * **check-status** (`int`) -- Check for a specific HTTP status
              code (optional)
            * **check-etag** (`bool`) -- Check the HTTP ETag for changes
              (default false)
            * **check-date** (`bool`) -- Check the last modification date of
              the URL (default false)
            * **check-content** (`list`) -- List of content type changes to
              monitor

              :Content Type: * **simple** (`bool`) -- Trigger on any change to
                               the content of the URL (default false)
                             * **json** (`list`) -- Trigger on any change to
                               the listed JSON paths
                             * **text** (`list`) -- Trigger on any change to
                               the listed regular expressions
                             * **xml** (`list`) -- Trigger on any change to
                               the listed XPath expressions

    Example:

    .. literalinclude:: /../../tests/triggers/fixtures/pollurl001.yaml
    """

    namespace = 'org.jenkinsci.plugins.urltrigger.'
    valid_content_types = {
        'simple': ['Simple', '', '', []],
        'json': ['JSON', 'jsonPaths', 'jsonPath', None],
        'text': ['TEXT', 'regExElements', 'regEx', None],
        'xml': ['XML', 'xPaths', 'xPath', None]
    }
    urltrig = XML.SubElement(xml_parent,
                             namespace + 'URLTrigger')
    node = data.get('polling-node')
    XML.SubElement(urltrig, 'spec').text = data.get('cron', '')
    XML.SubElement(urltrig, 'labelRestriction').text = str(bool(node)).lower()
    if node:
        XML.SubElement(urltrig, 'triggerLabel').text = node
    entries = XML.SubElement(urltrig, 'entries')
    urls = data.get('urls', [])
    if not urls:
        raise JenkinsJobsException('At least one url must be provided')
    for url in urls:
        entry = XML.SubElement(entries, namespace + 'URLTriggerEntry')
        XML.SubElement(entry, 'url').text = url['url']
        XML.SubElement(entry, 'proxyActivated').text = \
            str(url.get('proxy', False)).lower()
        if 'username' in url:
            XML.SubElement(entry, 'username').text = url['username']
        if 'password' in url:
            XML.SubElement(entry, 'password').text = url['password']
        if 'check-status' in url:
            XML.SubElement(entry, 'checkStatus').text = 'true'
            XML.SubElement(entry, 'statusCode').text = \
                str(url.get('check-status'))
        else:
            XML.SubElement(entry, 'checkStatus').text = 'false'
            XML.SubElement(entry, 'statusCode').text = '200'
        XML.SubElement(entry, 'timeout').text = \
            str(url.get('timeout', 300))
        XML.SubElement(entry, 'checkETag').text = \
            str(url.get('check-etag', False)).lower()
        XML.SubElement(entry, 'checkLastModificationDate').text = \
            str(url.get('check-date', False)).lower()
        check_content = url.get('check-content', [])
        XML.SubElement(entry, 'inspectingContent').text = \
            str(bool(check_content)).lower()
        content_types = XML.SubElement(entry, 'contentTypes')
        for entry in check_content:
            type_name = next(iter(entry.keys()))
            if type_name not in valid_content_types:
                raise JenkinsJobsException('check-content must be one of : %s'
                                           % ', '.join(valid_content_types.
                                                       keys()))

            content_type = valid_content_types.get(type_name)
            if entry[type_name]:
                sub_entries = content_type[3]
                if sub_entries is None:
                    sub_entries = entry[type_name]
                build_content_type(content_types, sub_entries,
                                   namespace + 'content', 'ContentType',
                                   'ContentEntry', *content_type[0:3])


def jms_messaging(registry, xml_parent, data):
    """yaml: jms-messaging
    The JMS Messaging Plugin provides the following functionality:
     - A build trigger to submit jenkins jobs upon receipt
       of a matching message.
     - A builder that may be used to submit a message to the topic
       upon the completion of a job
     - A post-build action that may be used to submit a message to the topic
       upon the completion of a job

    JMS Messaging provider types supported:
        - ActiveMQ
        - FedMsg

    Requires the Jenkins :jenkins-wiki:`JMS Messaging Plugin
    <JMS+Messaging+Plugin>`.

    :arg str selector: The JSON or YAML formatted text that conforms to
        the schema for defining the various OpenShift resources. (default '')
        note: topic needs to be in double quotes
        ex. topic = "org.fedoraproject.prod.fedimg.image.upload"
    :arg str provider-name: Name of message provider setup in the
        global config. (default '')
    :arg list checks: List of checks to monitor. (default [])
    :arg str field: Check the body of messages for a field. (default '')
    :arg str expected-value: Expected value for the field. regex (default '')


    Full Example:

    .. literalinclude::
        ../../tests/triggers/fixtures/jms-messaging001.yaml
       :language: yaml

    Minimal Example:

    .. literalinclude::
        ../../tests/triggers/fixtures/jms-messaging002.yaml
       :language: yaml
    """
    namespace = 'com.redhat.jenkins.plugins.ci.'
    jmsm = XML.SubElement(xml_parent,
                          namespace + 'CIBuildTrigger')

    mapping = [
        # option, xml name, default value
        ("spec", 'spec', ''),
        ("selector", 'selector', ''),
        ("provider-name", 'providerName', ''),
    ]
    helpers.convert_mapping_to_xml(jmsm, data, mapping, fail_required=True)

    checks = data.get('checks', [])
    if len(checks) > 0:
        msgchecks = XML.SubElement(jmsm, 'checks')
        for check in checks:
            msgcheck = XML.SubElement(msgchecks, namespace +
                                      'messaging.checks.MsgCheck')
            mapping = [
                ('field', 'field', ''),
                ('expected-value', 'expectedValue', ''),
            ]
            helpers.convert_mapping_to_xml(
                msgcheck, check, mapping, fail_required=True)


def timed(registry, xml_parent, data):
    """yaml: timed
    Trigger builds at certain times.

    :Parameter: when to run the job (cron syntax)

    Example::

      triggers:
        - timed: "@midnight"
    """
    scmtrig = XML.SubElement(xml_parent, 'hudson.triggers.TimerTrigger')
    XML.SubElement(scmtrig, 'spec').text = data


def bitbucket(registry, xml_parent, data):
    """yaml: bitbucket
    Trigger a job when bitbucket repository is pushed to.
    Requires the Jenkins :jenkins-wiki:`BitBucket Plugin
    <BitBucket+Plugin>`.

    Example:

    .. literalinclude:: /../../tests/triggers/fixtures/bitbucket.yaml
    """
    bbtrig = XML.SubElement(xml_parent, 'com.cloudbees.jenkins.'
                            'plugins.BitBucketTrigger')
    XML.SubElement(bbtrig, 'spec').text = ''


def github(registry, xml_parent, data):
    """yaml: github
    Trigger a job when github repository is pushed to.
    Requires the Jenkins :jenkins-wiki:`GitHub Plugin <GitHub+Plugin>`.

    Example::

      triggers:
        - github
    """
    ghtrig = XML.SubElement(xml_parent, 'com.cloudbees.jenkins.'
                            'GitHubPushTrigger')
    XML.SubElement(ghtrig, 'spec').text = ''


def github_pull_request(registry, xml_parent, data):
    """yaml: github-pull-request
    Build pull requests in github and report results.
    Requires the Jenkins :jenkins-wiki:`GitHub Pull Request Builder Plugin
    <GitHub+pull+request+builder+plugin>`.

    :arg list admin-list: the users with admin rights (optional)
    :arg list white-list: users whose pull requests build (optional)
    :arg list org-list: orgs whose users should be white listed (optional)
    :arg bool allow-whitelist-orgs-as-admins: members of white listed orgs
        will have admin rights. (default false)
    :arg string cron: cron syntax of when to run (optional)
    :arg string trigger-phrase: when filled, commenting this phrase
        in the pull request will trigger a build (optional)
    :arg bool only-trigger-phrase: only commenting the trigger phrase
        in the pull request will trigger a build (default false)
    :arg string skip-build-phrase: when filled, adding this phrase to
        the pull request title or body will not trigger a build (optional)
    :arg string black-list-labels: list of GitHub labels for which the build
        should not be triggered (optional)
    :arg string white-list-labels: list of GitHub labels for which the build
        should only be triggered. (Leave blank for 'any') (optional)
    :arg bool github-hooks: use github hook (default false)
    :arg bool permit-all: build every pull request automatically
        without asking (default false)
    :arg bool auto-close-on-fail: close failed pull request automatically
        (default false)
    :arg list white-list-target-branches: Adding branches to this whitelist
        allows you to selectively test pull requests destined for these
        branches only. Supports regular expressions (e.g. 'master',
        'feature-.*'). (optional)
    :arg list black-list-target-branches: Adding branches to this blacklist
        allows you to selectively prevent pull requests builds destined for
        these branches. Supports regular expressions (e.g. 'master',
        'feature-.*'). (optional)
    :arg string auth-id: the auth id to use (optional)
    :arg string build-desc-template: the template for build descriptions in
        jenkins (optional)
    :arg string status-context: the context to include on PR status comments
        (optional)
    :arg string triggered-status: the status message to set when the build has
        been triggered (optional)
    :arg string started-status: the status comment to set when the build has
        been started (optional)
    :arg string status-url: the status URL to set (optional)
    :arg bool status-add-test-results: add test result one-liner to status
        message (optional)
    :arg string success-status: the status message to set if the job succeeds
        (optional)
    :arg string failure-status: the status message to set if the job fails
        (optional)
    :arg string error-status: the status message to set if the job errors
        (optional)
    :arg string success-comment: comment to add to the PR on a successful job
        (optional)
    :arg string failure-comment: comment to add to the PR on a failed job
        (optional)
    :arg string error-comment: comment to add to the PR on an errored job
        (optional)
    :arg bool cancel-builds-on-update: cancel existing builds when a PR is
        updated (optional)
    :arg list included-regions: Each inclusion uses regular expression pattern
        matching, and must be separated by a new line. An empty list implies
        that everything is included. (optional)
    :arg list excluded-regions: Each exclusion uses regular expression pattern
        matching, and must be separated by a new line. Exclusions take
        precedence over inclusions, if there is an overlap between included
        and excluded regions. (optional)

    Full Example:

    .. literalinclude::
       /../../tests/triggers/fixtures/github-pull-request-full.yaml
       :language: yaml

    Minimal Example:

    .. literalinclude::
       /../../tests/triggers/fixtures/github-pull-request-minimal.yaml
       :language: yaml
    """
    ghprb = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.ghprb.'
                           'GhprbTrigger')
    XML.SubElement(ghprb, 'spec').text = data.get('cron', '')
    admin_string = "\n".join(data.get('admin-list', []))
    XML.SubElement(ghprb, 'adminlist').text = admin_string
    XML.SubElement(ghprb, 'allowMembersOfWhitelistedOrgsAsAdmin').text = str(
        data.get('allow-whitelist-orgs-as-admins', False)).lower()
    white_string = "\n".join(data.get('white-list', []))
    XML.SubElement(ghprb, 'whitelist').text = white_string
    org_string = "\n".join(data.get('org-list', []))
    XML.SubElement(ghprb, 'orgslist').text = org_string
    white_list_labels_string = "\n".join(data.get('white-list-labels', []))
    XML.SubElement(ghprb, 'whiteListLabels').text = white_list_labels_string
    black_list_labels_string = "\n".join(data.get('black-list-labels', []))
    XML.SubElement(ghprb, 'blackListLabels').text = black_list_labels_string
    XML.SubElement(ghprb, 'cron').text = data.get('cron', '')
    excluded_regions_string = "\n".join(data.get('excluded-regions', []))
    XML.SubElement(ghprb, 'excludedRegions').text = excluded_regions_string
    included_regions_string = "\n".join(data.get('included-regions', []))
    XML.SubElement(ghprb, 'includedRegions').text = included_regions_string

    build_desc_template = data.get('build-desc-template', '')
    if build_desc_template:
        XML.SubElement(ghprb, 'buildDescTemplate').text = str(
            build_desc_template)

    XML.SubElement(ghprb, 'triggerPhrase').text = \
        data.get('trigger-phrase', '')
    XML.SubElement(ghprb, 'skipBuildPhrase').text = str(
        data.get('skip-build-phrase', '')).lower()
    XML.SubElement(ghprb, 'onlyTriggerPhrase').text = str(
        data.get('only-trigger-phrase', False)).lower()
    XML.SubElement(ghprb, 'useGitHubHooks').text = str(
        data.get('github-hooks', False)).lower()
    XML.SubElement(ghprb, 'permitAll').text = str(
        data.get('permit-all', False)).lower()
    XML.SubElement(ghprb, 'autoCloseFailedPullRequests').text = str(
        data.get('auto-close-on-fail', False)).lower()

    white_list_target_branches = data.get('white-list-target-branches', [])
    if white_list_target_branches:
        ghprb_wltb = XML.SubElement(ghprb, 'whiteListTargetBranches')
        for branch in white_list_target_branches:
            be = XML.SubElement(ghprb_wltb, 'org.jenkinsci.plugins.'
                                'ghprb.GhprbBranch')
            XML.SubElement(be, 'branch').text = str(branch)

    black_list_target_branches = data.get('black-list-target-branches', [])
    if black_list_target_branches:
        ghprb_bltb = XML.SubElement(ghprb, 'blackListTargetBranches')
        for branch in black_list_target_branches:
            be = XML.SubElement(ghprb_bltb, 'org.jenkinsci.plugins.'
                                'ghprb.GhprbBranch')
            XML.SubElement(be, 'branch').text = str(branch)

    auth_id = data.get('auth-id', '')
    if auth_id:
        XML.SubElement(ghprb, 'gitHubAuthId').text = str(auth_id)

    # PR status update fields
    status_context = data.get('status-context', '')
    triggered_status = data.get('triggered-status', '')
    started_status = data.get('started-status', '')
    status_url = data.get('status-url', '')
    status_add_test_results = data.get('status-add-test-results', '')
    success_status = data.get('success-status', '')
    failure_status = data.get('failure-status', '')
    error_status = data.get('error-status', '')

    # is status handling is required?
    requires_status = (
        status_context or
        triggered_status or
        started_status or
        status_url or
        status_add_test_results or
        success_status or
        failure_status or
        error_status
    )

    # is status message handling required?
    requires_status_message = (
        success_status or
        failure_status or
        error_status
    )

    # is comment handling required?
    success_comment = data.get('success-comment', '')
    failure_comment = data.get('failure-comment', '')
    error_comment = data.get('error-comment', '')
    requires_job_comment = (
        success_comment or
        failure_comment or
        error_comment
    )

    cancel_builds_on_update = data.get('cancel-builds-on-update', False)

    # We want to have only one 'extensions' subelement, even if status
    # handling, comment handling and other extensions are enabled.
    if requires_status or requires_job_comment or cancel_builds_on_update:
        extensions = XML.SubElement(ghprb, 'extensions')

    # Both comment and status elements have this same type.  Using a const is
    # much easier to read than repeating the tokens for this class each time
    # it's used
    comment_type = 'org.jenkinsci.plugins.ghprb.extensions.comments.'
    comment_type = comment_type + 'GhprbBuildResultMessage'

    if requires_status:
        simple_status = XML.SubElement(extensions,
                                       'org.jenkinsci.plugins'
                                       '.ghprb.extensions.status.'
                                       'GhprbSimpleStatus')
        if status_context:
            XML.SubElement(simple_status, 'commitStatusContext').text = str(
                status_context)
        if triggered_status:
            XML.SubElement(simple_status, 'triggeredStatus').text = str(
                triggered_status)
        if started_status:
            XML.SubElement(simple_status, 'startedStatus').text = str(
                started_status)
        if status_url:
            XML.SubElement(simple_status, 'statusUrl').text = str(
                status_url)
        if status_add_test_results:
            XML.SubElement(simple_status, 'addTestResults').text = str(
                status_add_test_results).lower()

        if requires_status_message:
            completed_elem = XML.SubElement(simple_status, 'completedStatus')
            if success_status:
                success_elem = XML.SubElement(completed_elem, comment_type)
                XML.SubElement(success_elem, 'message').text = str(
                    success_status)
                XML.SubElement(success_elem, 'result').text = 'SUCCESS'
            if failure_status:
                failure_elem = XML.SubElement(completed_elem, comment_type)
                XML.SubElement(failure_elem, 'message').text = str(
                    failure_status)
                XML.SubElement(failure_elem, 'result').text = 'FAILURE'
            if error_status:
                error_elem = XML.SubElement(completed_elem, comment_type)
                XML.SubElement(error_elem, 'message').text = str(error_status)
                XML.SubElement(error_elem, 'result').text = 'ERROR'

    # job comment handling
    if requires_job_comment:
        build_status = XML.SubElement(extensions,
                                      'org.jenkinsci.plugins.ghprb.extensions'
                                      '.comments.'
                                      'GhprbBuildStatus')
        messages_elem = XML.SubElement(build_status, 'messages')
        if success_comment:
            success_comment_elem = XML.SubElement(messages_elem, comment_type)
            XML.SubElement(success_comment_elem, 'message').text = str(
                success_comment)
            XML.SubElement(success_comment_elem, 'result').text = 'SUCCESS'
        if failure_comment:
            failure_comment_elem = XML.SubElement(messages_elem, comment_type)
            XML.SubElement(failure_comment_elem, 'message').text = str(
                failure_comment)
            XML.SubElement(failure_comment_elem, 'result').text = 'FAILURE'
        if error_comment:
            error_comment_elem = XML.SubElement(messages_elem, comment_type)
            XML.SubElement(error_comment_elem, 'message').text = str(
                error_comment)
            XML.SubElement(error_comment_elem, 'result').text = 'ERROR'

    if cancel_builds_on_update:
        XML.SubElement(extensions,
                       'org.jenkinsci.plugins.ghprb.extensions.'
                       'build.GhprbCancelBuildsOnUpdate')


def gitlab_merge_request(registry, xml_parent, data):
    """yaml: gitlab-merge-request
    Build merge requests in gitlab and report results.
    Requires the Jenkins :jenkins-wiki:`Gitlab MergeRequest Builder Plugin.
    <Gitlab+Merge+Request+Builder+Plugin>`.

    :arg string cron: Cron syntax of when to run (required)
    :arg string project-path: Gitlab-relative path to project (required)
    :arg string use-http-url: Use the HTTP(S) URL to fetch/clone repository
        (default false)
    :arg string assignee-filter: Only MRs with this assigned user will
        trigger the build automatically (default 'jenkins')
    :arg string tag-filter: Only MRs with this label will trigger the build
        automatically (default 'Build')
    :arg string trigger-comment: Force build if this comment is the last
        in merge reguest (default '')
    :arg string publish-build-progress-messages: Publish build progress
        messages (except build failed) (default true)
    :arg string auto-close-failed: On failure, auto close the request
        (default false)
    :arg string auto-merge-passed: On success, auto merge the request
        (default false)

    Example:

    .. literalinclude:: \
        /../../tests/triggers/fixtures/gitlab-merge-request.yaml
    """
    ghprb = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.gitlab.'
                           'GitlabBuildTrigger')

    # Because of a design limitation in the GitlabBuildTrigger Jenkins plugin
    # both 'spec' and '__cron' have to be set to the same value to have them
    # take effect. Also, cron and projectPath are prefixed with underscores
    # in the plugin, but spec is not.
    mapping = [
        ('cron', 'spec', None),
        ('cron', '__cron', None),
        ('project-path', '__projectPath', None),
        ('use-http-url', '__useHttpUrl', False),
        ('assignee-filter', '__assigneeFilter', 'jenkins'),
        ('tag-filter', '__tagFilter', 'Build'),
        ('trigger-comment', '__triggerComment', ''),
        ('publish-build-progress-messages', '__publishBuildProgressMessages',
         True),
        ('auto-close-failed', '__autoCloseFailed', False),
        ('auto-merge-passed', '__autoMergePassed', False),
    ]