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

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