Tools to make Jenkins jobs from templates
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

triggers.py 91KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139
  1. # Copyright 2012 Hewlett-Packard Development Company, L.P.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. # License for the specific language governing permissions and limitations
  13. # under the License.
  14. """
  15. Triggers define what causes a Jenkins job to start building.
  16. **Component**: triggers
  17. :Macro: trigger
  18. :Entry Point: jenkins_jobs.triggers
  19. Example::
  20. job:
  21. name: test_job
  22. triggers:
  23. - timed: '@daily'
  24. """
  25. import logging
  26. import pkg_resources
  27. import re
  28. import sys
  29. import xml.etree.ElementTree as XML
  30. import six
  31. from jenkins_jobs.errors import InvalidAttributeError
  32. from jenkins_jobs.errors import JenkinsJobsException
  33. from jenkins_jobs.errors import MissingAttributeError
  34. import jenkins_jobs.modules.base
  35. from jenkins_jobs.modules import hudson_model
  36. from jenkins_jobs.modules.helpers import convert_mapping_to_xml
  37. logger = logging.getLogger(str(__name__))
  38. def gerrit_handle_legacy_configuration(data):
  39. hyphenizer = re.compile("[A-Z]")
  40. def hyphenize(attr):
  41. """Convert strings like triggerOn to trigger-on.
  42. """
  43. return hyphenizer.sub(lambda x: "-%s" % x.group(0).lower(),
  44. attr)
  45. def convert_dict(d, old_keys):
  46. for old_key in old_keys:
  47. if old_key in d:
  48. new_key = hyphenize(old_key)
  49. logger.warning(
  50. "'%s' is deprecated and will be removed after "
  51. "1.0.0, please use '%s' instead", old_key, new_key)
  52. d[new_key] = d[old_key]
  53. del d[old_key]
  54. convert_dict(data, [
  55. 'triggerOnPatchsetUploadedEvent',
  56. 'triggerOnChangeAbandonedEvent',
  57. 'triggerOnChangeMergedEvent',
  58. 'triggerOnChangeRestoredEvent',
  59. 'triggerOnCommentAddedEvent',
  60. 'triggerOnDraftPublishedEvent',
  61. 'triggerOnRefUpdatedEvent',
  62. 'triggerApprovalCategory',
  63. 'triggerApprovalValue',
  64. 'overrideVotes',
  65. 'gerritBuildSuccessfulVerifiedValue',
  66. 'gerritBuildFailedVerifiedValue',
  67. 'failureMessage',
  68. 'skipVote',
  69. ])
  70. for project in data.get('projects', []):
  71. convert_dict(project, [
  72. 'projectCompareType',
  73. 'projectPattern',
  74. 'branchCompareType',
  75. 'branchPattern',
  76. ])
  77. mapping_obj_type = type(data)
  78. old_format_events = mapping_obj_type(
  79. (key, should_register) for key, should_register in six.iteritems(data)
  80. if key.startswith('trigger-on-'))
  81. trigger_on = data.setdefault('trigger-on', [])
  82. if old_format_events:
  83. logger.warning(
  84. "The events: %s; which you used is/are deprecated. "
  85. "Please use 'trigger-on' instead.",
  86. ', '.join(old_format_events))
  87. if old_format_events and trigger_on:
  88. raise JenkinsJobsException(
  89. 'Both, the new format (trigger-on) and old format (trigger-on-*) '
  90. 'gerrit events format found. Please use either the new or the old '
  91. 'format of trigger events definition.')
  92. trigger_on.extend(event_name[len('trigger-on-'):]
  93. for event_name, should_register
  94. in six.iteritems(old_format_events) if should_register)
  95. for idx, event in enumerate(trigger_on):
  96. if event == 'comment-added-event':
  97. trigger_on[idx] = events = mapping_obj_type()
  98. try:
  99. events['comment-added-event'] = mapping_obj_type((
  100. ('approval-category', data['trigger-approval-category']),
  101. ('approval-value', data['trigger-approval-value'])
  102. ))
  103. except KeyError:
  104. raise JenkinsJobsException(
  105. 'The comment-added-event trigger requires which approval '
  106. 'category and value you want to trigger the job. '
  107. 'It should be specified by the approval-category '
  108. 'and approval-value properties.')
  109. def build_gerrit_triggers(xml_parent, data):
  110. available_simple_triggers = {
  111. 'change-abandoned-event': 'PluginChangeAbandonedEvent',
  112. 'change-merged-event': 'PluginChangeMergedEvent',
  113. 'change-restored-event': 'PluginChangeRestoredEvent',
  114. 'draft-published-event': 'PluginDraftPublishedEvent',
  115. 'patchset-uploaded-event': 'PluginPatchsetCreatedEvent',
  116. 'patchset-created-event': 'PluginPatchsetCreatedEvent',
  117. 'ref-updated-event': 'PluginRefUpdatedEvent',
  118. }
  119. tag_namespace = 'com.sonyericsson.hudson.plugins.gerrit.trigger.' \
  120. 'hudsontrigger.events'
  121. trigger_on_events = XML.SubElement(xml_parent, 'triggerOnEvents')
  122. for event in data.get('trigger-on', []):
  123. if isinstance(event, six.string_types):
  124. tag_name = available_simple_triggers.get(event)
  125. if event == 'patchset-uploaded-event':
  126. logger.warning(
  127. "'%s' is deprecated. Use 'patchset-created-event' "
  128. "format instead.", event)
  129. if not tag_name:
  130. known = ', '.join(available_simple_triggers.keys() +
  131. ['comment-added-event',
  132. 'comment-added-contains-event'])
  133. msg = ("The event '%s' under 'trigger-on' is not one of the "
  134. "known: %s.") % (event, known)
  135. raise JenkinsJobsException(msg)
  136. XML.SubElement(trigger_on_events,
  137. '%s.%s' % (tag_namespace, tag_name))
  138. else:
  139. if 'patchset-created-event' in event.keys():
  140. pce = event['patchset-created-event']
  141. pc = XML.SubElement(
  142. trigger_on_events,
  143. '%s.%s' % (tag_namespace, 'PluginPatchsetCreatedEvent'))
  144. mapping = [
  145. ('exclude-drafts', 'excludeDrafts', False),
  146. ('exclude-trivial-rebase', 'excludeTrivialRebase', False),
  147. ('exclude-no-code-change', 'excludeNoCodeChange', False)]
  148. convert_mapping_to_xml(pc, pce, mapping, fail_required=True)
  149. if 'comment-added-event' in event.keys():
  150. comment_added_event = event['comment-added-event']
  151. cadded = XML.SubElement(
  152. trigger_on_events,
  153. '%s.%s' % (tag_namespace, 'PluginCommentAddedEvent'))
  154. mapping = [
  155. ('approval-category', 'verdictCategory', None),
  156. ('approval-value',
  157. 'commentAddedTriggerApprovalValue', None)]
  158. convert_mapping_to_xml(cadded,
  159. comment_added_event, mapping, fail_required=True)
  160. if 'comment-added-contains-event' in event.keys():
  161. comment_added_event = event['comment-added-contains-event']
  162. caddedc = XML.SubElement(
  163. trigger_on_events,
  164. '%s.%s' % (tag_namespace,
  165. 'PluginCommentAddedContainsEvent'))
  166. XML.SubElement(caddedc, 'commentAddedCommentContains').text = \
  167. comment_added_event['comment-contains-value']
  168. def build_gerrit_skip_votes(xml_parent, data):
  169. outcomes = [('successful', 'onSuccessful'),
  170. ('failed', 'onFailed'),
  171. ('unstable', 'onUnstable'),
  172. ('notbuilt', 'onNotBuilt')]
  173. skip_vote_node = XML.SubElement(xml_parent, 'skipVote')
  174. skip_vote = data.get('skip-vote', {})
  175. for result_kind, tag_name in outcomes:
  176. setting = skip_vote.get(result_kind, False)
  177. XML.SubElement(skip_vote_node, tag_name).text = str(setting).lower()
  178. def gerrit(registry, xml_parent, data):
  179. """yaml: gerrit
  180. Trigger on a Gerrit event.
  181. Requires the Jenkins :jenkins-wiki:`Gerrit Trigger Plugin <Gerrit+Trigger>`
  182. version >= 2.6.0.
  183. :arg list trigger-on: Events to react on. Please use either the new
  184. **trigger-on**, or the old **trigger-on-*** events definitions. You
  185. cannot use both at once.
  186. .. _trigger_on:
  187. :Trigger on:
  188. * **patchset-created-event** (`dict`) -- Trigger upon patchset
  189. creation.
  190. :Patchset created:
  191. * **exclude-drafts** (`bool`) -- exclude drafts (default false)
  192. * **exclude-trivial-rebase** (`bool`) -- exclude trivial rebase
  193. (default false)
  194. * **exclude-no-code-change** (`bool`) -- exclude no code change
  195. (default false)
  196. Exclude drafts|trivial-rebase|no-code-change needs
  197. Gerrit Trigger v2.12.0
  198. * **patchset-uploaded-event** -- Trigger upon patchset creation
  199. (this is a alias for `patchset-created-event`).
  200. .. deprecated:: 1.1.0 Please use :ref:`trigger-on <trigger_on>`.
  201. * **change-abandoned-event** -- Trigger on patchset abandoned.
  202. Requires Gerrit Trigger Plugin version >= 2.8.0.
  203. * **change-merged-event** -- Trigger on change merged
  204. * **change-restored-event** -- Trigger on change restored. Requires
  205. Gerrit Trigger Plugin version >= 2.8.0
  206. * **draft-published-event** -- Trigger on draft published event.
  207. * **ref-updated-event** -- Trigger on ref-updated.
  208. * **comment-added-event** (`dict`) -- Trigger on comment added.
  209. :Comment added:
  210. * **approval-category** (`str`) -- Approval (verdict) category
  211. (for example 'APRV', 'CRVW', 'VRIF' -- see `Gerrit access
  212. control
  213. <http://gerrit.googlecode.com/svn/documentation/2.1/
  214. access-control.html#categories>`_
  215. * **approval-value** -- Approval value for the comment added.
  216. * **comment-added-contains-event** (`dict`) -- Trigger on comment
  217. added contains Regular Expression.
  218. :Comment added contains:
  219. * **comment-contains-value** (`str`) -- Comment contains
  220. Regular Expression value.
  221. :arg bool trigger-on-patchset-uploaded-event: Trigger on patchset upload.
  222. .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
  223. :arg bool trigger-on-change-abandoned-event: Trigger on change abandoned.
  224. Requires Gerrit Trigger Plugin version >= 2.8.0
  225. .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
  226. :arg bool trigger-on-change-merged-event: Trigger on change merged
  227. .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
  228. :arg bool trigger-on-change-restored-event: Trigger on change restored.
  229. Requires Gerrit Trigger Plugin version >= 2.8.0
  230. .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
  231. :arg bool trigger-on-comment-added-event: Trigger on comment added
  232. .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
  233. :arg bool trigger-on-draft-published-event: Trigger on draft published
  234. event
  235. .. deprecated:: 1.1.0 Please use :ref:`trigger-on <trigger_on>`.
  236. :arg bool trigger-on-ref-updated-event: Trigger on ref-updated
  237. .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
  238. :arg str trigger-approval-category: Approval category for comment added
  239. .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
  240. :arg int trigger-approval-value: Approval value for comment added
  241. .. deprecated:: 1.1.0. Please use :ref:`trigger-on <trigger_on>`.
  242. :arg bool override-votes: Override default vote values
  243. :arg int gerrit-build-started-verified-value: Started ''Verified'' value
  244. :arg int gerrit-build-successful-verified-value: Successful ''Verified''
  245. value
  246. :arg int gerrit-build-failed-verified-value: Failed ''Verified'' value
  247. :arg int gerrit-build-unstable-verified-value: Unstable ''Verified'' value
  248. :arg int gerrit-build-notbuilt-verified-value: Not built ''Verified''
  249. value
  250. :arg int gerrit-build-started-codereview-value: Started ''CodeReview''
  251. value
  252. :arg int gerrit-build-successful-codereview-value: Successful
  253. ''CodeReview'' value
  254. :arg int gerrit-build-failed-codereview-value: Failed ''CodeReview'' value
  255. :arg int gerrit-build-unstable-codereview-value: Unstable ''CodeReview''
  256. value
  257. :arg int gerrit-build-notbuilt-codereview-value: Not built ''CodeReview''
  258. value
  259. :arg str failure-message: Message to leave on failure (default '')
  260. :arg str successful-message: Message to leave on success (default '')
  261. :arg str unstable-message: Message to leave when unstable (default '')
  262. :arg str notbuilt-message: Message to leave when not built (default '')
  263. :arg str failure-message-file: Sets the filename within the workspace from
  264. which to retrieve the unsuccessful review message. (optional)
  265. :arg list projects: list of projects to match
  266. :Project: * **project-compare-type** (`str`) -- ''PLAIN'', ''ANT'' or
  267. ''REG_EXP''
  268. * **project-pattern** (`str`) -- Project name pattern to match
  269. * **branch-compare-type** (`str`) -- ''PLAIN'', ''ANT'' or
  270. ''REG_EXP'' (not used if `branches` list is specified)
  271. .. deprecated:: 1.1.0 Please use :ref:`branches <branches>`.
  272. * **branch-pattern** (`str`) -- Branch name pattern to match
  273. (not used if `branches` list is specified)
  274. .. deprecated:: 1.1.0 Please use :ref:`branches <branches>`.
  275. .. _branches:
  276. * **branches** (`list`) -- List of branches to match
  277. (optional)
  278. :Branch: * **branch-compare-type** (`str`) -- ''PLAIN'',
  279. ''ANT'' or ''REG_EXP'' (optional) (default
  280. ''PLAIN'')
  281. * **branch-pattern** (`str`) -- Branch name pattern
  282. to match
  283. * **file-paths** (`list`) -- List of file paths to match
  284. (optional)
  285. :File Path: * **compare-type** (`str`) -- ''PLAIN'', ''ANT''
  286. or ''REG_EXP'' (optional) (default ''PLAIN'')
  287. * **pattern** (`str`) -- File path pattern to
  288. match
  289. * **forbidden-file-paths** (`list`) -- List of file paths to
  290. skip triggering (optional)
  291. :Forbidden File Path: * **compare-type** (`str`) --
  292. ''PLAIN'', ''ANT'' or ''REG_EXP'' (optional)
  293. (default ''PLAIN'')
  294. * **pattern** (`str`) -- File path pattern to
  295. match
  296. * **topics** (`list`) -- List of topics to match
  297. (optional)
  298. :Topic: * **compare-type** (`str`) -- ''PLAIN'', ''ANT'' or
  299. ''REG_EXP'' (optional) (default ''PLAIN'')
  300. * **pattern** (`str`) -- Topic name pattern to
  301. match
  302. * **disable-strict-forbidden-file-verification** (`bool`) --
  303. Enabling this option will allow an event to trigger a
  304. build if the event contains BOTH one or more wanted file
  305. paths AND one or more forbidden file paths. In other
  306. words, with this option, the build will not get
  307. triggered if the change contains only forbidden files,
  308. otherwise it will get triggered. Requires plugin
  309. version >= 2.16.0 (default false)
  310. :arg dict skip-vote: map of build outcomes for which Jenkins must skip
  311. vote. Requires Gerrit Trigger Plugin version >= 2.7.0
  312. :Outcome: * **successful** (`bool`)
  313. * **failed** (`bool`)
  314. * **unstable** (`bool`)
  315. * **notbuilt** (`bool`)
  316. :arg bool silent: When silent mode is on there will be no communication
  317. back to Gerrit, i.e. no build started/failed/successful approve
  318. messages etc. If other non-silent jobs are triggered by the same
  319. Gerrit event as this job, the result of this job's build will not be
  320. counted in the end result of the other jobs. (default false)
  321. :arg bool silent-start: Sets silent start mode to on or off. When silent
  322. start mode is on there will be no 'build started' messages sent back
  323. to Gerrit. (default false)
  324. :arg bool escape-quotes: escape quotes in the values of Gerrit change
  325. parameters (default true)
  326. :arg bool no-name-and-email: Do not pass compound 'name and email'
  327. parameters (default false)
  328. :arg bool readable-message: If parameters regarding multiline text,
  329. e.g. commit message, should be as human readable or not. If false,
  330. those parameters are Base64 encoded to keep environment variables
  331. clean. (default false)
  332. :arg str dependency-jobs: All jobs on which this job depends. If a commit
  333. should trigger both a dependency and this job, the dependency will be
  334. built first. Use commas to separate job names. Beware of cyclic
  335. dependencies. (optional)
  336. :arg str notification-level: Defines to whom email notifications should be
  337. sent. This can either be nobody ('NONE'), the change owner ('OWNER'),
  338. reviewers and change owner ('OWNER_REVIEWERS'), all interested users
  339. i.e. owning, reviewing, watching, and starring ('ALL') or server
  340. default ('SERVER_DEFAULT'). (default 'SERVER_DEFAULT')
  341. :arg bool dynamic-trigger-enabled: Enable/disable the dynamic trigger
  342. (default false)
  343. :arg str dynamic-trigger-url: if you specify this option, the Gerrit
  344. trigger configuration will be fetched from there on a regular interval
  345. :arg bool trigger-for-unreviewed-patches: trigger patchset-created events
  346. for changes that were uploaded while connection to Gerrit was down
  347. (default false). Requires Gerrit Trigger Plugin version >= 2.11.0
  348. :arg str custom-url: Custom URL for a message sent to Gerrit. Build
  349. details URL will be used if empty. (default '')
  350. :arg str server-name: Name of the server to trigger on, or ''__ANY__'' to
  351. trigger on any configured Gerrit server (default '__ANY__'). Requires
  352. Gerrit Trigger Plugin version >= 2.11.0
  353. You may select one or more Gerrit events upon which to trigger.
  354. You must also supply at least one project and branch, optionally
  355. more. If you select the comment-added trigger, you should also
  356. indicate which approval category and value you want to trigger the
  357. job.
  358. Until version 0.4.0 of Jenkins Job Builder, camelCase keys were used to
  359. configure Gerrit Trigger Plugin, instead of hyphenated-keys. While still
  360. supported, camedCase keys are deprecated and should not be used. Support
  361. for this will be removed after 1.0.0 is released.
  362. Example:
  363. .. literalinclude:: /../../tests/triggers/fixtures/gerrit004.yaml
  364. :language: yaml
  365. """
  366. def get_compare_type(xml_tag, compare_type):
  367. valid_compare_types = ['PLAIN',
  368. 'ANT',
  369. 'REG_EXP']
  370. if compare_type not in valid_compare_types:
  371. raise InvalidAttributeError(xml_tag, compare_type,
  372. valid_compare_types)
  373. return compare_type
  374. gerrit_handle_legacy_configuration(data)
  375. projects = data.get('projects', [])
  376. gtrig = XML.SubElement(xml_parent,
  377. 'com.sonyericsson.hudson.plugins.gerrit.trigger.'
  378. 'hudsontrigger.GerritTrigger')
  379. XML.SubElement(gtrig, 'spec')
  380. gprojects = XML.SubElement(gtrig, 'gerritProjects')
  381. for project in projects:
  382. gproj = XML.SubElement(gprojects,
  383. 'com.sonyericsson.hudson.plugins.gerrit.'
  384. 'trigger.hudsontrigger.data.GerritProject')
  385. XML.SubElement(gproj, 'compareType').text = get_compare_type(
  386. 'project-compare-type', project.get(
  387. 'project-compare-type', 'PLAIN'))
  388. XML.SubElement(gproj, 'pattern').text = project['project-pattern']
  389. branches = XML.SubElement(gproj, 'branches')
  390. project_branches = project.get('branches', [])
  391. if 'branch-compare-type' in project and 'branch-pattern' in project:
  392. warning = 'branch-compare-type and branch-pattern at project ' \
  393. 'level are deprecated and support will be removed ' \
  394. 'in a later version of Jenkins Job Builder; '
  395. if project_branches:
  396. warning += 'discarding values and using values from ' \
  397. 'branches section'
  398. else:
  399. warning += 'please use branches section instead'
  400. logger.warning(warning)
  401. if not project_branches:
  402. project_branches = [
  403. {'branch-compare-type': project.get(
  404. 'branch-compare-type', 'PLAIN'),
  405. 'branch-pattern': project['branch-pattern']}]
  406. for branch in project_branches:
  407. gbranch = XML.SubElement(
  408. branches, 'com.sonyericsson.hudson.plugins.'
  409. 'gerrit.trigger.hudsontrigger.data.Branch')
  410. XML.SubElement(gbranch, 'compareType').text = get_compare_type(
  411. 'branch-compare-type', branch.get(
  412. 'branch-compare-type', 'PLAIN'))
  413. XML.SubElement(gbranch, 'pattern').text = branch['branch-pattern']
  414. project_file_paths = project.get('file-paths', [])
  415. if project_file_paths:
  416. fps_tag = XML.SubElement(gproj, 'filePaths')
  417. for file_path in project_file_paths:
  418. fp_tag = XML.SubElement(fps_tag,
  419. 'com.sonyericsson.hudson.plugins.'
  420. 'gerrit.trigger.hudsontrigger.data.'
  421. 'FilePath')
  422. XML.SubElement(fp_tag, 'compareType').text = get_compare_type(
  423. 'compare-type', file_path.get('compare-type', 'PLAIN'))
  424. XML.SubElement(fp_tag, 'pattern').text = file_path['pattern']
  425. project_forbidden_file_paths = project.get('forbidden-file-paths', [])
  426. if project_forbidden_file_paths:
  427. ffps_tag = XML.SubElement(gproj, 'forbiddenFilePaths')
  428. for forbidden_file_path in project_forbidden_file_paths:
  429. ffp_tag = XML.SubElement(ffps_tag,
  430. 'com.sonyericsson.hudson.plugins.'
  431. 'gerrit.trigger.hudsontrigger.data.'
  432. 'FilePath')
  433. XML.SubElement(ffp_tag, 'compareType').text = get_compare_type(
  434. 'compare-type', forbidden_file_path.get('compare-type',
  435. 'PLAIN'))
  436. XML.SubElement(ffp_tag, 'pattern').text = \
  437. forbidden_file_path['pattern']
  438. topics = project.get('topics', [])
  439. if topics:
  440. topics_tag = XML.SubElement(gproj, 'topics')
  441. for topic in topics:
  442. topic_tag = XML.SubElement(topics_tag,
  443. 'com.sonyericsson.hudson.plugins.'
  444. 'gerrit.trigger.hudsontrigger.data.'
  445. 'Topic')
  446. XML.SubElement(topic_tag, 'compareType').text = \
  447. get_compare_type('compare-type', topic.get('compare-type',
  448. 'PLAIN'))
  449. XML.SubElement(topic_tag, 'pattern').text = topic['pattern']
  450. XML.SubElement(gproj,
  451. 'disableStrictForbiddenFileVerification').text = str(
  452. project.get('disable-strict-forbidden-file-verification',
  453. False)).lower()
  454. build_gerrit_skip_votes(gtrig, data)
  455. general_mappings = [
  456. ('silent', 'silentMode', False),
  457. ('silent-start', 'silentStartMode', False),
  458. ('escape-quotes', 'escapeQuotes', True),
  459. ('no-name-and-email', 'noNameAndEmailParameters', False),
  460. ('readable-message', 'readableMessage', False),
  461. ('dependency-jobs', 'dependencyJobsNames', ''),
  462. ]
  463. convert_mapping_to_xml(gtrig, data, general_mappings, fail_required=True)
  464. notification_levels = ['NONE', 'OWNER', 'OWNER_REVIEWERS', 'ALL',
  465. 'SERVER_DEFAULT']
  466. notification_level = data.get('notification-level', 'SERVER_DEFAULT')
  467. if notification_level not in notification_levels:
  468. raise InvalidAttributeError('notification-level', notification_level,
  469. notification_levels)
  470. if notification_level == 'SERVER_DEFAULT':
  471. XML.SubElement(gtrig, 'notificationLevel').text = ''
  472. else:
  473. XML.SubElement(gtrig, 'notificationLevel').text = notification_level
  474. XML.SubElement(gtrig, 'dynamicTriggerConfiguration').text = str(
  475. data.get('dynamic-trigger-enabled', False))
  476. XML.SubElement(gtrig, 'triggerConfigURL').text = str(
  477. data.get('dynamic-trigger-url', ''))
  478. XML.SubElement(gtrig, 'triggerInformationAction').text = str(
  479. data.get('trigger-information-action', ''))
  480. XML.SubElement(gtrig, 'allowTriggeringUnreviewedPatches').text = str(
  481. data.get('trigger-for-unreviewed-patches', False)).lower()
  482. build_gerrit_triggers(gtrig, data)
  483. override = str(data.get('override-votes', False)).lower()
  484. if override == 'true':
  485. for yamlkey, xmlkey in [('gerrit-build-started-verified-value',
  486. 'gerritBuildStartedVerifiedValue'),
  487. ('gerrit-build-successful-verified-value',
  488. 'gerritBuildSuccessfulVerifiedValue'),
  489. ('gerrit-build-failed-verified-value',
  490. 'gerritBuildFailedVerifiedValue'),
  491. ('gerrit-build-unstable-verified-value',
  492. 'gerritBuildUnstableVerifiedValue'),
  493. ('gerrit-build-notbuilt-verified-value',
  494. 'gerritBuildNotBuiltVerifiedValue'),
  495. ('gerrit-build-started-codereview-value',
  496. 'gerritBuildStartedCodeReviewValue'),
  497. ('gerrit-build-successful-codereview-value',
  498. 'gerritBuildSuccessfulCodeReviewValue'),
  499. ('gerrit-build-failed-codereview-value',
  500. 'gerritBuildFailedCodeReviewValue'),
  501. ('gerrit-build-unstable-codereview-value',
  502. 'gerritBuildUnstableCodeReviewValue'),
  503. ('gerrit-build-notbuilt-codereview-value',
  504. 'gerritBuildNotBuiltCodeReviewValue')]:
  505. if data.get(yamlkey) is not None:
  506. # str(int(x)) makes input values like '+1' work
  507. XML.SubElement(gtrig, xmlkey).text = str(
  508. int(data.get(yamlkey)))
  509. message_mappings = [
  510. ('start-message', 'buildStartMessage', ''),
  511. ('failure-message', 'buildFailureMessage', ''),
  512. ('successful-message', 'buildSuccessfulMessage', ''),
  513. ('unstable-message', 'buildUnstableMessage', ''),
  514. ('notbuilt-message', 'buildNotBuiltMessage', ''),
  515. ('failure-message-file', 'buildUnsuccessfulFilepath', ''),
  516. ('custom-url', 'customUrl', ''),
  517. ('server-name', 'serverName', '__ANY__'),
  518. ]
  519. convert_mapping_to_xml(gtrig, data, message_mappings, fail_required=True)
  520. def dockerhub_notification(registry, xml_parent, data):
  521. """yaml: dockerhub-notification
  522. The job will get triggered when Docker Hub/Registry notifies
  523. that Docker image(s) used in this job has been rebuilt.
  524. Requires the Jenkins :jenkins-wiki:`CloudBees Docker Hub Notification
  525. <CloudBees+Docker+Hub+Notification>`.
  526. :arg bool referenced-image: Trigger the job based on repositories
  527. used by any compatible docker plugin in this job. (default true)
  528. :arg list repositories: Specified repositories to trigger the job.
  529. (default [])
  530. Minimal Example:
  531. .. literalinclude::
  532. /../../tests/triggers/fixtures/dockerhub-notification-minimal.yaml
  533. :language: yaml
  534. Full Example:
  535. .. literalinclude::
  536. /../../tests/triggers/fixtures/dockerhub-notification-full.yaml
  537. :language: yaml
  538. """
  539. dockerhub = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.'
  540. 'registry.notification.DockerHubTrigger')
  541. dockerhub.set('plugin', 'dockerhub-notification')
  542. option = XML.SubElement(dockerhub, 'options', {'class': 'vector'})
  543. if data.get('referenced-image'):
  544. XML.SubElement(option, 'org.jenkinsci.plugins.'
  545. 'registry.notification.'
  546. 'opt.impl.TriggerForAllUsedInJob')
  547. repos = data.get('repositories', [])
  548. if repos:
  549. specified_names = XML.SubElement(option,
  550. 'org.jenkinsci.plugins.registry.'
  551. 'notification.opt.impl.'
  552. 'TriggerOnSpecifiedImageNames')
  553. repo_tag = XML.SubElement(specified_names, 'repoNames')
  554. for repo in repos:
  555. XML.SubElement(repo_tag, 'string').text = repo
  556. def pollscm(registry, xml_parent, data):
  557. """yaml: pollscm
  558. Poll the SCM to determine if there has been a change.
  559. :Parameter: the polling interval (cron syntax)
  560. .. deprecated:: 1.3.0. Please use :ref:`cron <cron>`.
  561. .. _cron:
  562. :arg string cron: the polling interval (cron syntax, required)
  563. :arg bool ignore-post-commit-hooks: Ignore changes notified by SCM
  564. post-commit hooks. The subversion-plugin supports this since
  565. version 1.44. (default false)
  566. Example:
  567. .. literalinclude:: /../../tests/triggers/fixtures/pollscm002.yaml
  568. :language: yaml
  569. """
  570. try:
  571. cron = data['cron']
  572. ipch = str(data.get('ignore-post-commit-hooks', False)).lower()
  573. except KeyError as e:
  574. # ensure specific error on the attribute not being set is raised
  575. # for new format
  576. raise MissingAttributeError(e)
  577. except TypeError:
  578. # To keep backward compatibility
  579. logger.warning(
  580. "Your pollscm usage is deprecated, please use"
  581. " the syntax described in the documentation"
  582. " instead")
  583. cron = data
  584. ipch = 'false'
  585. if not cron and cron != '':
  586. raise InvalidAttributeError('cron', cron)
  587. scmtrig = XML.SubElement(xml_parent, 'hudson.triggers.SCMTrigger')
  588. XML.SubElement(scmtrig, 'spec').text = cron
  589. XML.SubElement(scmtrig, 'ignorePostCommitHooks').text = ipch
  590. def build_content_type(xml_parent, entries, namespace, collection_suffix,
  591. entry_suffix, prefix, collection_name, element_name):
  592. content_type = XML.SubElement(
  593. xml_parent, '{0}.{1}{2}'.format(namespace, prefix, collection_suffix))
  594. if entries:
  595. collection = XML.SubElement(content_type, collection_name)
  596. for entry in entries:
  597. content_entry = XML.SubElement(
  598. collection, '{0}.{1}{2}'.format(namespace, prefix,
  599. entry_suffix))
  600. XML.SubElement(content_entry, element_name).text = entry
  601. def pollurl(registry, xml_parent, data):
  602. """yaml: pollurl
  603. Trigger when the HTTP response from a URL changes.
  604. Requires the Jenkins :jenkins-wiki:`URLTrigger Plugin <URLTrigger+Plugin>`.
  605. :arg string cron: cron syntax of when to run (default '')
  606. :arg string polling-node: Restrict where the polling should run.
  607. (optional)
  608. :arg list urls: List of URLs to monitor
  609. :URL: * **url** (`str`) -- URL to monitor for changes (required)
  610. * **proxy** (`bool`) -- Activate the Jenkins proxy (default false)
  611. * **timeout** (`int`) -- Connect/read timeout in seconds
  612. (default 300)
  613. * **username** (`string`) -- User name for basic authentication
  614. (optional)
  615. * **password** (`string`) -- Password for basic authentication
  616. (optional)
  617. * **check-status** (`int`) -- Check for a specific HTTP status
  618. code (optional)
  619. * **check-etag** (`bool`) -- Check the HTTP ETag for changes
  620. (default false)
  621. * **check-date** (`bool`) -- Check the last modification date of
  622. the URL (default false)
  623. * **check-content** (`list`) -- List of content type changes to
  624. monitor
  625. :Content Type: * **simple** (`bool`) -- Trigger on any change to
  626. the content of the URL (default false)
  627. * **json** (`list`) -- Trigger on any change to
  628. the listed JSON paths
  629. * **text** (`list`) -- Trigger on any change to
  630. the listed regular expressions
  631. * **xml** (`list`) -- Trigger on any change to
  632. the listed XPath expressions
  633. Example:
  634. .. literalinclude:: /../../tests/triggers/fixtures/pollurl001.yaml
  635. """
  636. namespace = 'org.jenkinsci.plugins.urltrigger.'
  637. valid_content_types = {
  638. 'simple': ['Simple', '', '', []],
  639. 'json': ['JSON', 'jsonPaths', 'jsonPath', None],
  640. 'text': ['TEXT', 'regExElements', 'regEx', None],
  641. 'xml': ['XML', 'xPaths', 'xPath', None]
  642. }
  643. urltrig = XML.SubElement(xml_parent,
  644. namespace + 'URLTrigger')
  645. node = data.get('polling-node')
  646. XML.SubElement(urltrig, 'spec').text = data.get('cron', '')
  647. XML.SubElement(urltrig, 'labelRestriction').text = str(bool(node)).lower()
  648. if node:
  649. XML.SubElement(urltrig, 'triggerLabel').text = node
  650. entries = XML.SubElement(urltrig, 'entries')
  651. urls = data.get('urls', [])
  652. if not urls:
  653. raise JenkinsJobsException('At least one url must be provided')
  654. for url in urls:
  655. entry = XML.SubElement(entries, namespace + 'URLTriggerEntry')
  656. XML.SubElement(entry, 'url').text = url['url']
  657. XML.SubElement(entry, 'proxyActivated').text = \
  658. str(url.get('proxy', False)).lower()
  659. if 'username' in url:
  660. XML.SubElement(entry, 'username').text = url['username']
  661. if 'password' in url:
  662. XML.SubElement(entry, 'password').text = url['password']
  663. if 'check-status' in url:
  664. XML.SubElement(entry, 'checkStatus').text = 'true'
  665. XML.SubElement(entry, 'statusCode').text = \
  666. str(url.get('check-status'))
  667. else:
  668. XML.SubElement(entry, 'checkStatus').text = 'false'
  669. XML.SubElement(entry, 'statusCode').text = '200'
  670. XML.SubElement(entry, 'timeout').text = \
  671. str(url.get('timeout', 300))
  672. XML.SubElement(entry, 'checkETag').text = \
  673. str(url.get('check-etag', False)).lower()
  674. XML.SubElement(entry, 'checkLastModificationDate').text = \
  675. str(url.get('check-date', False)).lower()
  676. check_content = url.get('check-content', [])
  677. XML.SubElement(entry, 'inspectingContent').text = \
  678. str(bool(check_content)).lower()
  679. content_types = XML.SubElement(entry, 'contentTypes')
  680. for entry in check_content:
  681. type_name = next(iter(entry.keys()))
  682. if type_name not in valid_content_types:
  683. raise JenkinsJobsException('check-content must be one of : %s'
  684. % ', '.join(valid_content_types.
  685. keys()))
  686. content_type = valid_content_types.get(type_name)
  687. if entry[type_name]:
  688. sub_entries = content_type[3]
  689. if sub_entries is None:
  690. sub_entries = entry[type_name]
  691. build_content_type(content_types, sub_entries,
  692. namespace + 'content', 'ContentType',
  693. 'ContentEntry', *content_type[0:3])
  694. def jms_messaging(registry, xml_parent, data):
  695. """yaml: jms-messaging
  696. The JMS Messaging Plugin provides the following functionality:
  697. - A build trigger to submit jenkins jobs upon receipt
  698. of a matching message.
  699. - A builder that may be used to submit a message to the topic
  700. upon the completion of a job
  701. - A post-build action that may be used to submit a message to the topic
  702. upon the completion of a job
  703. JMS Messaging provider types supported:
  704. - ActiveMQ
  705. - FedMsg
  706. Requires the Jenkins :jenkins-wiki:`JMS Messaging Plugin
  707. <JMS+Messaging+Plugin>`.
  708. :arg str selector: The JSON or YAML formatted text that conforms to
  709. the schema for defining the various OpenShift resources. (default '')
  710. note: topic needs to be in double quotes
  711. ex. topic = "org.fedoraproject.prod.fedimg.image.upload"
  712. :arg str provider-name: Name of message provider setup in the
  713. global config. (default '')
  714. :arg list checks: List of checks to monitor. (default [])
  715. :arg str field: Check the body of messages for a field. (default '')
  716. :arg str expected-value: Expected value for the field. regex (default '')
  717. Full Example:
  718. .. literalinclude::
  719. ../../tests/triggers/fixtures/jms-messaging001.yaml
  720. :language: yaml
  721. Minimal Example:
  722. .. literalinclude::
  723. ../../tests/triggers/fixtures/jms-messaging002.yaml
  724. :language: yaml
  725. """
  726. namespace = 'com.redhat.jenkins.plugins.ci.'
  727. jmsm = XML.SubElement(xml_parent,
  728. namespace + 'CIBuildTrigger')
  729. mapping = [
  730. # option, xml name, default value
  731. ("spec", 'spec', ''),
  732. ("selector", 'selector', ''),
  733. ("provider-name", 'providerName', ''),
  734. ]
  735. convert_mapping_to_xml(jmsm, data, mapping, fail_required=True)
  736. checks = data.get('checks', [])
  737. if len(checks) > 0:
  738. msgchecks = XML.SubElement(jmsm, 'checks')
  739. for check in checks:
  740. msgcheck = XML.SubElement(msgchecks, namespace +
  741. 'messaging.checks.MsgCheck')
  742. mapping = [
  743. ('field', 'field', ''),
  744. ('expected-value', 'expectedValue', '')]
  745. convert_mapping_to_xml(
  746. msgcheck, check, mapping, fail_required=True)
  747. def timed(registry, xml_parent, data):
  748. """yaml: timed
  749. Trigger builds at certain times.
  750. :Parameter: when to run the job (cron syntax)
  751. Example::
  752. triggers:
  753. - timed: "@midnight"
  754. """
  755. scmtrig = XML.SubElement(xml_parent, 'hudson.triggers.TimerTrigger')
  756. XML.SubElement(scmtrig, 'spec').text = data
  757. def bitbucket(registry, xml_parent, data):
  758. """yaml: bitbucket
  759. Trigger a job when bitbucket repository is pushed to.
  760. Requires the Jenkins :jenkins-wiki:`BitBucket Plugin
  761. <BitBucket+Plugin>`.
  762. Example:
  763. .. literalinclude:: /../../tests/triggers/fixtures/bitbucket.yaml
  764. """
  765. bbtrig = XML.SubElement(xml_parent, 'com.cloudbees.jenkins.'
  766. 'plugins.BitBucketTrigger')
  767. XML.SubElement(bbtrig, 'spec').text = ''
  768. def github(registry, xml_parent, data):
  769. """yaml: github
  770. Trigger a job when github repository is pushed to.
  771. Requires the Jenkins :jenkins-wiki:`GitHub Plugin <GitHub+Plugin>`.
  772. Example::
  773. triggers:
  774. - github
  775. """
  776. ghtrig = XML.SubElement(xml_parent, 'com.cloudbees.jenkins.'
  777. 'GitHubPushTrigger')
  778. XML.SubElement(ghtrig, 'spec').text = ''
  779. def github_pull_request(registry, xml_parent, data):
  780. """yaml: github-pull-request
  781. Build pull requests in github and report results.
  782. Requires the Jenkins :jenkins-wiki:`GitHub Pull Request Builder Plugin
  783. <GitHub+pull+request+builder+plugin>`.
  784. :arg list admin-list: the users with admin rights (optional)
  785. :arg list white-list: users whose pull requests build (optional)
  786. :arg list org-list: orgs whose users should be white listed (optional)
  787. :arg bool allow-whitelist-orgs-as-admins: members of white listed orgs
  788. will have admin rights. (default false)
  789. :arg string cron: cron syntax of when to run (optional)
  790. :arg string trigger-phrase: when filled, commenting this phrase
  791. in the pull request will trigger a build (optional)
  792. :arg bool only-trigger-phrase: only commenting the trigger phrase
  793. in the pull request will trigger a build (default false)
  794. :arg string skip-build-phrase: when filled, adding this phrase to
  795. the pull request title or body will not trigger a build (optional)
  796. :arg string black-list-labels: list of GitHub labels for which the build
  797. should not be triggered (optional)
  798. :arg string white-list-labels: list of GitHub labels for which the build
  799. should only be triggered. (Leave blank for 'any') (optional)
  800. :arg bool github-hooks: use github hook (default false)
  801. :arg bool permit-all: build every pull request automatically
  802. without asking (default false)
  803. :arg bool auto-close-on-fail: close failed pull request automatically
  804. (default false)
  805. :arg list white-list-target-branches: Adding branches to this whitelist
  806. allows you to selectively test pull requests destined for these
  807. branches only. Supports regular expressions (e.g. 'master',
  808. 'feature-.*'). (optional)
  809. :arg list black-list-target-branches: Adding branches to this blacklist
  810. allows you to selectively prevent pull requests builds destined for
  811. these branches. Supports regular expressions (e.g. 'master',
  812. 'feature-.*'). (optional)
  813. :arg string auth-id: the auth id to use (optional)
  814. :arg string build-desc-template: the template for build descriptions in
  815. jenkins (optional)
  816. :arg string status-context: the context to include on PR status comments
  817. (optional)
  818. :arg string triggered-status: the status message to set when the build has
  819. been triggered (optional)
  820. :arg string started-status: the status comment to set when the build has
  821. been started (optional)
  822. :arg string status-url: the status URL to set (optional)
  823. :arg bool status-add-test-results: add test result one-liner to status
  824. message (optional)
  825. :arg string success-status: the status message to set if the job succeeds
  826. (optional)
  827. :arg string failure-status: the status message to set if the job fails
  828. (optional)
  829. :arg string error-status: the status message to set if the job errors
  830. (optional)
  831. :arg string success-comment: comment to add to the PR on a successful job
  832. (optional)
  833. :arg string failure-comment: comment to add to the PR on a failed job
  834. (optional)
  835. :arg string error-comment: comment to add to the PR on an errored job
  836. (optional)
  837. :arg bool cancel-builds-on-update: cancel existing builds when a PR is
  838. updated (optional)
  839. :arg list included-regions: Each inclusion uses regular expression pattern
  840. matching, and must be separated by a new line. An empty list implies
  841. that everything is included. (optional)
  842. :arg list excluded-regions: Each exclusion uses regular expression pattern
  843. matching, and must be separated by a new line. Exclusions take
  844. precedence over inclusions, if there is an overlap between included
  845. and excluded regions. (optional)
  846. Full Example:
  847. .. literalinclude::
  848. /../../tests/triggers/fixtures/github-pull-request-full.yaml
  849. :language: yaml
  850. Minimal Example:
  851. .. literalinclude::
  852. /../../tests/triggers/fixtures/github-pull-request-minimal.yaml
  853. :language: yaml
  854. """
  855. ghprb = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.ghprb.'
  856. 'GhprbTrigger')
  857. XML.SubElement(ghprb, 'spec').text = data.get('cron', '')
  858. admin_string = "\n".join(data.get('admin-list', []))
  859. XML.SubElement(ghprb, 'adminlist').text = admin_string
  860. XML.SubElement(ghprb, 'allowMembersOfWhitelistedOrgsAsAdmin').text = str(
  861. data.get('allow-whitelist-orgs-as-admins', False)).lower()
  862. white_string = "\n".join(data.get('white-list', []))
  863. XML.SubElement(ghprb, 'whitelist').text = white_string
  864. org_string = "\n".join(data.get('org-list', []))
  865. XML.SubElement(ghprb, 'orgslist').text = org_string
  866. white_list_labels_string = "\n".join(data.get('white-list-labels', []))
  867. XML.SubElement(ghprb, 'whiteListLabels').text = white_list_labels_string
  868. black_list_labels_string = "\n".join(data.get('black-list-labels', []))
  869. XML.SubElement(ghprb, 'blackListLabels').text = black_list_labels_string
  870. XML.SubElement(ghprb, 'cron').text = data.get('cron', '')
  871. excluded_regions_string = "\n".join(data.get('excluded-regions', []))
  872. XML.SubElement(ghprb, 'excludedRegions').text = excluded_regions_string
  873. included_regions_string = "\n".join(data.get('included-regions', []))
  874. XML.SubElement(ghprb, 'includedRegions').text = included_regions_string
  875. build_desc_template = data.get('build-desc-template', '')
  876. if build_desc_template:
  877. XML.SubElement(ghprb, 'buildDescTemplate').text = str(
  878. build_desc_template)
  879. XML.SubElement(ghprb, 'triggerPhrase').text = \
  880. data.get('trigger-phrase', '')
  881. XML.SubElement(ghprb, 'skipBuildPhrase').text = str(
  882. data.get('skip-build-phrase', '')).lower()
  883. XML.SubElement(ghprb, 'onlyTriggerPhrase').text = str(
  884. data.get('only-trigger-phrase', False)).lower()
  885. XML.SubElement(ghprb, 'useGitHubHooks').text = str(
  886. data.get('github-hooks', False)).lower()
  887. XML.SubElement(ghprb, 'permitAll').text = str(
  888. data.get('permit-all', False)).lower()
  889. XML.SubElement(ghprb, 'autoCloseFailedPullRequests').text = str(
  890. data.get('auto-close-on-fail', False)).lower()
  891. white_list_target_branches = data.get('white-list-target-branches', [])
  892. if white_list_target_branches:
  893. ghprb_wltb = XML.SubElement(ghprb, 'whiteListTargetBranches')
  894. for branch in white_list_target_branches:
  895. be = XML.SubElement(ghprb_wltb, 'org.jenkinsci.plugins.'
  896. 'ghprb.GhprbBranch')
  897. XML.SubElement(be, 'branch').text = str(branch)
  898. black_list_target_branches = data.get('black-list-target-branches', [])
  899. if black_list_target_branches:
  900. ghprb_bltb = XML.SubElement(ghprb, 'blackListTargetBranches')
  901. for branch in black_list_target_branches:
  902. be = XML.SubElement(ghprb_bltb, 'org.jenkinsci.plugins.'
  903. 'ghprb.GhprbBranch')
  904. XML.SubElement(be, 'branch').text = str(branch)
  905. auth_id = data.get('auth-id', '')
  906. if auth_id:
  907. XML.SubElement(ghprb, 'gitHubAuthId').text = str(auth_id)
  908. # PR status update fields
  909. status_context = data.get('status-context', '')
  910. triggered_status = data.get('triggered-status', '')
  911. started_status = data.get('started-status', '')
  912. status_url = data.get('status-url', '')
  913. status_add_test_results = data.get('status-add-test-results', '')
  914. success_status = data.get('success-status', '')
  915. failure_status = data.get('failure-status', '')
  916. error_status = data.get('error-status', '')
  917. # is status handling is required?
  918. requires_status = (
  919. status_context or
  920. triggered_status or
  921. started_status or
  922. status_url or
  923. status_add_test_results or
  924. success_status or
  925. failure_status or
  926. error_status
  927. )
  928. # is status message handling required?
  929. requires_status_message = (
  930. success_status or
  931. failure_status or
  932. error_status
  933. )
  934. # is comment handling required?
  935. success_comment = data.get('success-comment', '')
  936. failure_comment = data.get('failure-comment', '')
  937. error_comment = data.get('error-comment', '')
  938. requires_job_comment = (
  939. success_comment or
  940. failure_comment or
  941. error_comment
  942. )
  943. cancel_builds_on_update = data.get('cancel-builds-on-update', False)
  944. # We want to have only one 'extensions' subelement, even if status
  945. # handling, comment handling and other extensions are enabled.
  946. if requires_status or requires_job_comment or cancel_builds_on_update:
  947. extensions = XML.SubElement(ghprb, 'extensions')
  948. # Both comment and status elements have this same type. Using a const is
  949. # much easier to read than repeating the tokens for this class each time
  950. # it's used
  951. comment_type = 'org.jenkinsci.plugins.ghprb.extensions.comments.'
  952. comment_type = comment_type + 'GhprbBuildResultMessage'
  953. if requires_status:
  954. simple_status = XML.SubElement(extensions,
  955. 'org.jenkinsci.plugins'
  956. '.ghprb.extensions.status.'
  957. 'GhprbSimpleStatus')
  958. if status_context:
  959. XML.SubElement(simple_status, 'commitStatusContext').text = str(
  960. status_context)
  961. if triggered_status:
  962. XML.SubElement(simple_status, 'triggeredStatus').text = str(
  963. triggered_status)
  964. if started_status:
  965. XML.SubElement(simple_status, 'startedStatus').text = str(
  966. started_status)
  967. if status_url:
  968. XML.SubElement(simple_status, 'statusUrl').text = str(
  969. status_url)
  970. if status_add_test_results:
  971. XML.SubElement(simple_status, 'addTestResults').text = str(
  972. status_add_test_results).lower()
  973. if requires_status_message:
  974. completed_elem = XML.SubElement(simple_status, 'completedStatus')
  975. if success_status:
  976. success_elem = XML.SubElement(completed_elem, comment_type)
  977. XML.SubElement(success_elem, 'message').text = str(
  978. success_status)
  979. XML.SubElement(success_elem, 'result').text = 'SUCCESS'
  980. if failure_status:
  981. failure_elem = XML.SubElement(completed_elem, comment_type)
  982. XML.SubElement(failure_elem, 'message').text = str(
  983. failure_status)
  984. XML.SubElement(failure_elem, 'result').text = 'FAILURE'
  985. if error_status:
  986. error_elem = XML.SubElement(completed_elem, comment_type)
  987. XML.SubElement(error_elem, 'message').text = str(error_status)
  988. XML.SubElement(error_elem, 'result').text = 'ERROR'
  989. # job comment handling
  990. if requires_job_comment:
  991. build_status = XML.SubElement(extensions,
  992. 'org.jenkinsci.plugins.ghprb.extensions'
  993. '.comments.'
  994. 'GhprbBuildStatus')
  995. messages_elem = XML.SubElement(build_status, 'messages')
  996. if success_comment:
  997. success_comment_elem = XML.SubElement(messages_elem, comment_type)
  998. XML.SubElement(success_comment_elem, 'message').text = str(
  999. success_comment)
  1000. XML.SubElement(success_comment_elem, 'result').text = 'SUCCESS'
  1001. if failure_comment:
  1002. failure_comment_elem = XML.SubElement(messages_elem, comment_type)
  1003. XML.SubElement(failure_comment_elem, 'message').text = str(
  1004. failure_comment)
  1005. XML.SubElement(failure_comment_elem, 'result').text = 'FAILURE'
  1006. if error_comment:
  1007. error_comment_elem = XML.SubElement(messages_elem, comment_type)
  1008. XML.SubElement(error_comment_elem, 'message').text = str(
  1009. error_comment)
  1010. XML.SubElement(error_comment_elem, 'result').text = 'ERROR'
  1011. if cancel_builds_on_update:
  1012. XML.SubElement(extensions,
  1013. 'org.jenkinsci.plugins.ghprb.extensions.'
  1014. 'build.GhprbCancelBuildsOnUpdate')
  1015. def gitlab_merge_request(registry, xml_parent, data):
  1016. """yaml: gitlab-merge-request
  1017. Build merge requests in gitlab and report results.
  1018. Requires the Jenkins :jenkins-wiki:`Gitlab MergeRequest Builder Plugin.
  1019. <Gitlab+Merge+Request+Builder+Plugin>`.
  1020. :arg string cron: Cron syntax of when to run (required)
  1021. :arg string project-path: Gitlab-relative path to project (required)
  1022. :arg string use-http-url: Use the HTTP(S) URL to fetch/clone repository
  1023. (default false)
  1024. :arg string assignee-filter: Only MRs with this assigned user will
  1025. trigger the build automatically (default 'jenkins')
  1026. :arg string tag-filter: Only MRs with this label will trigger the build
  1027. automatically (default 'Build')
  1028. :arg string trigger-comment: Force build if this comment is the last
  1029. in merge reguest (default '')
  1030. :arg string publish-build-progress-messages: Publish build progress
  1031. messages (except build failed) (default true)
  1032. :arg string auto-close-failed: On failure, auto close the request
  1033. (default false)
  1034. :arg string auto-merge-passed: On success, auto merge the request
  1035. (default false)
  1036. Example:
  1037. .. literalinclude:: \
  1038. /../../tests/triggers/fixtures/gitlab-merge-request.yaml
  1039. """
  1040. ghprb = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.gitlab.'
  1041. 'GitlabBuildTrigger')
  1042. # Because of a design limitation in the GitlabBuildTrigger Jenkins plugin
  1043. # both 'spec' and '__cron' have to be set to the same value to have them
  1044. # take effect. Also, cron and projectPath are prefixed with underscores
  1045. # in the plugin, but spec is not.
  1046. mapping = [
  1047. ('cron', 'spec', None),
  1048. ('cron', '__cron', None),
  1049. ('project-path', '__projectPath', None),
  1050. ('use-http-url', '__useHttpUrl', False),
  1051. ('assignee-filter', '__assigneeFilter', 'jenkins'),
  1052. ('tag-filter', '__tagFilter', 'Build'),
  1053. ('trigger-comment', '__triggerComment', ''),
  1054. ('publish-build-progress-messages', '__publishBuildProgressMessages',
  1055. True),
  1056. ('auto-close-failed', '__autoCloseFailed', False),
  1057. ('auto-merge-passed', '__autoMergePassed', False)
  1058. ]
  1059. convert_mapping_to_xml(ghprb, data, mapping, True)
  1060. def gitlab(registry, xml_parent, data):
  1061. """yaml: gitlab
  1062. Makes Jenkins act like a GitLab CI server.
  1063. Requires the Jenkins :jenkins-wiki:`GitLab Plugin
  1064. <GitLab+Plugin>`.
  1065. :arg bool trigger-push: Build on Push Events (default true)
  1066. :arg bool trigger-merge-request: Build on Merge Request Events (default
  1067. true)
  1068. :arg bool trigger-accepted-merge-request: Build on Accepted Merge Request
  1069. Events (>= 1.4.6) (default false)
  1070. :arg bool trigger-closed-merge-request: Build on Closed Merge Request
  1071. Events (>= 1.4.6) (default false)
  1072. :arg str trigger-open-merge-request-push: Rebuild open Merge Requests
  1073. on Push Events.
  1074. :trigger-open-merge-request-push values (< 1.1.26):
  1075. * **true** (default)
  1076. * **false**
  1077. :trigger-open-merge-request-push values (>= 1.1.26):
  1078. * **never** (default)
  1079. * **source**
  1080. * **both**
  1081. :arg bool trigger-note: Build when comment is added with defined phrase
  1082. (>= 1.2.4) (default true)
  1083. :arg str note-regex: Phrase that triggers the build (>= 1.2.4) (default
  1084. 'Jenkins please retry a build')
  1085. :arg bool ci-skip: Enable skipping builds of commits that contain
  1086. [ci-skip] in the commit message (default true)
  1087. :arg bool wip-skip: Enable skipping builds of WIP Merge Requests (>= 1.2.4)
  1088. (default true)
  1089. :arg bool set-build-description: Set build description to build cause
  1090. (eg. Merge request or Git Push) (default true)
  1091. :arg bool add-note-merge-request: Add note with build status on
  1092. merge requests (default true)
  1093. :arg bool add-vote-merge-request: Vote added to note with build status
  1094. on merge requests (>= 1.1.27) (default true)
  1095. :arg bool accept-merge-request-on-success: Automatically accept the Merge
  1096. Request if the build is successful (>= 1.1.27) (default false)
  1097. :arg bool add-ci-message: Add CI build status (1.1.28 - 1.2.0) (default
  1098. false)
  1099. :arg bool allow-all-branches: Allow all branches (Ignoring Filtered
  1100. Branches) (< 1.1.29) (default false)
  1101. :arg str branch-filter-type: Filter branches that can trigger a build.
  1102. Valid values and their additional attributes are described in the
  1103. `branch filter type`_ table (>= 1.1.29) (default 'All').
  1104. :arg list include-branches: Defined list of branches to include
  1105. (default [])
  1106. :arg list exclude-branches: Defined list of branches to exclude
  1107. (default [])
  1108. :arg str target-branch-regex: Regular expression to select branches
  1109. .. _`branch filter type`:
  1110. ================== ====================================================
  1111. Branch filter type Description
  1112. ================== ====================================================
  1113. All All branches are allowed to trigger this job.
  1114. NameBasedFilter Filter branches by name.
  1115. List source branches that are allowed to trigger a
  1116. build from a Push event or a Merge Request event. If
  1117. both fields are left empty, all branches are allowed
  1118. to trigger this job. For Merge Request events only
  1119. the target branch name is filtered out by the
  1120. **include-branches** and **exclude-branches** lists.
  1121. RegexBasedFilter Filter branches by regex
  1122. The target branch regex allows you to limit the
  1123. execution of this job to certain branches. Any
  1124. branch matching the specified pattern in
  1125. **target-branch-regex** triggers the job. No
  1126. filtering is performed if the field is left empty.
  1127. ================== ====================================================
  1128. Example (version < 1.1.26):
  1129. .. literalinclude:: /../../tests/triggers/fixtures/gitlab001.yaml
  1130. :language: yaml
  1131. Minimal example (version >= 1.1.26):
  1132. .. literalinclude:: /../../tests/triggers/fixtures/gitlab005.yaml
  1133. :language: yaml
  1134. Full example (version >= 1.1.26):
  1135. .. literalinclude:: /../../tests/triggers/fixtures/gitlab004.yaml
  1136. :language: yaml
  1137. """
  1138. def _add_xml(elem, name, value):
  1139. XML.SubElement(elem, name).text = value
  1140. gitlab = XML.SubElement(
  1141. xml_parent, 'com.dabsquared.gitlabjenkins.GitLabPushTrigger'
  1142. )
  1143. plugin_info = registry.get_plugin_info('GitLab Plugin')
  1144. # Note: Assume latest version of plugin is preferred config format
  1145. plugin_ver = pkg_resources.parse_version(
  1146. plugin_info.get('version', str(sys.maxsize)))
  1147. valid_merge_request = ['never', 'source', 'both']
  1148. if plugin_ver >= pkg_resources.parse_version("1.1.26"):
  1149. mapping = [
  1150. ('trigger-open-merge-request-push',
  1151. 'triggerOpenMergeRequestOnPush', 'never', valid_merge_request)]
  1152. convert_mapping_to_xml(gitlab, data, mapping, fail_required=True)
  1153. else:
  1154. mapping = [
  1155. ('trigger-open-merge-request-push',
  1156. 'triggerOpenMergeRequestOnPush', True)]
  1157. convert_mapping_to_xml(gitlab, data, mapping, fail_required=True)
  1158. if plugin_ver < pkg_resources.parse_version('1.2.0'):
  1159. if data.get('branch-filter-type', '') == 'All':
  1160. data['branch-filter-type'] = ''
  1161. valid_filters = ['', 'NameBasedFilter', 'RegexBasedFilter']
  1162. mapping = [
  1163. ('branch-filter-type', 'branchFilterName', '', valid_filters)]
  1164. convert_mapping_to_xml(gitlab, data, mapping, fail_required=True)
  1165. else:
  1166. valid_filters = ['All', 'NameBasedFilter', 'RegexBasedFilter']
  1167. mapping = [
  1168. ('branch-filter-type', 'branchFilterType', 'All', valid_filters)]
  1169. convert_mapping_to_xml(gitlab, data, mapping, fail_required=True)
  1170. XML.SubElement(gitlab, 'spec').text = ''
  1171. mapping = [
  1172. ('trigger-push', 'triggerOnPush', True),
  1173. ('trigger-merge-request', 'triggerOnMergeRequest', True),
  1174. ('trigger-accepted-merge-request', 'triggerOnAcceptedMergeRequest',
  1175. False),
  1176. ('trigger-closed-merge-request', 'triggerOnClosedMergeRequest', False),
  1177. ('trigger-note', 'triggerOnNoteRequest', True),
  1178. ('note-regex', 'noteRegex', 'Jenkins please retry a build'),
  1179. ('ci-skip', 'ciSkip', True),
  1180. ('wip-skip', 'skipWorkInProgressMergeRequest', True),
  1181. ('set-build-description', 'setBuildDescription', True),
  1182. ('add-note-merge-request', 'addNoteOnMergeRequest', True),
  1183. ('add-vote-merge-request', 'addVoteOnMergeRequest', True),
  1184. ('accept-merge-request-on-success', 'acceptMergeRequestOnSuccess',
  1185. False),
  1186. ('add-ci-message', 'addCiMessage', False),
  1187. ('allow-all-branches', 'allowAllBranches', False),
  1188. ('target-branch-regex', 'targetBranchRegex', '')
  1189. ]
  1190. list_mapping = (
  1191. ('include-branches', 'includeBranchesSpec', []),
  1192. ('exclude-branches', 'excludeBranchesSpec', []),
  1193. )
  1194. convert_mapping_to_xml(gitlab, data, mapping, fail_required=True)
  1195. for yaml_name, xml_name, default_val in list_mapping:
  1196. value = ', '.join(data.get(yaml_name, default_val))
  1197. _add_xml(gitlab, xml_name, value)
  1198. def build_result(registry, xml_parent, data):
  1199. """yaml: build-result
  1200. Configure jobB to monitor jobA build result. A build is scheduled if there
  1201. is a new build result that matches your criteria (unstable, failure, ...).
  1202. Requires the Jenkins :jenkins-wiki:`BuildResultTrigger Plugin
  1203. <BuildResultTrigger+Plugin>`.
  1204. :arg list groups: List groups of jobs and results to monitor for
  1205. :arg list jobs: The jobs to monitor (required)
  1206. :arg list results: Build results to monitor for (default success)
  1207. :arg bool combine: Combine all job information. A build will be
  1208. scheduled only if all conditions are met (default false)
  1209. :arg str cron: The cron syntax with which to poll the jobs for the
  1210. supplied result (default '')
  1211. Full Example:
  1212. .. literalinclude::
  1213. /../../tests/triggers/fixtures/build-result-full.yaml
  1214. :language: yaml
  1215. Minimal Example:
  1216. .. literalinclude::
  1217. /../../tests/triggers/fixtures/build-result-minimal.yaml
  1218. :language: yaml
  1219. """
  1220. brt = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.'
  1221. 'buildresulttrigger.BuildResultTrigger')
  1222. brt.set('plugin', 'buildresult-trigger')
  1223. mapping = [
  1224. ('cron', 'spec', ''),
  1225. ('combine', 'combinedJobs', False),
  1226. ]
  1227. convert_mapping_to_xml(brt, data, mapping, fail_required=True)
  1228. jobs_info = XML.SubElement(brt, 'jobsInfo')
  1229. result_dict = {'success': 'SUCCESS',
  1230. 'unstable': 'UNSTABLE',
  1231. 'failure': 'FAILURE',
  1232. 'not-built': 'NOT_BUILT',
  1233. 'aborted': 'ABORTED'}
  1234. for group in data['groups']:
  1235. brti = XML.SubElement(jobs_info, 'org.jenkinsci.plugins.'
  1236. 'buildresulttrigger.model.'
  1237. 'BuildResultTriggerInfo')
  1238. jobs_string = ",".join(group['jobs'])
  1239. mapping = [('', 'jobNames', jobs_string, group)]
  1240. convert_mapping_to_xml(brti, group, mapping, fail_required=True)
  1241. checked_results = XML.SubElement(brti, 'checkedResults')
  1242. for result in group.get('results', ['success']):
  1243. model_checked = XML.SubElement(checked_results, 'org.jenkinsci.'
  1244. 'plugins.buildresulttrigger.model.'
  1245. 'CheckedResult')
  1246. mapping = [('', 'checked', result, result_dict)]
  1247. convert_mapping_to_xml(
  1248. model_checked, result_dict, mapping, fail_required=True)
  1249. def reverse(registry, xml_parent, data):
  1250. """yaml: reverse
  1251. This trigger can be configured in the UI using the checkbox with the
  1252. following text: 'Build after other projects are built'.
  1253. Set up a trigger so that when some other projects finish building, a new
  1254. build is scheduled for this project. This is convenient for running an
  1255. extensive test after a build is complete, for example.
  1256. This configuration complements the "Build other projects" section in the
  1257. "Post-build Actions" of an upstream project, but is preferable when you
  1258. want to configure the downstream project.
  1259. :arg str jobs: List of jobs to watch. Can be either a comma separated
  1260. list or a list.
  1261. :arg str result: Build results to monitor for between the following
  1262. options: success, unstable and failure. (default 'success').
  1263. Example:
  1264. .. literalinclude:: /../../tests/triggers/fixtures/reverse.yaml
  1265. Example List:
  1266. .. literalinclude:: /../../tests/triggers/fixtures/reverse-list.yaml
  1267. """
  1268. reserveBuildTrigger = XML.SubElement(
  1269. xml_parent, 'jenkins.triggers.ReverseBuildTrigger')
  1270. supported_thresholds = ['SUCCESS', 'UNSTABLE', 'FAILURE']
  1271. XML.SubElement(reserveBuildTrigger, 'spec').text = ''
  1272. jobs = data.get('jobs')
  1273. if isinstance(jobs, list):
  1274. jobs = ",".join(jobs)
  1275. XML.SubElement(reserveBuildTrigger, 'upstreamProjects').text = \
  1276. jobs
  1277. threshold = XML.SubElement(reserveBuildTrigger, 'threshold')
  1278. result = str(data.get('result', 'success')).upper()
  1279. if result not in supported_thresholds:
  1280. raise jenkins_jobs.errors.JenkinsJobsException(
  1281. "Choice should be one of the following options: %s." %
  1282. ", ".join(supported_thresholds))
  1283. XML.SubElement(threshold, 'name').text = \
  1284. hudson_model.THRESHOLDS[result]['name']
  1285. XML.SubElement(threshold, 'ordinal').text = \
  1286. hudson_model.THRESHOLDS[result]['ordinal']
  1287. XML.SubElement(threshold, 'color').text = \
  1288. hudson_model.THRESHOLDS[result]['color']
  1289. XML.SubElement(threshold, 'completeBuild').text = \
  1290. str(hudson_model.THRESHOLDS[result]['complete']).lower()
  1291. def monitor_folders(registry, xml_parent, data):
  1292. """yaml: monitor-folders
  1293. Configure Jenkins to monitor folders.
  1294. Requires the Jenkins :jenkins-wiki:`Filesystem Trigger Plugin
  1295. <FSTrigger+Plugin>`.
  1296. :arg str path: Folder path to poll. (default '')
  1297. :arg list includes: Fileset includes setting that specifies the list of
  1298. includes files. Basedir of the fileset is relative to the workspace
  1299. root. If no value is set, all files are used. (default '')
  1300. :arg str excludes: The 'excludes' pattern. A file that matches this mask
  1301. will not be polled even if it matches the mask specified in 'includes'
  1302. section. (default '')
  1303. :arg bool check-modification-date: Check last modification date.
  1304. (default true)
  1305. :arg bool check-content: Check content. (default true)
  1306. :arg bool check-fewer: Check fewer files (default true)
  1307. :arg str cron: cron syntax of when to run (default '')
  1308. Full Example:
  1309. .. literalinclude::
  1310. /../../tests/triggers/fixtures/monitor-folders-full.yaml
  1311. :language: yaml
  1312. Minimal Example:
  1313. .. literalinclude::
  1314. /../../tests/triggers/fixtures/monitor-folders-minimal.yaml
  1315. :language: yaml
  1316. """
  1317. ft = XML.SubElement(xml_parent, ('org.jenkinsci.plugins.fstrigger.'
  1318. 'triggers.FolderContentTrigger'))
  1319. ft.set('plugin', 'fstrigger')
  1320. mappings = [
  1321. ('path', 'path', ''),
  1322. ('cron', 'spec', ''),
  1323. ]
  1324. convert_mapping_to_xml(ft, data, mappings, fail_required=True)
  1325. includes = data.get('includes', '')
  1326. XML.SubElement(ft, 'includes').text = ",".join(includes)
  1327. XML.SubElement(ft, 'excludes').text = data.get('excludes', '')
  1328. XML.SubElement(ft, 'excludeCheckLastModificationDate').text = str(
  1329. not data.get('check-modification-date', True)).lower()
  1330. XML.SubElement(ft, 'excludeCheckContent').text = str(
  1331. not data.get('check-content', True)).lower()
  1332. XML.SubElement(ft, 'excludeCheckFewerOrMoreFiles').text = str(
  1333. not data.get('check-fewer', True)).lower()
  1334. def monitor_files(registry, xml_parent, data):
  1335. """yaml: monitor-files
  1336. Configure Jenkins to monitor files.
  1337. Requires the Jenkins :jenkins-wiki:`Filesystem Trigger Plugin
  1338. <FSTrigger+Plugin>`.
  1339. :arg list files: List of files to monitor
  1340. :File:
  1341. * **path** (`str`) -- File path to monitor. You can use a pattern
  1342. that specifies a set of files if you don't know the real file
  1343. path. (required)
  1344. * **strategy** (`str`) -- Choose your strategy if there is more
  1345. than one matching file. Can be one of Ignore file ('IGNORE') or
  1346. Use the most recent ('LATEST'). (default 'LATEST')
  1347. * **check-content** (`list`) -- List of content changes of the
  1348. file to monitor
  1349. :Content Nature:
  1350. * **simple** (`bool`) -- Trigger on change in content of
  1351. the specified file (whatever the type file).
  1352. (default false)
  1353. * **jar** (`bool`) -- Trigger on change in content of the
  1354. specified JAR file. (default false)
  1355. * **tar** (`bool`) -- Trigger on change in content of the
  1356. specified Tar file. (default false)
  1357. * **zip** (`bool`) -- Trigger on change in content of the
  1358. specified ZIP file. (default false)
  1359. * **source-manifest** (`list`) -- Trigger on change to
  1360. MANIFEST files.
  1361. :MANIFEST File:
  1362. * **keys** (`list`) -- List of keys to inspect.
  1363. (optional)
  1364. * **all-keys** (`bool`) -- If true, take into
  1365. account all keys. (default true)
  1366. * **jar-manifest** (`list`) -- Trigger on change to
  1367. MANIFEST files (contained in jar files).
  1368. :MANIFEST File:
  1369. * **keys** (`list`) -- List of keys to inspect.
  1370. (optional)
  1371. * **all-keys** (`bool`) -- If true, take into
  1372. account all keys. (default true)
  1373. * **properties** (`list`) -- Monitor the contents of the
  1374. properties file.
  1375. :Properties File:
  1376. * **keys** (`list`) -- List of keys to inspect.
  1377. (optional)
  1378. * **all-keys** (`bool`) -- If true, take into
  1379. account all keys. (default true)
  1380. * **xml** (`list str`) -- Trigger on change to the listed
  1381. XPath expressions.
  1382. * **text** (`list str`) -- Trigger on change to the listed
  1383. regular expressions.
  1384. * **ignore-modificaton-date** (`bool`) -- If true, ignore the file
  1385. modification date. Only valid when content changes of the file
  1386. are being monitored. (default true)
  1387. :arg str cron: cron syntax of when to run (default '')
  1388. Minimal Example:
  1389. .. literalinclude::
  1390. /../../tests/triggers/fixtures/monitor-files-minimal.yaml
  1391. :language: yaml
  1392. Full Example:
  1393. .. literalinclude::
  1394. /../../tests/triggers/fixtures/monitor-files-full.yaml
  1395. :language: yaml
  1396. """
  1397. ft_prefix = 'org.jenkinsci.plugins.fstrigger.triggers.'
  1398. valid_strategies = ['LATEST', 'IGNORE']
  1399. valid_content_types = {
  1400. 'simple': ['Simple', '', '', []],
  1401. 'jar': ['JAR', '', '', []],
  1402. 'tar': ['Tar', '', '', []],
  1403. 'zip': ['ZIP', '', '', []],
  1404. 'source-manifest': ['SourceManifest'],
  1405. 'jar-manifest': ['JARManifest'],
  1406. 'properties': ['Properties'],
  1407. 'xml': ['XML', 'expressions', 'expression', None],
  1408. 'text': ['Text', 'regexElements', 'regex', None]
  1409. }
  1410. ft = XML.SubElement(xml_parent, ft_prefix + 'FileNameTrigger')
  1411. XML.SubElement(ft, 'spec').text = str(data.get('cron', ''))
  1412. files = data.get('files', [])
  1413. if not files:
  1414. raise JenkinsJobsException('At least one file must be provided')
  1415. files_tag = XML.SubElement(ft, 'fileInfo')
  1416. for file_info in files:
  1417. file_tag = XML.SubElement(files_tag, ft_prefix + 'FileNameTriggerInfo')
  1418. check_content = file_info.get('check-content', [])
  1419. files_mapping = [
  1420. ('path', 'filePathPattern', None),
  1421. ('strategy', 'strategy', 'LATEST', valid_strategies),
  1422. ('', 'inspectingContentFile', bool(check_content)),
  1423. ]
  1424. convert_mapping_to_xml(
  1425. file_tag, file_info, files_mapping, fail_required=True)
  1426. base_content_tag = XML.SubElement(file_tag, 'contentFileTypes')
  1427. for content in check_content:
  1428. type_name = next(iter(content.keys()))
  1429. if type_name not in valid_content_types:
  1430. raise InvalidAttributeError('check-content', type_name,
  1431. valid_content_types.keys())
  1432. content_type = valid_content_types.get(type_name)
  1433. if len(content_type) == 1:
  1434. class_name = '{0}filecontent.{1}FileContent'.format(
  1435. ft_prefix, content_type[0])
  1436. content_data = content.get(type_name)
  1437. if not content_data:
  1438. raise JenkinsJobsException("Need to specify something "
  1439. "under " + type_name)
  1440. for entry in content_data:
  1441. content_tag = XML.SubElement(base_content_tag, class_name)
  1442. keys = entry.get('keys', [])
  1443. if keys:
  1444. XML.SubElement(content_tag, 'keys2Inspect'
  1445. ).text = ",".join(keys)
  1446. XML.SubElement(content_tag, 'allKeys').text = str(
  1447. entry.get('all-keys', True)).lower()
  1448. else:
  1449. if content[type_name]:
  1450. sub_entries = content_type[3]
  1451. if sub_entries is None:
  1452. sub_entries = content[type_name]
  1453. build_content_type(base_content_tag, sub_entries,
  1454. ft_prefix + 'filecontent',
  1455. 'FileContent', 'FileContentEntry',
  1456. *content_type[0:3])
  1457. if bool(check_content):
  1458. XML.SubElement(file_tag,
  1459. 'doNotCheckLastModificationDate').text = str(
  1460. file_info.get('ignore-modificaton-date', True)).lower()
  1461. def ivy(registry, xml_parent, data):
  1462. """yaml: ivy
  1463. Poll with an Ivy script
  1464. Requires the Jenkins :jenkins-wiki:`IvyTrigger Plugin
  1465. <IvyTrigger+Plugin>`.
  1466. :arg str path: Path of the ivy file. (optional)
  1467. :arg str settings-path: Ivy Settings Path. (optional)
  1468. :arg list str properties-file: List of properties file path. Properties
  1469. will be injected as variables in the ivy settings file. (optional)
  1470. :arg str properties-content: Properties content. Properties will be
  1471. injected as variables in the ivy settings file. (optional)
  1472. :arg bool debug: Active debug mode on artifacts resolution. (default false)
  1473. :arg download-artifacts: Download artifacts for dependencies to see if they
  1474. have changed. (default true)
  1475. :arg bool enable-concurrent: Enable Concurrent Build. (default false)
  1476. :arg str label: Restrict where the polling should run. (default '')
  1477. :arg str cron: cron syntax of when to run (default '')
  1478. Example:
  1479. .. literalinclude:: /../../tests/triggers/fixtures/ivy.yaml
  1480. """
  1481. it = XML.SubElement(xml_parent,
  1482. 'org.jenkinsci.plugins.ivytrigger.IvyTrigger')
  1483. mapping = [
  1484. ('path', 'ivyPath', None),
  1485. ('settings-path', 'ivySettingsPath', None),
  1486. ('properties-content', 'propertiesContent', None),
  1487. ('debug', 'debug', False),
  1488. ('download-artifacts', 'downloadArtifacts', True),
  1489. ('enable-concurrent', 'enableConcurrentBuild', False),
  1490. ('cron', 'spec', ''),
  1491. ]
  1492. convert_mapping_to_xml(it, data, mapping, fail_required=False)
  1493. properties_file_path = data.get('properties-file', [])
  1494. XML.SubElement(it, 'propertiesFilePath').text = ";".join(
  1495. properties_file_path)
  1496. label = data.get('label')
  1497. XML.SubElement(it, 'labelRestriction').text = str(bool(label)).lower()
  1498. if label:
  1499. XML.SubElement(it, 'triggerLabel').text = label
  1500. def script(registry, xml_parent, data):
  1501. """yaml: script
  1502. Triggers the job using shell or batch script.
  1503. Requires the Jenkins :jenkins-wiki:`ScriptTrigger Plugin
  1504. <ScriptTrigger+Plugin>`.
  1505. :arg str label: Restrict where the polling should run. (default '')
  1506. :arg str script: A shell or batch script. (default '')
  1507. :arg str script-file-path: A shell or batch script path. (default '')
  1508. :arg str cron: cron syntax of when to run (default '')
  1509. :arg bool enable-concurrent: Enables triggering concurrent builds.
  1510. (default false)
  1511. :arg int exit-code: If the exit code of the script execution returns this
  1512. expected exit code, a build is scheduled. (default 0)
  1513. Full Example:
  1514. .. literalinclude:: /../../tests/triggers/fixtures/script-full.yaml
  1515. :language: yaml
  1516. Minimal Example:
  1517. .. literalinclude:: /../../tests/triggers/fixtures/script-minimal.yaml
  1518. :language: yaml
  1519. """
  1520. st = XML.SubElement(
  1521. xml_parent,
  1522. 'org.jenkinsci.plugins.scripttrigger.ScriptTrigger'
  1523. )
  1524. st.set('plugin', 'scripttrigger')
  1525. label = data.get('label')
  1526. mappings = [
  1527. ('script', 'script', ''),
  1528. ('script-file-path', 'scriptFilePath', ''),
  1529. ('cron', 'spec', ''),
  1530. ('enable-concurrent', 'enableConcurrentBuild', False),
  1531. ('exit-code', 'exitCode', 0),
  1532. ('', 'labelRestriction', bool(label)),
  1533. ('', 'triggerLabel', label),
  1534. ]
  1535. convert_mapping_to_xml(st, data, mappings, fail_required=False)
  1536. def groovy_script(registry, xml_parent, data):
  1537. """yaml: groovy-script
  1538. Triggers the job using a groovy script.
  1539. Requires the Jenkins :jenkins-wiki:`ScriptTrigger Plugin
  1540. <ScriptTrigger+Plugin>`.
  1541. :arg bool system-script: If true, run the groovy script as a system script,
  1542. the script will have access to the same variables as the Groovy Console.
  1543. If false, run the groovy script on the executor node, the script will not
  1544. have access to the hudson or job model. (default false)
  1545. :arg str script: Content of the groovy script. If the script result is
  1546. evaluated to true, a build is scheduled. (default '')
  1547. :arg str script-file-path: Groovy script path. (default '')
  1548. :arg str property-file-path: Property file path. All properties will be set
  1549. as parameters for the triggered build. (default '')
  1550. :arg bool enable-concurrent: Enable concurrent build. (default false)
  1551. :arg str label: Restrict where the polling should run. (default '')
  1552. :arg str cron: cron syntax of when to run (default '')
  1553. Full Example:
  1554. .. literalinclude:: /../../tests/triggers/fixtures/groovy-script-full.yaml
  1555. :language: yaml
  1556. Minimal Example:
  1557. .. literalinclude::
  1558. /../../tests/triggers/fixtures/groovy-script-minimal.yaml
  1559. :language: yaml
  1560. """
  1561. gst = XML.SubElement(
  1562. xml_parent,
  1563. 'org.jenkinsci.plugins.scripttrigger.groovy.GroovyScriptTrigger'
  1564. )
  1565. gst.set('plugin', 'scripttrigger')
  1566. label = data.get('label')
  1567. mappings = [
  1568. ('system-script', 'groovySystemScript', False),
  1569. ('script', 'groovyExpression', ''),
  1570. ('script-file-path', 'groovyFilePath', ''),
  1571. ('property-file-path', 'propertiesFilePath', ''),
  1572. ('enable-concurrent', 'enableConcurrentBuild', False),
  1573. ('cron', 'spec', ''),
  1574. ('', 'labelRestriction', bool(label)),
  1575. ('', 'triggerLabel', label),
  1576. ]
  1577. convert_mapping_to_xml(gst, data, mappings, fail_required=False)
  1578. def rabbitmq(registry, xml_parent, data):
  1579. """yaml: rabbitmq
  1580. This plugin triggers build using remote build message in RabbitMQ queue.
  1581. Requires the Jenkins :jenkins-wiki:`RabbitMQ Build Trigger Plugin
  1582. <RabbitMQ+Build+Trigger+Plugin>`.
  1583. :arg str token: the build token expected in the message queue (required)
  1584. Example:
  1585. .. literalinclude:: /../../tests/triggers/fixtures/rabbitmq.yaml
  1586. :language: yaml
  1587. """
  1588. rabbitmq = XML.SubElement(
  1589. xml_parent,
  1590. 'org.jenkinsci.plugins.rabbitmqbuildtrigger.'
  1591. 'RemoteBuildTrigger')
  1592. mapping = [
  1593. ('', 'spec', ''),
  1594. ('token', 'remoteBuildToken', None)]
  1595. convert_mapping_to_xml(rabbitmq, data, mapping, fail_required=True)
  1596. def parameterized_timer(parser, xml_parent, data):
  1597. """yaml: parameterized-timer
  1598. Trigger builds with parameters at certain times.
  1599. Requires the Jenkins :jenkins-wiki:`Parameterized Scheduler Plugin
  1600. <Parameterized+Scheduler+Plugin>`.
  1601. :arg str cron: cron syntax of when to run and with which parameters
  1602. (required)
  1603. Example:
  1604. .. literalinclude::
  1605. /../../tests/triggers/fixtures/parameterized-timer001.yaml
  1606. :language: yaml
  1607. """
  1608. param_timer = XML.SubElement(
  1609. xml_parent,
  1610. 'org.jenkinsci.plugins.parameterizedscheduler.'
  1611. 'ParameterizedTimerTrigger')
  1612. mapping = [
  1613. ('', 'spec', ''),
  1614. ('cron', 'parameterizedSpecification', None)]
  1615. convert_mapping_to_xml(param_timer, data, mapping, fail_required=True)
  1616. def jira_changelog(registry, xml_parent, data):
  1617. """yaml: jira-changelog
  1618. Sets up a trigger that listens to JIRA issue changes
  1619. Requires the Jenkins :jenkins-wiki:`JIRA Trigger Plugin
  1620. <JIRA+Trigger+Plugin>`.
  1621. :arg str jql-filter: Must match updated issues to trigger a build.
  1622. (default '')
  1623. :arg list changelog-matchers:
  1624. :Custom Field Matcher:
  1625. * **custom-field-name** (`str`) -- The custom field
  1626. name that has been changed during the issue update.
  1627. (default '')
  1628. * **compare-new-value** (`bool`) -- Compare the
  1629. new value of the updated field. (default false)
  1630. * **new-value** (`str`) -- The new value of the updated field.
  1631. (default '')
  1632. * **compare-old-value** (`bool`) -- Compare the
  1633. old value of the updated field. (default false)
  1634. * **old-value** (`str`) -- The value
  1635. before the field is updated. (default '')
  1636. :JIRA Field Matcher:
  1637. * **jira-field-ID** (`str`) -- The JIRA Field ID that
  1638. has been changed during the issue update. (default '')
  1639. * **compare-new-value** (`bool`) -- Compare the new value
  1640. of the updated field. (default false)
  1641. * **new-value** (`str`) -- The new value of the updated field.
  1642. (default '')
  1643. * **compare-old-value** (`bool`) -- Compare the old value
  1644. of the updated field. (default false)
  1645. * **old-value** (`str`) -- The value before
  1646. the field is updated. (default '')
  1647. :arg list parameter-mapping:
  1648. :Issue Attribute Path:
  1649. * **jenkins-parameter** (`str`) -- Jenkins parameter name
  1650. (default '')
  1651. * **issue-attribute-path** (`str`) -- Attribute path (default '')
  1652. Minimal Example:
  1653. .. literalinclude::
  1654. /../../tests/triggers/fixtures/jira-changelog-minimal.yaml
  1655. :language: yaml
  1656. Full Example:
  1657. .. literalinclude::
  1658. /../../tests/triggers/fixtures/jira-changelog-full.yaml
  1659. :language: yaml
  1660. """
  1661. jcht = XML.SubElement(xml_parent, 'com.ceilfors.jenkins.plugins.'
  1662. 'jiratrigger.JiraChangelogTrigger')
  1663. jcht.set('plugin', 'jira-trigger')
  1664. mapping = [('jql-filter', 'jqlFilter', '')]
  1665. convert_mapping_to_xml(jcht, data, mapping, fail_required=True)
  1666. changelog = XML.SubElement(jcht, 'changelogMatchers')
  1667. mappings = [
  1668. ('field', 'field', ''),
  1669. ('new-value', 'newValue', ''),
  1670. ('old-value', 'oldValue', ''),
  1671. ('compare-new-value', 'comparingNewValue', False),
  1672. ('compare-old-value', 'comparingOldValue', False),
  1673. ]
  1674. for matcher in data.get('changelog-matchers', []):
  1675. fieldtype = matcher.get('field-type')
  1676. if fieldtype == 'CUSTOM':
  1677. parent_tag = XML.SubElement(changelog, 'com.ceilfors.jenkins.'
  1678. 'plugins.jiratrigger.changelog.'
  1679. 'CustomFieldChangelogMatcher')
  1680. XML.SubElement(parent_tag, 'fieldType').text = 'CUSTOM'
  1681. elif fieldtype == 'JIRA':
  1682. parent_tag = XML.SubElement(changelog, 'com.ceilfors.jenkins.'
  1683. 'plugins.jiratrigger.changelog.'
  1684. 'JiraFieldChangelogMatcher')
  1685. XML.SubElement(parent_tag, 'fieldType').text = 'JIRA'
  1686. convert_mapping_to_xml(parent_tag, matcher,
  1687. mappings, fail_required=True)
  1688. param = XML.SubElement(jcht, 'parameterMappings')
  1689. parameter_mappings = [
  1690. ('jenkins-parameter', 'jenkinsParameter', ''),
  1691. ('issue-attribute-path', 'issueAttributePath', ''),
  1692. ]
  1693. for parameter in data.get('parameter-mapping', []):
  1694. parent = XML.SubElement(param, 'com.ceilfors.jenkins.plugins.'
  1695. 'jiratrigger.parameter.'
  1696. 'IssueAttributePathParameterMapping')
  1697. convert_mapping_to_xml(
  1698. parent, parameter, parameter_mappings, fail_required=True)
  1699. def jira_comment_trigger(registry, xml_parent, data):
  1700. """yaml: jira-comment-trigger
  1701. Trigger builds when a comment is added to JIRA.
  1702. Requires the Jenkins :jenkins-wiki:`JIRA Trigger Plugin
  1703. <JIRA+Trigger+Plugin>`.
  1704. :arg str jql-filter: Must match updated issues to trigger a build.
  1705. (default '')
  1706. :arg str comment-pattern: Triggers build only when the comment added to
  1707. JIRA matches pattern (default '(?i)build this please')
  1708. :arg list parameter-mapping:
  1709. :Issue Attribute Path:
  1710. * **jenkins-parameter** (`str`) -- Jenkins parameter name
  1711. (default '')
  1712. * **issue-attribute-path** (`str`) -- Attribute path (default '')
  1713. Minimal Example:
  1714. .. literalinclude::
  1715. /../../tests/triggers/fixtures/jira-comment-trigger-minimal.yaml
  1716. :language: yaml
  1717. Full Example:
  1718. .. literalinclude::
  1719. /../../tests/triggers/fixtures/jira-comment-trigger-full.yaml
  1720. :language: yaml
  1721. """
  1722. jct = XML.SubElement(xml_parent, 'com.ceilfors.jenkins.plugins.'
  1723. 'jiratrigger.JiraCommentTrigger')
  1724. jct.set('plugin', 'jira-trigger')
  1725. mapping = [
  1726. ('jql-filter', 'jqlFilter', ''),
  1727. ('comment-pattern', 'commentPattern', '(?i)build this please')]
  1728. convert_mapping_to_xml(jct, data, mapping, fail_required=True)
  1729. param = XML.SubElement(jct, 'parameterMappings')
  1730. for parameter in data.get('parameter-mapping', []):
  1731. parent = XML.SubElement(param, 'com.ceilfors.jenkins.plugins.'
  1732. 'jiratrigger.parameter.'
  1733. 'IssueAttributePathParameterMapping')
  1734. parameter_mappings = [
  1735. ('jenkins-parameter', 'jenkinsParameter', ''),
  1736. ('issue-attribute-path', 'issueAttributePath', '')]
  1737. convert_mapping_to_xml(
  1738. parent, parameter, parameter_mappings, fail_required=True)
  1739. def stash_pull_request(registry, xml_parent, data):
  1740. """yaml: stash-pull-request
  1741. Trigger builds via Stash/Bitbucket Server Pull Requests.
  1742. Requires the Jenkins :jenkins-wiki:`Stash Pull Request Builder Plugin
  1743. <Stash+pullrequest+builder+plugin>`.
  1744. :arg str cron: cron syntax of when to run (required)
  1745. :arg str stash-host: The HTTP or HTTPS URL of the Stash host (NOT ssh).
  1746. e.g.: https://example.com (required)
  1747. :arg str credentials-id: Jenkins credential set to use. (required)
  1748. :arg str project: Abbreviated project code. e.g.: PRJ or ~user (required)
  1749. :arg str repository: Stash Repository Name. e.g.: Repo (required)
  1750. :arg str ci-skip-phrases: CI Skip Phrases. (default 'NO TEST')
  1751. :arg str ci-build-phrases: CI Build Phrases. (default 'test this please')
  1752. :arg str target-branches: Target branches to filter. (default '')
  1753. :arg bool ignore-ssl: Ignore SSL certificates for Stash host.
  1754. (default false)
  1755. :arg bool check-destination-commit: Rebuild if destination branch
  1756. changes. (default false)
  1757. :arg bool check-mergable: Build only if PR is mergeable. (default false)
  1758. :arg bool merge-on-success: Merge PR if build is successful.
  1759. (default false)
  1760. :arg bool check-not-conflicted: Build only if Stash reports no conflicts.
  1761. (default false)
  1762. :arg bool only-build-on-comment: Only build when asked (with test
  1763. phrase). (default false)
  1764. :arg bool delete-previous-build-finish-comments: Keep PR comment only for
  1765. most recent Build. (default false)
  1766. :arg bool cancel-outdated-jobs: Cancel outdated jobs. (default false)
  1767. Minimal Example:
  1768. .. literalinclude::
  1769. /../../tests/triggers/fixtures/stash-pull-request-minimal.yaml
  1770. :language: yaml
  1771. Full Example:
  1772. .. literalinclude::
  1773. /../../tests/triggers/fixtures/stash-pull-request-full.yaml
  1774. :language: yaml
  1775. """
  1776. pr_trigger = XML.SubElement(
  1777. xml_parent,
  1778. 'stashpullrequestbuilder.stashpullrequestbuilder.StashBuildTrigger')
  1779. pr_trigger.set('plugin', 'stash-pullrequest-builder')
  1780. mappings = [
  1781. ('cron', 'spec', None), # Spec needs to be set to the same as cron
  1782. ('cron', 'cron', None),
  1783. ('stash-host', 'stashHost', None),
  1784. ('credentials-id', 'credentialsId', None),
  1785. ('project', 'projectCode', None),
  1786. ('repository', 'repositoryName', None),
  1787. ('ci-skip-phrases', 'ciSkipPhrases', 'NO TEST'),
  1788. ('ci-build-phrases', 'ciBuildPhrases', 'test this please'),
  1789. ('target-branches', 'targetBranchesToBuild', ''),
  1790. ('ignore-ssl', 'ignoreSsl', False),
  1791. ('check-destination-commit', 'checkDestinationCommit', False),
  1792. ('check-mergable', 'checkMergeable', False),
  1793. ('merge-on-success', 'mergeOnSuccess', False),
  1794. ('check-not-conflicted', 'checkNotConflicted', True),
  1795. ('only-build-on-comment', 'onlyBuildOnComment', False),
  1796. ('delete-previous-build-finish-comments',
  1797. 'deletePreviousBuildFinishComments', False),
  1798. ('cancel-outdated-jobs', 'cancelOutdatedJobsEnabled', False),
  1799. ]
  1800. convert_mapping_to_xml(pr_trigger, data, mappings, fail_required=True)
  1801. class Triggers(jenkins_jobs.modules.base.Base):
  1802. sequence = 50
  1803. component_type = 'trigger'
  1804. component_list_type = 'triggers'
  1805. def gen_xml(self, xml_parent, data):
  1806. triggers = data.get('triggers', [])
  1807. if not triggers:
  1808. return
  1809. trig_e = XML.SubElement(xml_parent, 'triggers', {'class': 'vector'})
  1810. for trigger in triggers:
  1811. self.registry.dispatch('trigger', trig_e, trigger)