blob: e28bed8648f7b35f75d06912ee7379e7a7c27cba [file] [log] [blame]
Jakub Josefe3807982016-12-15 11:54:51 +01001# -*- coding: utf-8 -*-
2
3# Import Python libs
4from __future__ import absolute_import
5import difflib
6import logging
7
8# Import Salt libs
9import salt.ext.six as six
10import salt.utils
11
12# Import XML parser
13import xml.etree.ElementTree as ET
14
15log = logging.getLogger(__name__)
16
17
18def _elements_equal(e1, e2):
19 if e1.tag != e2.tag:
20 return False
21 if e1.text != e2.text:
22 return False
23 if e1.tail != e2.tail:
24 return False
25 if e1.attrib != e2.attrib:
26 return False
27 if len(e1) != len(e2):
28 return False
29 return all(_elements_equal(c1, c2) for c1, c2 in zip(e1, e2))
30
31
32def present(name,
33 config=None,
34 **kwargs):
35 '''
36 Ensure the job is present in the Jenkins
37 configured jobs
38 name
39 The unique name for the Jenkins job
40 config
41 The Salt URL for the file to use for
42 configuring the job.
43 '''
44
45 ret = {'name': name,
46 'result': True,
47 'changes': {},
48 'comment': ['Job {0} is up to date.'.format(name)]}
49
50 _job_exists = __salt__['jenkins.job_exists'](name)
51
52 if _job_exists:
53 _current_job_config = __salt__['jenkins.get_job_config'](name)
54 buf = six.moves.StringIO(_current_job_config)
55 oldXML = ET.fromstring(buf.read())
56
57 cached_source_path = __salt__['cp.cache_file'](config, __env__)
58 with salt.utils.fopen(cached_source_path) as _fp:
59 newXML = ET.fromstring(_fp.read())
60 if not _elements_equal(oldXML, newXML):
61 diff = difflib.unified_diff(
62 oldXML.tostring(), newXML.tostring(), lineterm='')
63 __salt__['jenkins.update_job'](name, config, __env__)
64 ret['changes'] = ''.join(diff)
65 ret['comment'].append('Job {0} updated.'.format(name))
66
67 else:
68 cached_source_path = __salt__['cp.cache_file'](config, __env__)
69 with salt.utils.fopen(cached_source_path) as _fp:
70 new_config_xml = _fp.read()
71
72 __salt__['jenkins.create_job'](name, config, __env__)
73
74 buf = six.moves.StringIO(new_config_xml)
75 _current_job_config = buf.readlines()
76
77 diff = difflib.unified_diff('', buf, lineterm='')
78 ret['changes'] = ''.join(diff)
79 ret['comment'].append('Job {0} added.'.format(name))
80
81 ret['comment'] = '\n'.join(ret['comment'])
82 return ret
83
84
85def absent(name,
86 **kwargs):
87 '''
88 Ensure the job is present in the Jenkins
89 configured jobs
90
91 name
92 The name of the Jenkins job to remove.
93
94 '''
95
96 ret = {'name': name,
97 'result': True,
98 'changes': {},
99 'comment': []}
100
101 _job_exists = __salt__['jenkins.job_exists'](name)
102
103 if _job_exists:
104 __salt__['jenkins.delete_job'](name)
105 ret['comment'] = 'Job {0} deleted.'.format(name)
106 else:
107 ret['comment'] = 'Job {0} already absent.'.format(name)
108 return ret