Debian Codegraph @

jenkins_jobs/xml_config.py

raw
1 #!/usr/bin/env python
2 # Copyright (C) 2015 OpenStack, LLC.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 # Manage Jenkins XML config file output.
17
18 import hashlib
19 import pkg_resources
20 import sys
21 from xml.dom import minidom
22 import xml.etree.ElementTree as XML
23
24 from jenkins_jobs.errors import JenkinsJobsException
25
26 __all__ = ["XmlJobGenerator", "XmlJob"]
27
28
29 def remove_ignorable_whitespace(node):
30 """Remove insignificant whitespace from XML nodes
31
32 It should only remove whitespace in between elements and sub elements.
33 This should be safe for Jenkins due to how it's XML serialization works
34 but may not be valid for other XML documents. So use this method with
35 caution outside of this specific library.
36 """
37 # strip tail whitespace if it's not significant
38 if node.tail and node.tail.strip() == "":
39 node.tail = None
40
41 for child in node:
42 # only strip whitespace from the text node if there are subelement
43 # nodes as this means we are removing leading whitespace before such
44 # sub elements. Otherwise risk removing whitespace from an element
45 # that only contains whitespace
46 if node.text and node.text.strip() == "":
47 node.text = None
48 remove_ignorable_whitespace(child)
49
50
51 class XmlJob(object):
52 def __init__(self, xml, name):
53 self.xml = xml
54 self.name = name
55
56 def md5(self):
57 if sys.version_info[:2] >= (3, 6):
58 # allows md5 use on fips-enabled systems
59 hash_func = hashlib.new("md5", usedforsecurity=False)
60 hash_func.update(self.output())
61 return hash_func.hexdigest()
62 else:
63 return hashlib.md5(self.output()).hexdigest()
64
65 def output(self):
66 out = minidom.parseString(XML.tostring(self.xml, encoding="UTF-8"))
67 return out.toprettyxml(indent=" ", encoding="utf-8")
68
69
70 class XmlGenerator(object):
71 """A super-class to capture common XML generation logic.
72
73 Sub-classes should define three attribute: ``entry_point_group``,
74 ``kind_attribute`` and ``kind_default``. The value of ``kind_attribute``
75 in the given data dictionary (or ``kind_default`` if it isn't present)
76 will be used to filter the entry points in ``entry_point_group``; the
77 module so found will be used to generate the XML object.
78 """
79
80 def __init__(self, registry):
81 self.registry = registry
82
83 def generateXML(self, data_list):
84 xml_objs = []
85 for data in data_list:
86 try:
87 xml_objs.append(self._getXMLForData(data.data))
88 except JenkinsJobsException as x:
89 raise x.with_ctx_list(data.context)
90 return xml_objs
91
92 def _getXMLForData(self, data):
93 kind = data.get(self.kind_attribute, self.kind_default)
94
95 for ep in pkg_resources.iter_entry_points(
96 group=self.entry_point_group, name=kind
97 ):
98 Mod = ep.load()
99 mod = Mod(self.registry)
100 xml = mod.root_xml(data)
101 if "view-type" not in data:
102 self._gen_xml(xml, data)
103 obj = XmlJob(xml, data["name"])
104 return obj
105
106 names = [
107 ep.name
108 for ep in pkg_resources.iter_entry_points(group=self.entry_point_group)
109 ]
110 raise JenkinsJobsException(
111 "Unrecognized {}: {} (supported types are: {})".format(
112 self.kind_attribute, kind, ", ".join(names)
113 )
114 )
115
116 def _gen_xml(self, xml, data):
117 for module in self.registry.modules:
118 if hasattr(module, "gen_xml"):
119 module.gen_xml(xml, data)
120
121
122 class XmlJobGenerator(XmlGenerator):
123 """Class for generating Jenkins Configuration XML.
124
125 Generates XML from a compatible intermediate representation of Jenkins Jobs.
126 """
127
128 entry_point_group = "jenkins_jobs.projects"
129 kind_attribute = "project-type"
130 kind_default = "freestyle"
131
132
133 class XmlViewGenerator(XmlGenerator):
134 """Class for generating Jenkins Configuration XML.
135
136 Generates XML from a compatible intermediate representation of Jenkins Views.
137 """
138
139 entry_point_group = "jenkins_jobs.views"
140 kind_attribute = "view-type"
141 kind_default = "list"