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.

scm.py 65KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496
  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. The SCM module allows you to specify the source code location for the
  16. project. It adds the ``scm`` attribute to the :ref:`Job` definition,
  17. which accepts any number of scm definitions. It is also possible to pass
  18. ``[]`` to the ``scm`` attribute. This is useful when a set of configs has a
  19. global default ``scm`` and you want to a particular job to override that
  20. default with no SCM.
  21. **Component**: scm
  22. :Macro: scm
  23. :Entry Point: jenkins_jobs.scm
  24. The scm module allows referencing multiple repositories in a Jenkins job.
  25. Note: Adding more than one scm definition requires the Jenkins
  26. :jenkins-wiki:`Multiple SCMs plugin <Multiple+SCMs+Plugin>`.
  27. Example of multiple repositories in a single job:
  28. .. literalinclude:: /../../tests/macros/fixtures/scm/multi-scms001.yaml
  29. Example of an empty ``scm``:
  30. .. literalinclude:: /../../tests/scm/fixtures/empty.yaml
  31. """
  32. import logging
  33. import xml.etree.ElementTree as XML
  34. from jenkins_jobs.errors import InvalidAttributeError
  35. from jenkins_jobs.errors import JenkinsJobsException
  36. import jenkins_jobs.modules.base
  37. from jenkins_jobs.modules.helpers import convert_mapping_to_xml
  38. def git(registry, xml_parent, data):
  39. """yaml: git
  40. Specifies the git SCM repository for this job.
  41. Requires the Jenkins :jenkins-wiki:`Git Plugin <Git+Plugin>`.
  42. :arg str url: URL of the git repository
  43. :arg str credentials-id: ID of credential to use to connect, which is the
  44. last field (a 32-digit hexadecimal code) of the path of URL visible
  45. after you clicked the credential under Jenkins Global credentials.
  46. (optional)
  47. :arg str refspec: refspec to fetch (default
  48. '+refs/heads/\*:refs/remotes/remoteName/\*')
  49. :arg str name: name to fetch (default 'origin')
  50. :arg list(str) remotes: list of remotes to set up (optional, only needed if
  51. multiple remotes need to be set up)
  52. :Remote:
  53. * **url** (`string`) - url of remote repo
  54. * **refspec** (`string`) - refspec to fetch (optional)
  55. * **credentials-id** - ID of credential to use to connect, which
  56. is the last field of the path of URL (a 32-digit hexadecimal
  57. code) visible after you clicked credential under Jenkins Global
  58. credentials. (optional)
  59. :arg list(str) branches: list of branch specifiers to build (default '**')
  60. :arg bool skip-tag: Skip tagging (default true)
  61. .. deprecated:: 2.0.0. Please use per-build-tag extension, which has
  62. the inverse meaning.
  63. :arg bool clean: Clean after checkout (default false)
  64. .. deprecated:: 1.1.1. Please use clean extension format.
  65. :arg bool fastpoll: Use fast remote polling (default false)
  66. :arg bool disable-submodules: Disable submodules (default false)
  67. .. deprecated:: 1.1.1. Please use submodule extension.
  68. :arg bool recursive-submodules: Recursively update submodules (default
  69. false)
  70. .. deprecated:: 1.1.1. Please use submodule extension.
  71. :arg str git-tool: The name of the Git installation to use (default
  72. 'Default')
  73. :arg str reference-repo: Path of the reference repo to use during clone
  74. (optional)
  75. :arg str browser: what repository browser to use.
  76. :browsers supported:
  77. * **auto** - (default)
  78. * **assemblaweb** - https://www.assembla.com/home
  79. * **bitbucketweb** - https://bitbucket.org/
  80. * **cgit** - https://git.zx2c4.com/cgit/about/
  81. * **fisheye** - https://www.atlassian.com/software/fisheye
  82. * **gitblit** - http://gitblit.com/
  83. * **githubweb** - https://github.com/
  84. * **gitiles** - https://code.google.com/p/gitiles/
  85. * **gitlab** - https://about.gitlab.com/
  86. * **gitlist** - http://gitlist.org/
  87. * **gitoriousweb** - https://gitorious.org/
  88. * **gitweb** - https://git-scm.com/docs/gitweb
  89. * **kiln** - https://www.fogcreek.com/kiln/
  90. * **microsoft\-tfs\-2013** - |tfs_2013|
  91. * **phabricator** - http://phabricator.org/
  92. * **redmineweb** - http://www.redmine.org/
  93. * **rhodecode** - https://rhodecode.com/
  94. * **stash** - https://www.atlassian.com/software/bitbucket/server
  95. * **viewgit** - http://viewgit.fealdia.org/
  96. :arg str browser-url: url for the repository browser (required if browser
  97. is not 'auto', no default)
  98. :arg str browser-version: version of the repository browser (GitLab only,
  99. default '0.0')
  100. :arg str project-name: project name in Gitblit and ViewGit repobrowser
  101. (optional)
  102. :arg str repo-name: repository name in phabricator repobrowser (optional)
  103. :arg str git-config-name: Configure name for Git clone (optional)
  104. :arg str git-config-email: Configure email for Git clone (optional)
  105. :extensions:
  106. * **basedir** (`string`) - Location relative to the workspace root to
  107. clone to (default workspace)
  108. * **changelog-against** (`dict`)
  109. * **remote** (`string`) - name of repo that contains branch to
  110. create changelog against (default 'origin')
  111. * **branch** (`string`) - name of the branch to create changelog
  112. against (default 'master')
  113. * **choosing-strategy**: (`string`) - Jenkins class for selecting what
  114. to build. Can be one of `default`,`inverse`, or `gerrit`
  115. (default 'default')
  116. * **clean** (`dict`)
  117. * **after** (`bool`) - Clean the workspace after checkout
  118. * **before** (`bool`) - Clean the workspace before checkout
  119. * **excluded-users**: (`list(string)`) - list of users to ignore
  120. revisions from when polling for changes.
  121. (if polling is enabled, optional)
  122. * **included-regions**: (`list(string)`) - list of file/folders to
  123. include (optional)
  124. * **excluded-regions**: (`list(string)`) - list of file/folders to
  125. exclude (optional)
  126. * **ignore-commits-with-messages** (`list(str)`) - Revisions committed
  127. with messages matching these patterns will be ignored. (optional)
  128. * **ignore-notify**: (`bool`) - Ignore notifyCommit URL accesses
  129. (default false)
  130. * **force-polling-using-workspace** (`bool`) - Force polling using
  131. workspace (default false)
  132. * **local-branch** (`string`) - Checkout/merge to local branch
  133. (optional)
  134. * **merge** (`dict`)
  135. * **remote** (`string`) - name of repo that contains branch to
  136. merge to (default 'origin')
  137. * **branch** (`string`) - name of the branch to merge to
  138. * **strategy** (`string`) - merge strategy. Can be one of
  139. 'default', 'resolve', 'recursive', 'octopus', 'ours',
  140. 'subtree'. (default 'default')
  141. * **fast-forward-mode** (`string`) - merge fast-forward mode.
  142. Can be one of 'FF', 'FF_ONLY' or 'NO_FF'. (default 'FF')
  143. * **per-build-tag** (`bool`) - Create a tag in the workspace for every
  144. build. (default is inverse of skip-tag if set, otherwise false)
  145. * **prune** (`bool`) - Prune remote branches (default false)
  146. * **scm-name** (`string`) - The unique scm name for this Git SCM
  147. (optional)
  148. * **shallow-clone** (`bool`) - Perform shallow clone (default false)
  149. * **depth** (`int`) - Set shallow clone depth (default 1)
  150. * **do-not-fetch-tags** (`bool`) - Perform a clone without tags
  151. (default false)
  152. * **sparse-checkout** (`dict`)
  153. * **paths** (`list`) - List of paths to sparse checkout. (optional)
  154. * **submodule** (`dict`)
  155. * **disable** (`bool`) - By disabling support for submodules you
  156. can still keep using basic git plugin functionality and just have
  157. Jenkins to ignore submodules completely as if they didn't exist.
  158. * **recursive** (`bool`) - Retrieve all submodules recursively
  159. (uses '--recursive' option which requires git>=1.6.5)
  160. * **tracking** (`bool`) - Retrieve the tip of the configured
  161. branch in .gitmodules (Uses '\-\-remote' option which requires
  162. git>=1.8.2)
  163. * **parent-credentials** (`bool`) - Use credentials from default
  164. remote of parent repository (default false).
  165. * **reference-repo** (`str`) - Path of the reference repo to use
  166. during clone (optional)
  167. * **timeout** (`int`) - Specify a timeout (in minutes) for
  168. submodules operations (default 10).
  169. * **timeout** (`str`) - Timeout for git commands in minutes (optional)
  170. * **use-author** (`bool`): Use author rather than committer in Jenkin's
  171. build changeset (default false)
  172. * **wipe-workspace** (`bool`) - Wipe out workspace before build
  173. (default true)
  174. Example:
  175. .. literalinclude:: /../../tests/scm/fixtures/git001.yaml
  176. .. |tfs_2013| replace::
  177. https://www.visualstudio.com/en-us/products/tfs-overview-vs.aspx
  178. """
  179. logger = logging.getLogger("%s:git" % __name__)
  180. # XXX somebody should write the docs for those with option name =
  181. # None so we have a sensible name/key for it.
  182. mapping = [
  183. # option, xml name, default value (text), attributes (hard coded)
  184. ("disable-submodules", 'disableSubmodules', False),
  185. ("recursive-submodules", 'recursiveSubmodules', False),
  186. (None, 'doGenerateSubmoduleConfigurations', False),
  187. # XXX is this the same as force-polling-using-workspace?
  188. ("fastpoll", 'remotePoll', False),
  189. # XXX does this option still exist?
  190. ("git-tool", 'gitTool', "Default"),
  191. (None, 'submoduleCfg', '', {'class': 'list'}),
  192. ('reference-repo', 'reference', ''),
  193. ("git-config-name", 'gitConfigName', ''),
  194. ("git-config-email", 'gitConfigEmail', ''),
  195. ]
  196. choosing_strategies = {
  197. 'default': 'hudson.plugins.git.util.DefaultBuildChooser',
  198. 'gerrit': ('com.sonyericsson.hudson.plugins.'
  199. 'gerrit.trigger.hudsontrigger.GerritTriggerBuildChooser'),
  200. 'inverse': 'hudson.plugins.git.util.InverseBuildChooser',
  201. }
  202. scm = XML.SubElement(xml_parent,
  203. 'scm', {'class': 'hudson.plugins.git.GitSCM'})
  204. XML.SubElement(scm, 'configVersion').text = '2'
  205. user = XML.SubElement(scm, 'userRemoteConfigs')
  206. if 'remotes' not in data:
  207. data['remotes'] = [{data.get('name', 'origin'): data.copy()}]
  208. for remoteData in data['remotes']:
  209. huser = XML.SubElement(user, 'hudson.plugins.git.UserRemoteConfig')
  210. remoteName = next(iter(remoteData.keys()))
  211. XML.SubElement(huser, 'name').text = remoteName
  212. remoteParams = next(iter(remoteData.values()))
  213. if 'refspec' in remoteParams:
  214. refspec = remoteParams['refspec']
  215. else:
  216. refspec = '+refs/heads/*:refs/remotes/' + remoteName + '/*'
  217. XML.SubElement(huser, 'refspec').text = refspec
  218. if 'url' in remoteParams:
  219. remoteURL = remoteParams['url']
  220. else:
  221. raise JenkinsJobsException('Must specify a url for git remote \"' +
  222. remoteName + '"')
  223. XML.SubElement(huser, 'url').text = remoteURL
  224. if 'credentials-id' in remoteParams:
  225. credentialsId = remoteParams['credentials-id']
  226. XML.SubElement(huser, 'credentialsId').text = credentialsId
  227. xml_branches = XML.SubElement(scm, 'branches')
  228. branches = data.get('branches', ['**'])
  229. for branch in branches:
  230. bspec = XML.SubElement(xml_branches, 'hudson.plugins.git.BranchSpec')
  231. XML.SubElement(bspec, 'name').text = branch
  232. for elem in mapping:
  233. (optname, xmlname, val) = elem[:3]
  234. # Throw warning for deprecated settings and skip if the 'submodule' key
  235. # is available.
  236. submodule_cfgs = ['disable-submodules', 'recursive-submodules']
  237. if optname in submodule_cfgs:
  238. if optname in data:
  239. logger.warning(
  240. "'{0}' is deprecated, please convert to use the "
  241. "'submodule' section instead as support for this "
  242. "top level option will be removed in a future "
  243. "release.".format(optname))
  244. if 'submodule' in data:
  245. continue
  246. attrs = {}
  247. if len(elem) >= 4:
  248. attrs = elem[3]
  249. xe = XML.SubElement(scm, xmlname, attrs)
  250. if optname and optname in data:
  251. val = data[optname]
  252. if type(val) == bool:
  253. xe.text = str(val).lower()
  254. else:
  255. xe.text = val
  256. exts_node = XML.SubElement(scm, 'extensions')
  257. impl_prefix = 'hudson.plugins.git.extensions.impl.'
  258. if 'basedir' in data:
  259. ext = XML.SubElement(exts_node,
  260. impl_prefix + 'RelativeTargetDirectory')
  261. XML.SubElement(ext, 'relativeTargetDir').text = data['basedir']
  262. if 'changelog-against' in data:
  263. ext_name = impl_prefix + 'ChangelogToBranch'
  264. ext = XML.SubElement(exts_node, ext_name)
  265. opts = XML.SubElement(ext, 'options')
  266. change_remote = data['changelog-against'].get('remote', 'origin')
  267. change_branch = data['changelog-against'].get('branch', 'master')
  268. XML.SubElement(opts, 'compareRemote').text = change_remote
  269. XML.SubElement(opts, 'compareTarget').text = change_branch
  270. if 'choosing-strategy' in data:
  271. try:
  272. choosing_strategy = choosing_strategies[
  273. data.get('choosing-strategy')]
  274. except KeyError:
  275. raise ValueError('Invalid choosing-strategy %r' %
  276. data.get('choosing-strategy'))
  277. ext = XML.SubElement(exts_node, impl_prefix + 'BuildChooserSetting')
  278. XML.SubElement(ext, 'buildChooser', {'class': choosing_strategy})
  279. if 'clean' in data:
  280. # Keep support for old format 'clean' configuration by checking
  281. # if 'clean' is boolean. Else we're using the new extensions style.
  282. if isinstance(data['clean'], bool):
  283. clean_after = data['clean']
  284. clean_before = False
  285. logger.warning(
  286. "'clean: bool' configuration format is deprecated, "
  287. "please use the extension style format to configure "
  288. "this option.")
  289. else:
  290. clean_after = data['clean'].get('after', False)
  291. clean_before = data['clean'].get('before', False)
  292. if clean_after:
  293. ext_name = impl_prefix + 'CleanCheckout'
  294. ext = XML.SubElement(exts_node, ext_name)
  295. if clean_before:
  296. ext_name = impl_prefix + 'CleanBeforeCheckout'
  297. ext = XML.SubElement(exts_node, ext_name)
  298. if 'excluded-users' in data:
  299. excluded_users = '\n'.join(data['excluded-users'])
  300. ext = XML.SubElement(exts_node, impl_prefix + 'UserExclusion')
  301. XML.SubElement(ext, 'excludedUsers').text = excluded_users
  302. if 'included-regions' in data or 'excluded-regions' in data:
  303. ext = XML.SubElement(exts_node,
  304. 'hudson.plugins.git.extensions.impl.'
  305. 'PathRestriction')
  306. if 'included-regions' in data:
  307. include_string = '\n'.join(data['included-regions'])
  308. XML.SubElement(ext, 'includedRegions').text = include_string
  309. if 'excluded-regions' in data:
  310. exclude_string = '\n'.join(data['excluded-regions'])
  311. XML.SubElement(ext, 'excludedRegions').text = exclude_string
  312. if 'ignore-commits-with-messages' in data:
  313. for msg in data['ignore-commits-with-messages']:
  314. ext_name = impl_prefix + 'MessageExclusion'
  315. ext = XML.SubElement(exts_node, ext_name)
  316. XML.SubElement(ext, 'excludedMessage').text = msg
  317. if 'local-branch' in data:
  318. ext = XML.SubElement(exts_node, impl_prefix + 'LocalBranch')
  319. XML.SubElement(ext, 'localBranch').text = str(data['local-branch'])
  320. if 'merge' in data:
  321. merge = data['merge']
  322. merge_strategies = ['default', 'resolve', 'recursive', 'octopus',
  323. 'ours', 'subtree']
  324. fast_forward_modes = ['FF', 'FF_ONLY', 'NO_FF']
  325. name = merge.get('remote', 'origin')
  326. branch = merge['branch']
  327. ext = XML.SubElement(exts_node, impl_prefix + 'PreBuildMerge')
  328. merge_opts = XML.SubElement(ext, 'options')
  329. XML.SubElement(merge_opts, 'mergeRemote').text = name
  330. XML.SubElement(merge_opts, 'mergeTarget').text = branch
  331. strategy = merge.get('strategy', 'default')
  332. if strategy not in merge_strategies:
  333. raise InvalidAttributeError('strategy', strategy, merge_strategies)
  334. XML.SubElement(merge_opts, 'mergeStrategy').text = strategy
  335. fast_forward_mode = merge.get('fast-forward-mode', 'FF')
  336. if fast_forward_mode not in fast_forward_modes:
  337. raise InvalidAttributeError('fast-forward-mode', fast_forward_mode,
  338. fast_forward_modes)
  339. XML.SubElement(merge_opts, 'fastForwardMode').text = fast_forward_mode
  340. if 'scm-name' in data:
  341. ext = XML.SubElement(exts_node, impl_prefix + 'ScmName')
  342. XML.SubElement(ext, 'name').text = str(data['scm-name'])
  343. clone_options = (
  344. "shallow-clone",
  345. "timeout",
  346. "do-not-fetch-tags"
  347. )
  348. if any(key in data for key in clone_options):
  349. clo = XML.SubElement(exts_node, impl_prefix + 'CloneOption')
  350. clone_mapping = [
  351. ('shallow-clone', 'shallow', False),
  352. ('depth', 'depth', 1)]
  353. convert_mapping_to_xml(clo, data, clone_mapping, fail_required=True)
  354. if 'do-not-fetch-tags' in data:
  355. XML.SubElement(clo, 'noTags').text = str(
  356. data.get('do-not-fetch-tags', False)).lower()
  357. if 'timeout' in data:
  358. XML.SubElement(clo, 'timeout').text = str(data['timeout'])
  359. if 'sparse-checkout' in data:
  360. ext_name = impl_prefix + 'SparseCheckoutPaths'
  361. ext = XML.SubElement(exts_node, ext_name)
  362. sparse_co = XML.SubElement(ext, 'sparseCheckoutPaths')
  363. sparse_paths = data['sparse-checkout'].get('paths')
  364. if sparse_paths is not None:
  365. path_tagname = impl_prefix + 'SparseCheckoutPath'
  366. for path in sparse_paths:
  367. path_tag = XML.SubElement(sparse_co, path_tagname)
  368. XML.SubElement(path_tag, 'path').text = path
  369. if 'submodule' in data:
  370. ext_name = impl_prefix + 'SubmoduleOption'
  371. ext = XML.SubElement(exts_node, ext_name)
  372. XML.SubElement(ext, 'disableSubmodules').text = str(
  373. data['submodule'].get('disable', False)).lower()
  374. XML.SubElement(ext, 'recursiveSubmodules').text = str(
  375. data['submodule'].get('recursive', False)).lower()
  376. XML.SubElement(ext, 'trackingSubmodules').text = str(
  377. data['submodule'].get('tracking', False)).lower()
  378. XML.SubElement(ext, 'parentCredentials').text = str(
  379. data['submodule'].get('parent-credentials', False)).lower()
  380. XML.SubElement(ext, 'reference').text = str(
  381. data['submodule'].get('reference-repo', ''))
  382. XML.SubElement(ext, 'timeout').text = str(
  383. data['submodule'].get('timeout', 10))
  384. if 'timeout' in data:
  385. co = XML.SubElement(exts_node, impl_prefix + 'CheckoutOption')
  386. XML.SubElement(co, 'timeout').text = str(data['timeout'])
  387. polling_using_workspace = str(data.get('force-polling-using-workspace',
  388. False)).lower()
  389. if polling_using_workspace == 'true':
  390. ext_name = impl_prefix + 'DisableRemotePoll'
  391. ext = XML.SubElement(exts_node, ext_name)
  392. if 'per-build-tag' in data or 'skip-tag' in data:
  393. # We want to support both skip-tag (the old option) and per-build-tag
  394. # (the new option), with the new one overriding the old one.
  395. # Unfortunately they have inverse meanings, so we have to be careful.
  396. # The default value of per-build-tag is False if skip-tag is not set,
  397. # so we set the default value of skip-tag to True.
  398. per_build_tag_default = False
  399. if str(data.get('skip-tag', True)).lower() == 'false':
  400. per_build_tag_default = True
  401. if str(data.get('per-build-tag',
  402. per_build_tag_default)).lower() == 'true':
  403. XML.SubElement(exts_node, impl_prefix + 'PerBuildTag')
  404. prune = str(data.get('prune', False)).lower()
  405. if prune == 'true':
  406. XML.SubElement(exts_node, impl_prefix + 'PruneStaleBranch')
  407. ignore_notify_commits = str(data.get('ignore-notify', False)).lower()
  408. if ignore_notify_commits == 'true':
  409. XML.SubElement(exts_node, impl_prefix + 'IgnoreNotifyCommit')
  410. # By default we wipe the workspace
  411. wipe_workspace = str(data.get('wipe-workspace', True)).lower()
  412. if wipe_workspace == 'true':
  413. ext_name = impl_prefix + 'WipeWorkspace'
  414. ext = XML.SubElement(exts_node, ext_name)
  415. use_author = str(data.get('use-author', False)).lower()
  416. if use_author == 'true':
  417. XML.SubElement(exts_node, impl_prefix + 'AuthorInChangelog')
  418. browser = data.get('browser', 'auto')
  419. browserdict = {
  420. 'auto': 'auto',
  421. 'assemblaweb': 'AssemblaWeb',
  422. 'bitbucketweb': 'BitbucketWeb',
  423. 'cgit': 'CGit',
  424. 'fisheye': 'FisheyeGitRepositoryBrowser',
  425. 'gitblit': 'GitBlitRepositoryBrowser',
  426. 'githubweb': 'GithubWeb',
  427. 'gitiles': 'Gitiles',
  428. 'gitlab': 'GitLab',
  429. 'gitlist': 'GitList',
  430. 'gitoriousweb': 'GitoriousWeb',
  431. 'gitweb': 'GitWeb',
  432. 'kiln': 'KilnGit',
  433. 'microsoft-tfs-2013': 'TFS2013GitRepositoryBrowser',
  434. 'phabricator': 'Phabricator',
  435. 'redmineweb': 'RedmineWeb',
  436. 'rhodecode': 'RhodeCode',
  437. 'stash': 'Stash',
  438. 'viewgit': 'ViewGitWeb',
  439. }
  440. if browser not in browserdict:
  441. valid = sorted(browserdict.keys())
  442. raise JenkinsJobsException("Browser entered is not valid must be one "
  443. "of: %s or %s." % (", ".join(valid[:-1]),
  444. valid[-1]))
  445. if browser != 'auto':
  446. bc = XML.SubElement(scm, 'browser', {'class':
  447. 'hudson.plugins.git.browser.' +
  448. browserdict[browser]})
  449. XML.SubElement(bc, 'url').text = data['browser-url']
  450. if browser in ['gitblit', 'viewgit']:
  451. XML.SubElement(bc, 'projectName').text = str(
  452. data.get('project-name', ''))
  453. if browser == 'gitlab':
  454. XML.SubElement(bc, 'version').text = str(
  455. data.get('browser-version', '0.0'))
  456. if browser == 'phabricator':
  457. XML.SubElement(bc, 'repo').text = str(
  458. data.get('repo-name', ''))
  459. def cvs(registry, xml_parent, data):
  460. """yaml: cvs
  461. Specifies the CVS SCM repository for this job.
  462. Requires the Jenkins :jenkins-wiki:`CVS Plugin <CVS+Plugin>`.
  463. :arg list repos: List of CVS repositories. (required)
  464. :Repos:
  465. * **root** (`str`) -- The CVS connection string Jenkins uses to
  466. connect to the server. The format is :protocol:user@host:path
  467. (required)
  468. * **locations** (`list`) -- List of locations. (required)
  469. :Locations:
  470. * **type** (`str`) -- Type of location.
  471. :supported values:
  472. * **HEAD** - (default)
  473. * **BRANCH**
  474. * **TAG**
  475. * **name** (`str`) -- Name of location. Only valid in case
  476. of 'BRANCH' or 'TAG' location type. (default '')
  477. * **use-head** (`bool`) -- Use Head if not found. Only
  478. valid in case of 'BRANCH' or 'TAG' location type.
  479. (default false)
  480. * **modules** (`list`) -- List of modules. (required)
  481. :Modules:
  482. * **remote** -- The name of the module in the
  483. repository at CVSROOT. (required)
  484. * **local-name** -- The name to be applied to
  485. this module in the local workspace. If blank,
  486. the remote module name will be used.
  487. (default '')
  488. * **excluded-regions** (`list str`) -- Patterns for excluding
  489. regions. (optional)
  490. * **compression-level** (`int`) -- Compression level. Must be a
  491. number between -1 and 9 inclusive. Choose -1 for System Default.
  492. (default -1)
  493. :arg bool use-update: If true, Jenkins will use 'cvs update' whenever
  494. possible for builds. This makes a build faster. But this also causes the
  495. artifacts from the previous build to remain in the file system when a
  496. new build starts, making it not a true clean build. (default true)
  497. :arg bool prune-empty: Remove empty directories after checkout using the
  498. CVS '-P' option. (default true)
  499. :arg bool skip-changelog: Prevent the changelog being generated after
  500. checkout has completed. (default false)
  501. :arg bool show-all-output: Instructs CVS to show all logging output. CVS
  502. normally runs in quiet mode but this option disables that.
  503. (default false)
  504. :arg bool clean-checkout: Perform clean checkout on failed update.
  505. (default false)
  506. :arg bool clean-copy: Force clean copy for locally modified files.
  507. (default false)
  508. Example
  509. .. literalinclude:: /../../tests/scm/fixtures/cvs001.yaml
  510. :language: yaml
  511. .. literalinclude:: /../../tests/scm/fixtures/cvs002.yaml
  512. :language: yaml
  513. """
  514. prefix = 'hudson.scm.'
  515. valid_loc_types = {'HEAD': 'Head', 'TAG': 'Tag', 'BRANCH': 'Branch'}
  516. cvs = XML.SubElement(xml_parent, 'scm', {'class': prefix + 'CVSSCM'})
  517. repos = data.get('repos')
  518. repos_tag = XML.SubElement(cvs, 'repositories')
  519. for repo in repos:
  520. repo_tag = XML.SubElement(repos_tag, prefix + 'CvsRepository')
  521. compression_level = repo.get('compression-level', '-1')
  522. repo_mapping = [('root', 'cvsRoot', None),
  523. ('', 'compressionLevel', int(compression_level), range(-1, 10))]
  524. convert_mapping_to_xml(repo_tag,
  525. repo, repo_mapping, fail_required=True)
  526. items_tag = XML.SubElement(repo_tag, 'repositoryItems')
  527. locations = repo.get('locations')
  528. for location in locations:
  529. item_tag = XML.SubElement(items_tag, prefix + 'CvsRepositoryItem')
  530. loc_type = location.get('type', 'HEAD')
  531. if loc_type not in valid_loc_types:
  532. raise InvalidAttributeError('type', loc_type, valid_loc_types)
  533. loc_class = ('{0}CvsRepositoryLocation${1}Repository'
  534. 'Location').format(prefix, valid_loc_types[loc_type])
  535. loc_tag = XML.SubElement(item_tag, 'location',
  536. {'class': loc_class})
  537. mapping = [('type', 'locationType', 'HEAD')]
  538. convert_mapping_to_xml(
  539. loc_tag, location, mapping, fail_required=True)
  540. if loc_type != 'HEAD':
  541. mapping = [
  542. ('name', 'locationName', ''),
  543. ('use-head', 'useHeadIfNotFound', False)]
  544. convert_mapping_to_xml(
  545. loc_tag, location, mapping, fail_required=True)
  546. modules = location.get('modules')
  547. modules_tag = XML.SubElement(item_tag, 'modules')
  548. for module in modules:
  549. module_tag = XML.SubElement(modules_tag, prefix + 'CvsModule')
  550. mapping = [
  551. ('remote', 'remoteName', None),
  552. ('local-name', 'localName', '')]
  553. convert_mapping_to_xml(
  554. module_tag, module, mapping, fail_required=True)
  555. excluded = repo.get('excluded-regions', [])
  556. excluded_tag = XML.SubElement(repo_tag, 'excludedRegions')
  557. for pattern in excluded:
  558. pattern_tag = XML.SubElement(excluded_tag,
  559. prefix + 'ExcludedRegion')
  560. XML.SubElement(pattern_tag, 'pattern').text = pattern
  561. mappings = [
  562. ('use-update', 'canUseUpdate', True),
  563. ('prune-empty', 'pruneEmptyDirectories', True),
  564. ('skip-changelog', 'skipChangeLog', False),
  565. ('show-all-output', 'disableCvsQuiet', False),
  566. ('clean-checkout', 'cleanOnFailedUpdate', False),
  567. ('clean-copy', 'forceCleanCopy', False)]
  568. convert_mapping_to_xml(cvs, data, mappings, fail_required=True)
  569. def repo(registry, xml_parent, data):
  570. """yaml: repo
  571. Specifies the repo SCM repository for this job.
  572. Requires the Jenkins :jenkins-wiki:`Repo Plugin <Repo+Plugin>`.
  573. :arg str manifest-url: URL of the repo manifest (required)
  574. :arg str manifest-branch: The branch of the manifest to use (optional)
  575. :arg str manifest-file: Initial manifest file to use when initialising
  576. (optional)
  577. :arg str manifest-group: Only retrieve those projects in the manifest
  578. tagged with the provided group name (optional)
  579. :arg list(str) ignore-projects: a list of projects in which changes would
  580. not be considered to trigger a build when pooling (optional)
  581. :arg str destination-dir: Location relative to the workspace root to clone
  582. under (optional)
  583. :arg str repo-url: custom url to retrieve the repo application (optional)
  584. :arg str mirror-dir: Path to mirror directory to reference when
  585. initialising (optional)
  586. :arg int jobs: Number of projects to fetch simultaneously (default 0)
  587. :arg int depth: Specify the depth in history to sync from the source. The
  588. default is to sync all of the history. Use 1 to just sync the most
  589. recent commit (default 0)
  590. :arg bool current-branch: Fetch only the current branch from the server
  591. (default true)
  592. :arg bool reset-first: Remove any commits that are not on the repositories
  593. by running the following command before anything else (default false):
  594. ``repo forall -c "git reset --hard"``
  595. :arg bool quiet: Make repo more quiet
  596. (default true)
  597. :arg bool force-sync: Continue sync even if a project fails to sync
  598. (default false)
  599. :arg bool no-tags: Don't fetch tags (default false)
  600. :arg bool trace: Trace git command execution into the build logs. (default
  601. false)
  602. :arg bool show-all-changes: When this is checked --first-parent is no
  603. longer passed to git log when determining changesets (default false)
  604. :arg str local-manifest: Contents of .repo/local_manifest.xml, written
  605. prior to calling sync (optional)
  606. Example:
  607. .. literalinclude:: /../../tests/scm/fixtures/repo001.yaml
  608. """
  609. scm = XML.SubElement(xml_parent,
  610. 'scm', {'class': 'hudson.plugins.repo.RepoScm'})
  611. mapping = [
  612. # option, xml name, default value
  613. ('manifest-url', 'manifestRepositoryUrl', None),
  614. ('jobs', 'jobs', 0),
  615. ('depth', 'depth', 0),
  616. ('current-branch', 'currentBranch', True),
  617. ('reset-first', 'resetFirst', False),
  618. ('quiet', 'quiet', True),
  619. ('force-sync', 'forceSync', False),
  620. ('no-tags', 'noTags', False),
  621. ('trace', 'trace', False),
  622. ('show-all-changes', 'showAllChanges', False),
  623. ]
  624. convert_mapping_to_xml(scm, data, mapping, fail_required=True)
  625. optional_mapping = [
  626. # option, xml name, default value
  627. ('manifest-branch', 'manifestBranch', None),
  628. ('manifest-file', 'manifestFile', None),
  629. ('manifest-group', 'manifestGroup', None),
  630. ('destination-dir', 'destinationDir', None),
  631. ('repo-url', 'repoUrl', None),
  632. ('mirror-dir', 'mirrorDir', None),
  633. ('local-manifest', 'localManifest', None),
  634. ]
  635. convert_mapping_to_xml(scm, data, optional_mapping, fail_required=False)
  636. # ignore-projects does not follow the same pattern of the other parameters,
  637. # so process it here:
  638. ip = XML.SubElement(scm, 'ignoreProjects', {'class': 'linked-hash-set'})
  639. ignored_projects = data.get('ignore-projects', [''])
  640. for ignored_project in ignored_projects:
  641. XML.SubElement(ip, 'string').text = str(ignored_project)
  642. def store(registry, xml_parent, data):
  643. """yaml: store
  644. Specifies the Visualworks Smalltalk Store repository for this job.
  645. Requires the Jenkins :jenkins-wiki:`Visualworks Smalltalk Store Plugin
  646. <Visualworks+Smalltalk+Store+Plugin>`.
  647. :arg str script: name of the Store script to run
  648. :arg str repository: name of the Store repository
  649. :arg str version-regex: regular expression that specifies which pundle
  650. versions should be considered (optional)
  651. :arg str minimum-blessing: minimum blessing level to consider (optional)
  652. :arg str parcel-builder-file: name of the file to generate as input to
  653. a later parcel building step (optional - if not specified, then no
  654. parcel builder file will be generated)
  655. :arg list pundles:
  656. :(package or bundle): (`dict`): A package or bundle to check
  657. Example:
  658. .. literalinclude:: /../../tests/scm/fixtures/store001.yaml
  659. """
  660. namespace = 'org.jenkinsci.plugins.visualworks_store'
  661. scm = XML.SubElement(xml_parent, 'scm',
  662. {'class': '{0}.StoreSCM'.format(namespace)})
  663. mapping = [
  664. ('script', 'scriptName', None),
  665. ('repository', 'repositoryName', None)]
  666. convert_mapping_to_xml(scm, data, mapping, fail_required=True)
  667. pundle_specs = data.get('pundles', [])
  668. if not pundle_specs:
  669. raise JenkinsJobsException("At least one pundle must be specified")
  670. valid_pundle_types = ['PACKAGE', 'BUNDLE']
  671. pundles = XML.SubElement(scm, 'pundles')
  672. for pundle_spec in pundle_specs:
  673. pundle = XML.SubElement(pundles, '{0}.PundleSpec'.format(namespace))
  674. pundle_type = next(iter(pundle_spec))
  675. pundle_name = pundle_spec[pundle_type]
  676. mapping = [
  677. ('', 'name', pundle_name),
  678. ('', 'pundleType', pundle_type.upper(), valid_pundle_types)]
  679. convert_mapping_to_xml(pundle, data, mapping, fail_required=True)
  680. generate_parcel = 'parcel-builder-file' in data
  681. mapping_optional = [
  682. ('version-regex', 'versionRegex', None),
  683. ('minimum-blessing', 'minimumBlessingLevel', None),
  684. ('', 'generateParcelBuilderInputFile', generate_parcel),
  685. ('parcel-builder-file', 'parcelBuilderInputFilename', None)]
  686. convert_mapping_to_xml(scm,
  687. data, mapping_optional, fail_required=False)
  688. def svn(registry, xml_parent, data):
  689. """yaml: svn
  690. Specifies the svn SCM repository for this job.
  691. :arg str url: URL of the svn repository
  692. :arg str basedir: location relative to the workspace root to checkout to
  693. (default '.')
  694. :arg str credentials-id: optional argument to specify the ID of credentials
  695. to use
  696. :arg str repo-depth: Repository depth. Can be one of 'infinity', 'empty',
  697. 'files', 'immediates' or 'unknown'. (default 'infinity')
  698. :arg bool ignore-externals: Ignore Externals. (default false)
  699. :arg str workspaceupdater: optional argument to specify
  700. :arg str workspaceupdater: optional argument to specify how to update the
  701. workspace (default wipeworkspace)
  702. :supported values:
  703. * **wipeworkspace** - deletes the workspace before checking out
  704. * **revertupdate** - do an svn revert then an svn update
  705. * **emulateclean** - delete unversioned/ignored files then update
  706. * **update** - do an svn update as much as possible
  707. :arg list(str) excluded-users: list of users to ignore revisions from
  708. when polling for changes (if polling is enabled; parameter is optional)
  709. :arg list(str) included-regions: list of file/folders to include
  710. (optional)
  711. :arg list(str) excluded-regions: list of file/folders to exclude (optional)
  712. :arg list(str) excluded-commit-messages: list of commit messages to exclude
  713. (optional)
  714. :arg str exclusion-revprop-name: revision svn-property to ignore (optional)
  715. :arg bool ignore-property-changes-on-directories: ignore svn-property only
  716. changes of directories (default false)
  717. :arg bool filter-changelog: If set Jenkins will apply the same inclusion
  718. and exclusion patterns for displaying changelog entries as it does for
  719. polling for changes (default false)
  720. :arg list repos: list of repositories to checkout (optional)
  721. :arg list additional-credentials: list of additional credentials (optional)
  722. :Additional-Credentials:
  723. * **realm** (`str`) -- realm to use
  724. * **credentials-id** (`str`) -- optional ID of credentials to use
  725. :arg str viewvc-url: URL of the svn web interface (optional)
  726. :Repo:
  727. * **url** (`str`) -- URL for the repository
  728. * **basedir** (`str`) -- Location relative to the workspace root
  729. to checkout to (default '.')
  730. * **credentials-id** - optional ID of credentials to use
  731. * **repo-depth** - Repository depth. Can be one of 'infinity',
  732. 'empty', 'files', 'immediates' or 'unknown'. (default 'infinity')
  733. * **ignore-externals** - Ignore Externals. (default false)
  734. Multiple repos example:
  735. .. literalinclude:: /../../tests/scm/fixtures/svn-multiple-repos-001.yaml
  736. Advanced commit filtering example:
  737. .. literalinclude:: /../../tests/scm/fixtures/svn-regions-001.yaml
  738. """
  739. scm = XML.SubElement(xml_parent, 'scm', {'class':
  740. 'hudson.scm.SubversionSCM'})
  741. if 'viewvc-url' in data:
  742. browser = XML.SubElement(
  743. scm, 'browser', {'class': 'hudson.scm.browsers.ViewSVN'})
  744. mapping = [('viewvc-url', 'url', None)]
  745. convert_mapping_to_xml(browser, data, mapping, fail_required=True)
  746. locations = XML.SubElement(scm, 'locations')
  747. def populate_repo_xml(parent, data):
  748. module = XML.SubElement(parent,
  749. 'hudson.scm.SubversionSCM_-ModuleLocation')
  750. mapping = [
  751. ('url', 'remote', None),
  752. ('basedir', 'local', '.')]
  753. convert_mapping_to_xml(module, data, mapping, fail_required=True)
  754. repo_depths = ['infinity', 'empty', 'files', 'immediates', 'unknown']
  755. mapping_optional = [
  756. ('credentials-id', 'credentialsId', None),
  757. ('repo-depth', 'depthOption', 'infinity', repo_depths),
  758. ('ignore-externals', 'ignoreExternalsOption', False)]
  759. convert_mapping_to_xml(module, data,
  760. mapping_optional, fail_required=False)
  761. if 'repos' in data:
  762. repos = data['repos']
  763. for repo in repos:
  764. populate_repo_xml(locations, repo)
  765. elif 'url' in data:
  766. populate_repo_xml(locations, data)
  767. else:
  768. raise JenkinsJobsException("A top level url or repos list must exist")
  769. def populate_additional_credential_xml(parent, data):
  770. module = XML.SubElement(parent,
  771. 'hudson.scm.SubversionSCM_-AdditionalCredentials')
  772. XML.SubElement(module, 'realm').text = data['realm']
  773. if 'credentials-id' in data:
  774. XML.SubElement(module, 'credentialsId').text = data[
  775. 'credentials-id']
  776. if 'additional-credentials' in data:
  777. additional_credentials = XML.SubElement(scm, 'additionalCredentials')
  778. additional_credentials_data = data['additional-credentials']
  779. for additional_credential in additional_credentials_data:
  780. populate_additional_credential_xml(additional_credentials,
  781. additional_credential)
  782. updater = data.get('workspaceupdater', 'wipeworkspace')
  783. if updater == 'wipeworkspace':
  784. updaterclass = 'CheckoutUpdater'
  785. elif updater == 'revertupdate':
  786. updaterclass = 'UpdateWithRevertUpdater'
  787. elif updater == 'emulateclean':
  788. updaterclass = 'UpdateWithCleanUpdater'
  789. elif updater == 'update':
  790. updaterclass = 'UpdateUpdater'
  791. XML.SubElement(scm, 'workspaceUpdater', {'class':
  792. 'hudson.scm.subversion.' + updaterclass})
  793. mapping = [
  794. # option, xml name, default value
  795. ("excluded-regions", 'excludedRegions', []),
  796. ("included-regions", 'includedRegions', []),
  797. ("excluded-users", 'excludedUsers', []),
  798. ("exclusion-revprop-name", 'excludedRevprop', ''),
  799. ("excluded-commit-messages", 'excludedCommitMessages', []),
  800. ("ignore-property-changes-on-directories", 'ignoreDirPropChanges',
  801. False),
  802. ("filter-changelog", 'filterChangelog', False),
  803. ]
  804. for optname, xmlname, defvalue in mapping:
  805. if isinstance(defvalue, list):
  806. val = '\n'.join(data.get(optname, defvalue))
  807. else:
  808. val = data.get(optname, defvalue)
  809. # Skip adding xml entry if default is empty and no value given
  810. if not val and (defvalue in ['', []]):
  811. continue
  812. xe = XML.SubElement(scm, xmlname)
  813. if isinstance(defvalue, bool):
  814. xe.text = str(val).lower()
  815. else:
  816. xe.text = str(val)
  817. def tfs(registry, xml_parent, data):
  818. """yaml: tfs
  819. Specifies the Team Foundation Server repository for this job.
  820. Requires the Jenkins :jenkins-wiki:`Team Foundation Server Plugin
  821. <Team+Foundation+Server+Plugin>`.
  822. **NOTE**: TFS Password must be entered manually on the project if a
  823. user name is specified. The password will be overwritten with an empty
  824. value every time the job is rebuilt with Jenkins Job Builder.
  825. :arg str server-url: The name or URL of the team foundation server.
  826. If the server has been registered on the machine then it is only
  827. necessary to enter the name.
  828. :arg str project-path: The name of the project as it is registered on the
  829. server.
  830. :arg str login: The user name that is registered on the server. The user
  831. name must contain the name and the domain name. Entered as
  832. domain\\\\user or user\@domain (optional).
  833. **NOTE**: You must enter in at least two slashes for the
  834. domain\\\\user format in JJB YAML. It will be rendered normally.
  835. :arg str use-update: If true, Hudson will not delete the workspace at end
  836. of each build. This causes the artifacts from the previous build to
  837. remain when a new build starts. (default true)
  838. :arg str local-path: The folder where all files will be retrieved into.
  839. The folder name is a relative path, under the workspace of the current
  840. job. (default .)
  841. :arg str workspace: The name of the workspace under which the source
  842. should be retrieved. This workspace is created at the start of a
  843. download, and deleted at the end. You can normally omit the property
  844. unless you want to name a workspace to avoid conflicts on the server
  845. (i.e. when you have multiple projects on one server talking to a
  846. Team Foundation Server). (default Hudson-${JOB_NAME}-${NODE_NAME})
  847. The TFS plugin supports the following macros that are replaced in the
  848. workspace name:
  849. * ${JOB_NAME} - The name of the job.
  850. * ${USER_NAME} - The user name that the Hudson server or slave is
  851. running as.
  852. * ${NODE_NAME} - The name of the node/slave that the plugin currently
  853. is executed on. Note that this is not the hostname, this value is
  854. the Hudson configured name of the slave/node.
  855. * ${ENV} - The environment variable that is set on the master or slave.
  856. :arg dict web-access: Adds links in "changes" views within Jenkins to an
  857. external system for browsing the details of those changes. The "Auto"
  858. selection attempts to infer the repository browser from other jobs,
  859. if supported by the SCM and a job with matching SCM details can be
  860. found. (optional, default Auto).
  861. :web-access value:
  862. * **web-url** -- Enter the URL to the TSWA server. The plugin will
  863. strip the last path (if any) of the URL when building URLs for
  864. change set pages and other pages. (optional, default
  865. uses server-url)
  866. Examples:
  867. .. literalinclude:: /../../tests/scm/fixtures/tfs-001.yaml
  868. .. literalinclude:: /../../tests/scm/fixtures/tfs-002.yaml
  869. """
  870. tfs = XML.SubElement(xml_parent, 'scm',
  871. {'class': 'hudson.plugins.tfs.'
  872. 'TeamFoundationServerScm'})
  873. mapping = [
  874. ('server-url', 'serverUrl', ''),
  875. ('project-path', 'projectPath', ''),
  876. ('local-path', 'localPath', '.'),
  877. ('workspace', 'workspaceName', 'Hudson-${JOB_NAME}-${NODE_NAME}'),
  878. # TODO: In the future, it would be nice to have a place that can pull
  879. # passwords into JJB without having to commit them in plaintext. This
  880. # could also integrate nicely with global configuration options.
  881. ('', 'userPassword', ''),
  882. ('login', 'userName', ''),
  883. ('use-update', 'useUpdate', True),
  884. ]
  885. convert_mapping_to_xml(tfs, data, mapping, fail_required=True)
  886. store = data.get('web-access', None)
  887. if isinstance(store, list):
  888. web = XML.SubElement(tfs, 'repositoryBrowser',
  889. {'class': 'hudson.plugins.tfs.browsers.'
  890. 'TeamSystemWebAccessBrowser'})
  891. XML.SubElement(web, 'url').text = str(store[0].get('web-url', None))
  892. elif 'web-access' in data and store is None:
  893. XML.SubElement(tfs, 'repositoryBrowser', {'class': 'hudson.'
  894. 'plugins.tfs.browsers.'
  895. 'TeamSystemWebAccess'
  896. 'Browser'})
  897. def workspace(registry, xml_parent, data):
  898. """yaml: workspace
  899. Specifies the cloned workspace for this job to use as a SCM source.
  900. Requires the Jenkins :jenkins-wiki:`Clone Workspace SCM Plugin
  901. <Clone+Workspace+SCM+Plugin>`.
  902. The job the workspace is cloned from must be configured with an
  903. clone-workspace publisher
  904. :arg str parent-job: The name of the parent job to clone the
  905. workspace from.
  906. :arg str criteria: Set the criteria to determine what build of the parent
  907. project to use. Can be one of 'Any', 'Not Failed' or 'Successful'.
  908. (default Any)
  909. Example:
  910. .. literalinclude:: /../../tests/scm/fixtures/workspace001.yaml
  911. """
  912. workspace = XML.SubElement(xml_parent, 'scm', {'class': 'hudson.plugins.'
  913. 'cloneworkspace.CloneWorkspaceSCM'})
  914. criteria_list = ['Any', 'Not Failed', 'Successful']
  915. criteria = data.get('criteria', 'Any').title()
  916. mapping = [
  917. ('parent-job', 'parentJobName', ''),
  918. ('', 'criteria', criteria, criteria_list)]
  919. convert_mapping_to_xml(workspace, data, mapping, fail_required=True)
  920. def hg(self, xml_parent, data):
  921. """yaml: hg
  922. Specifies the mercurial SCM repository for this job.
  923. Requires the Jenkins :jenkins-wiki:`Mercurial Plugin <Mercurial+Plugin>`.
  924. :arg str url: URL of the hg repository (required)
  925. :arg str credentials-id: ID of credentials to use to connect (optional)
  926. :arg str revision-type: revision type to use (default 'branch')
  927. :arg str revision: the branch or tag name you would like to track
  928. (default 'default')
  929. :arg list(str) modules: reduce unnecessary builds by specifying a list of
  930. "modules" within the repository. A module is a directory name within
  931. the repository that this project lives in. (default '')
  932. :arg bool clean: wipe any local modifications or untracked files in the
  933. repository checkout (default false)
  934. :arg str subdir: check out the Mercurial repository into this
  935. subdirectory of the job's workspace (optional)
  936. :arg bool disable-changelog: do not calculate the Mercurial changelog
  937. for each build (default false)
  938. :arg str browser: what repository browser to use
  939. :browsers supported:
  940. * **auto** - (default)
  941. * **bitbucketweb** - https://bitbucket.org/
  942. * **fisheye** - https://www.atlassian.com/software/fisheye
  943. * **googlecode** - https://code.google.com/
  944. * **hgweb** - https://www.selenic.com/hg/help/hgweb
  945. * **kilnhg** - https://www.fogcreek.com/kiln/
  946. * **rhodecode** - https://rhodecode.com/ (versions >= 1.2)
  947. * **rhodecode-pre-1.2.0** - https://rhodecode.com/ (versions < 1.2)
  948. :arg str browser-url: url for the repository browser
  949. (required if browser is set)
  950. Example:
  951. .. literalinclude:: ../../tests/scm/fixtures/hg02.yaml
  952. """
  953. revision_type_dict = {
  954. 'branch': 'BRANCH',
  955. 'tag': 'TAG',
  956. }
  957. browser = data.get('browser', 'auto')
  958. browserdict = {
  959. 'auto': '',
  960. 'bitbucket': 'BitBucket', # deprecated
  961. 'bitbucketweb': 'BitBucket',
  962. 'fisheye': 'FishEye',
  963. 'googlecode': 'GoogleCode',
  964. 'hgweb': 'HgWeb',
  965. 'kilnhg': 'KilnHG',
  966. 'rhodecode': 'RhodeCode',
  967. 'rhodecode-pre-1.2.0': 'RhodeCodeLegacy'
  968. }
  969. scm = XML.SubElement(xml_parent, 'scm', {'class':
  970. 'hudson.plugins.mercurial.MercurialSCM'})
  971. mapping = [('url', 'source', None)]
  972. convert_mapping_to_xml(scm, data, mapping, fail_required=True)
  973. mapping_optional = [
  974. ('credentials-id', 'credentialsId', None),
  975. ('revision-type', 'revisionType', 'branch', revision_type_dict),
  976. ('revision', 'revision', 'default'),
  977. ('subdir', 'subdir', None),
  978. ('clean', 'clean', False)]
  979. convert_mapping_to_xml(scm, data, mapping_optional, fail_required=False)
  980. modules = data.get('modules', '')
  981. if isinstance(modules, list):
  982. modules = " ".join(modules)
  983. XML.SubElement(scm, 'modules').text = modules
  984. XML.SubElement(scm, 'disableChangeLog').text = str(data.get(
  985. 'disable-changelog', False)).lower()
  986. if browser != 'auto':
  987. bc = XML.SubElement(scm, 'browser',
  988. {'class': 'hudson.plugins.mercurial.browser.' +
  989. browserdict[browser]})
  990. mapping = [('browser-url', 'url', None, browserdict[browser])]
  991. convert_mapping_to_xml(bc, data, mapping, fail_required=True)
  992. def openshift_img_streams(registry, xml_parent, data):
  993. """yaml: openshift-img-streams
  994. Rather than a Build step extension plugin, this is an extension of the
  995. Jenkins SCM plugin, where this baked-in polling mechanism provided by
  996. Jenkins is leveraged by exposing some of the common semantics between
  997. OpenShift ImageStreams (which are abstractions of Docker repositories)
  998. and SCMs - versions / commit IDs of related artifacts
  999. (images vs. programmatics files)
  1000. Requires the Jenkins :jenkins-wiki:`OpenShift
  1001. Pipeline Plugin <OpenShift+Pipeline+Plugin>`._
  1002. :arg str image-stream-name: The name of the ImageStream is what shows up
  1003. in the NAME column if you dump all the ImageStream's with the
  1004. `oc get is` command invocation. (default nodejs-010-centos7)
  1005. :arg str tag: The specific image tag within the ImageStream to monitor.
  1006. (default latest)
  1007. :arg str api-url: This would be the value you specify if you leverage the
  1008. --server option on the OpenShift `oc` command.
  1009. (default \https://openshift.default.svc.cluster.local\)
  1010. :arg str namespace: The value here should be whatever was the output
  1011. form `oc project` when you created the BuildConfig you want to run
  1012. a Build on. (default test)
  1013. :arg str auth-token: The value here is what you supply with the --token
  1014. option when invoking the OpenShift `oc` command. (default '')
  1015. :arg bool verbose: This flag is the toggle for
  1016. turning on or off detailed logging in this plug-in. (default false)
  1017. Full Example:
  1018. .. literalinclude::
  1019. ../../tests/scm/fixtures/openshift-img-streams001.yaml
  1020. :language: yaml
  1021. Minimal Example:
  1022. .. literalinclude::
  1023. ../../tests/scm/fixtures/openshift-img-streams002.yaml
  1024. :language: yaml
  1025. """
  1026. scm = XML.SubElement(xml_parent,
  1027. 'scm', {'class':
  1028. 'com.openshift.jenkins.plugins.pipeline.'
  1029. 'OpenShiftImageStreams'})
  1030. mapping = [
  1031. # option, xml name, default value
  1032. ("image-stream-name", 'imageStreamName', 'nodejs-010-centos7'),
  1033. ("tag", 'tag', 'latest'),
  1034. ("api-url", 'apiURL', 'https://openshift.default.svc.cluster.local'),
  1035. ("namespace", 'namespace', 'test'),
  1036. ("auth-token", 'authToken', ''),
  1037. ("verbose", 'verbose', False),
  1038. ]
  1039. convert_mapping_to_xml(scm, data, mapping, fail_required=True)
  1040. def bzr(registry, xml_parent, data):
  1041. """yaml: bzr
  1042. Specifies the bzr SCM repository for this job.
  1043. Requires the Jenkins :jenkins-wiki:`Bazaar Plugin <Bazaar+Plugin>`.
  1044. :arg str url: URL of the bzr branch (required)
  1045. :arg bool clean-tree: Clean up the workspace (using bzr) before pulling
  1046. the branch (default false)
  1047. :arg bool lightweight-checkout: Use a lightweight checkout instead of a
  1048. full branch (default false)
  1049. :arg str browser: The repository browser to use.
  1050. :browsers supported:
  1051. * **auto** - (default)
  1052. * **loggerhead** - as used by Launchpad
  1053. * **opengrok** - https://opengrok.github.io/OpenGrok/
  1054. :arg str browser-url:
  1055. URL for the repository browser (required if browser is set).
  1056. :arg str opengrok-root-module:
  1057. Root module for OpenGrok (required if browser is opengrok).
  1058. Example:
  1059. .. literalinclude:: /../../tests/scm/fixtures/bzr001.yaml
  1060. :language: yaml
  1061. """
  1062. mapping = [
  1063. # option, xml name, default value (text), attributes (hard coded)
  1064. ('url', 'source', None),
  1065. ('clean-tree', 'cleantree', False),
  1066. ('lightweight-checkout', 'checkout', False),
  1067. ]
  1068. scm_element = XML.SubElement(
  1069. xml_parent, 'scm', {'class': 'hudson.plugins.bazaar.BazaarSCM'})
  1070. convert_mapping_to_xml(scm_element, data, mapping, fail_required=True)
  1071. browser_name_to_class = {
  1072. 'loggerhead': 'Loggerhead',
  1073. 'opengrok': 'OpenGrok',
  1074. }
  1075. browser = data.get('browser', 'auto')
  1076. if browser == 'auto':
  1077. return
  1078. if browser not in browser_name_to_class:
  1079. raise InvalidAttributeError('browser', browser,
  1080. browser_name_to_class.keys())
  1081. browser_element = XML.SubElement(
  1082. scm_element,
  1083. 'browser',
  1084. {'class': 'hudson.plugins.bazaar.browsers.{0}'.format(
  1085. browser_name_to_class[browser])})
  1086. mapping = [('browser-url', 'url', None)]
  1087. convert_mapping_to_xml(browser_element, data, mapping, fail_required=True)
  1088. if browser == 'opengrok':
  1089. mapping = [('opengrok-root-module', 'rootModule', None)]
  1090. convert_mapping_to_xml(browser_element,
  1091. data, mapping, fail_required=True)
  1092. def url(registry, xml_parent, data):
  1093. """yaml: url
  1094. Watch for changes in, and download an artifact from a particular url.
  1095. Requires the Jenkins :jenkins-wiki:`URL SCM <URL+SCM>`.
  1096. :arg list url-list: List of URLs to watch. (required)
  1097. :arg bool clear-workspace: If set to true, clear the workspace before
  1098. downloading the artifact(s) specified in url-list. (default false)
  1099. Examples:
  1100. .. literalinclude:: ../../tests/scm/fixtures/url001.yaml
  1101. :language: yaml
  1102. .. literalinclude:: ../../tests/scm/fixtures/url002.yaml
  1103. :language: yaml
  1104. """
  1105. scm = XML.SubElement(xml_parent, 'scm', {'class':
  1106. 'hudson.plugins.URLSCM.URLSCM'})
  1107. urls = XML.SubElement(scm, 'urls')
  1108. for data_url in data['url-list']:
  1109. url_tuple = XML.SubElement(
  1110. urls, 'hudson.plugins.URLSCM.URLSCM_-URLTuple')
  1111. mapping = [('', 'urlString', data_url)]
  1112. convert_mapping_to_xml(url_tuple, data, mapping, fail_required=True)
  1113. mapping = [('clear-workspace', 'clearWorkspace', False)]
  1114. convert_mapping_to_xml(scm, data, mapping, fail_required=True)
  1115. def dimensions(registry, xml_parent, data):
  1116. """yaml: dimensions
  1117. Specifies the Dimensions SCM repository for this job.
  1118. Requires Jenkins :jenkins-wiki:`Dimensions Plugin <Dimensions+Plugin>`.
  1119. :arg str project: Project name of format PRODUCT_ID:PROJECT_NAME (required)
  1120. :arg str permissions: Default Permissions for updated files
  1121. (default: DEFAULT)
  1122. :Permissions:
  1123. * **DEFAULT**
  1124. * **READONLY**
  1125. * **WRITABLE**
  1126. :arg str eol: End of line (default: DEFAULT)
  1127. :End of line:
  1128. * **DEFAULT**
  1129. * **UNIX**
  1130. * **WINDOWS**
  1131. * **UNCHANGED**
  1132. :arg list folders: Folders to monitor (default /)
  1133. :arg list exclude: Paths to exclude from monitor
  1134. :arg str username: Repository username for this job
  1135. :arg str password: Repository password for this job
  1136. :arg str server: Dimensions server for this job
  1137. :arg str database: Dimensions database for this job.
  1138. Format must be database@dsn
  1139. :arg bool update: Use update (default false)
  1140. :arg bool clear-workspace: Clear workspace prior to build (default false)
  1141. :arg bool force-build: Force build even if the repository SCM checkout
  1142. operation fails (default false)
  1143. :arg bool overwrite-modified: Overwrite files in worspace from
  1144. repository files (default false)
  1145. :arg bool expand-vars: Expand substitution variables (default false)
  1146. :arg bool no-metadata: Checkout files with no metadata (default false)
  1147. :arg bool maintain-timestamp: Maintain file timestamp from Dimensions
  1148. (default false)
  1149. :arg bool slave-checkout: Force slave based checkout (default false)
  1150. :arg str timezone: Server timezone
  1151. :arg str web-url: Dimensions Web URL
  1152. Examples:
  1153. .. literalinclude:: /../../tests/scm/fixtures/dimensions-minimal.yaml
  1154. :language: yaml
  1155. .. literalinclude:: /../../tests/scm/fixtures/dimensions-full.yaml
  1156. :language: yaml
  1157. """
  1158. scm = XML.SubElement(
  1159. xml_parent,
  1160. 'scm', {'class': 'hudson.plugins.dimensionsscm.DimensionsSCM'})
  1161. # List to check against for valid permission
  1162. perm = ['DEFAULT', 'READONLY', 'WRITABLE']
  1163. # List to check against for valid end of line
  1164. eol = ['DEFAULT', 'UNIX', 'WINDOWS', 'UNCHANGED']
  1165. mapping = [
  1166. # option, xml name, default value (text), attributes (hard coded)
  1167. ('project', 'project', None),
  1168. ('permissions', 'permissions', 'DEFAULT', perm),
  1169. ('eol', 'eol', 'DEFAULT', eol),
  1170. ('update', 'canJobUpdate', False),
  1171. ('clear-workspace', 'canJobDelete', False),
  1172. ('force-build', 'canJobForce', False),
  1173. ('overwrite-modified', 'canJobRevert', False),
  1174. ('expand-vars', 'canJobExpand', False),
  1175. ('no-metadata', 'canJobNoMetadata', False),
  1176. ('maintain-timestamp', 'canJobNoTouch', False),
  1177. ('slave-checkout', 'forceAsSlave', False),
  1178. ]
  1179. convert_mapping_to_xml(scm, data, mapping, fail_required=True)
  1180. # Folders to monitor. Default '/'
  1181. folders = XML.SubElement(scm, 'folders')
  1182. if 'folders' in data:
  1183. for folder in data['folders']:
  1184. XML.SubElement(folders, 'string').text = folder
  1185. else:
  1186. XML.SubElement(folders, 'string').text = '/'
  1187. # Excluded paths
  1188. exclude = XML.SubElement(scm, 'pathsToExclude')
  1189. if 'exclude' in data:
  1190. for exc in data['exclude']:
  1191. XML.SubElement(exclude, 'string').text = exc
  1192. optional_mapping = [
  1193. # option, xml name, default value (text), attributes (hard coded)
  1194. ('username', 'jobUserName', None),
  1195. ('password', 'jobPasswd', None),
  1196. ('server', 'jobServer', None),
  1197. ('database', 'jobDatabase', None),
  1198. ('timezone', 'jobTimeZone', None),
  1199. ('web-url', 'jobWebUrl', None),
  1200. ]
  1201. convert_mapping_to_xml(scm, data, optional_mapping, fail_required=False)
  1202. def accurev(registry, xml_parent, data):
  1203. """yaml: accurev
  1204. Specifies the AccuRev SCM repository for this job.
  1205. Requires the Jenkins :jenkins-wiki:`AccuRev Plugin <AccuRev+Plugin>`.
  1206. :arg str depot: Depot you want to use for the current job (optional)
  1207. :arg str stream: Stream where the build will be generated from (optional)
  1208. :arg str server-name: AccuRev server you are using
  1209. for your builds (required)
  1210. :arg bool ignore-parent-changes: Ignore possibility
  1211. of changes in the parent stream (default false)
  1212. :arg bool clean-reference-tree: Deletes any external files
  1213. in reference tree (default false)
  1214. :arg bool build-from-snapshot: Creates snapshot
  1215. of the target stream, then populates and
  1216. builds from that snapshot (default false)
  1217. :arg bool do-not-pop-content: If checkbox is on, elements
  1218. are not populating vice versa (default false)
  1219. :arg str workspace: Name of existing workspace (optional)
  1220. :arg str reference-tree: Name of the reference tree (optional)
  1221. :arg str directory-offset: Relative directory path from
  1222. the default Jenkins workspace location
  1223. where the files from the stream, workspace,
  1224. or reference tree should be retrieved from. (optional)
  1225. :arg str sub-path: Makes a "best effort" to ensure
  1226. that only the sub-path is populated (optional)
  1227. :arg str filter-poll-scm: Specify directories or
  1228. files you want Jenkins to check before starting a build (optional)
  1229. :arg str snapshot-name-format: Naming conventions
  1230. for the snapshot in this field (optional)
  1231. Example:
  1232. .. literalinclude:: /../../tests/scm/fixtures/accurev001.yaml
  1233. """
  1234. scm = XML.SubElement(xml_parent,
  1235. 'scm', {'class': 'hudson.plugins.accurev.AccurevSCM'})
  1236. mapping = [
  1237. ('depot', 'depot', None),
  1238. ('stream', 'stream', None),
  1239. ('server-name', 'serverName', None),
  1240. ('ignore-parent-changes', 'ignoreStreamParent', False),
  1241. ('clean-reference-tree', 'cleanreftree', False),
  1242. ('build-from-snapshot', 'useSnapshot', False),
  1243. ('do-not-pop-content', 'dontPopContent', False),
  1244. ]
  1245. convert_mapping_to_xml(scm, data, mapping, fail_required=True)
  1246. additional_mapping = [
  1247. ('workspace', 'workspace', None),
  1248. ('reference-tree', 'reftree', None),
  1249. ('directory-offset', 'directoryOffset', None),
  1250. ('sub-path', 'subPath', None),
  1251. ('filter-poll-scm', 'filterForPollSCM', None),
  1252. ('snapshot-name-format', 'snapshotNameFormat', None),
  1253. ]
  1254. convert_mapping_to_xml(scm, data, additional_mapping, fail_required=False)
  1255. class SCM(jenkins_jobs.modules.base.Base):
  1256. sequence = 30
  1257. component_type = 'scm'
  1258. component_list_type = 'scm'
  1259. def gen_xml(self, xml_parent, data):
  1260. # multibranch-pipeline scm implementation is incompatible with SCM
  1261. if data.get('project-type') in ['multibranch', 'multibranch-defaults']:
  1262. logging.debug("SCM Module skipped for multibranch project-type.")
  1263. return
  1264. scms_parent = XML.Element('scms')
  1265. for scm in data.get('scm', []):
  1266. self.registry.dispatch('scm', scms_parent, scm)
  1267. scms_count = len(scms_parent)
  1268. if scms_count == 0:
  1269. XML.SubElement(xml_parent, 'scm', {'class': 'hudson.scm.NullSCM'})
  1270. elif scms_count == 1:
  1271. xml_parent.append(scms_parent[0])
  1272. else:
  1273. class_name = 'org.jenkinsci.plugins.multiplescms.MultiSCM'
  1274. xml_attribs = {'class': class_name}
  1275. xml_parent = XML.SubElement(xml_parent, 'scm', xml_attribs)
  1276. for scms_child in scms_parent:
  1277. try:
  1278. scms_child.tag = scms_child.attrib['class']
  1279. del(scms_child.attrib['class'])
  1280. except KeyError:
  1281. pass
  1282. xml_parent.append(scms_parent)
  1283. class PipelineSCM(jenkins_jobs.modules.base.Base):
  1284. sequence = 30
  1285. component_type = 'pipeline-scm'
  1286. component_list_type = 'pipeline-scm'
  1287. def gen_xml(self, xml_parent, data):
  1288. definition_parent = xml_parent.find('definition')
  1289. pipeline_dict = data.get(self.component_type, {})
  1290. scms = pipeline_dict.get('scm')
  1291. if scms:
  1292. scms_count = len(scms)
  1293. if scms_count == 0:
  1294. raise JenkinsJobsException("'scm' missing or empty")
  1295. elif scms_count == 1:
  1296. self.registry.dispatch('scm', definition_parent, scms[0])
  1297. mapping = [('script-path', 'scriptPath', 'Jenkinsfile'),
  1298. ('lightweight-checkout', 'lightweight', None,
  1299. [True, False])]
  1300. convert_mapping_to_xml(definition_parent, pipeline_dict,
  1301. mapping, fail_required=False)
  1302. else:
  1303. raise JenkinsJobsException('Only one SCM can be specified '
  1304. 'as pipeline-scm')