Debian Codegraph @

lib/ansible/modules/subversion.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright: (c) 2012, Michael DeHaan <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 from __future__ import annotations
7
8
9 DOCUMENTATION = """
10 ---
11 module: subversion
12 short_description: Deploys a subversion repository
13 description:
14 - Deploy given repository URL / revision to dest. If dest exists, update to the specified revision, otherwise perform a checkout.
15 version_added: "0.7"
16 author:
17 - Dane Summers (@dsummersl) <[email protected]>
18 options:
19 repo:
20 description:
21 - The subversion URL to the repository.
22 type: str
23 required: true
24 aliases: [ name, repository ]
25 dest:
26 description:
27 - Absolute path where the repository should be deployed.
28 - The destination directory must be specified unless O(checkout=no), O(update=no), and O(export=no).
29 type: path
30 revision:
31 description:
32 - Specific revision to checkout.
33 type: str
34 default: HEAD
35 aliases: [ rev, version ]
36 force:
37 description:
38 - If V(true), modified files will be discarded. If V(false), module will fail if it encounters modified files.
39 Prior to 1.9 the default was V(true).
40 type: bool
41 default: "no"
42 in_place:
43 description:
44 - If the directory exists, then the working copy will be checked-out over-the-top using
45 C(svn checkout --force); if force is specified then existing files with different content are reverted.
46 type: bool
47 default: "no"
48 version_added: "2.6"
49 username:
50 description:
51 - C(--username) parameter passed to svn.
52 type: str
53 password:
54 description:
55 - C(--password) parameter passed to svn when svn is less than version 1.10.0. This is not secure and
56 the password will be leaked to argv.
57 - C(--password-from-stdin) parameter when svn is greater or equal to version 1.10.0.
58 type: str
59 executable:
60 description:
61 - Path to svn executable to use. If not supplied,
62 the normal mechanism for resolving binary paths will be used.
63 type: path
64 version_added: "1.4"
65 checkout:
66 description:
67 - If V(false), do not check out the repository if it does not exist locally.
68 type: bool
69 default: "yes"
70 version_added: "2.3"
71 update:
72 description:
73 - If V(false), do not retrieve new revisions from the origin repository.
74 type: bool
75 default: "yes"
76 version_added: "2.3"
77 export:
78 description:
79 - If V(true), do export instead of checkout/update.
80 type: bool
81 default: "no"
82 version_added: "1.6"
83 switch:
84 description:
85 - If V(false), do not call svn switch before update.
86 default: "yes"
87 version_added: "2.0"
88 type: bool
89 validate_certs:
90 description:
91 - If V(false), passes the C(--trust-server-cert) flag to svn.
92 - If V(true), does not pass the flag.
93 default: "no"
94 version_added: "2.11"
95 type: bool
96 extends_documentation_fragment: action_common_attributes
97 attributes:
98 check_mode:
99 support: full
100 diff_mode:
101 support: none
102 platform:
103 platforms: posix
104 notes:
105 - This module does not handle externals.
106
107 requirements:
108 - subversion (the command line tool with C(svn) entrypoint)
109 """
110
111 EXAMPLES = """
112 - name: Checkout subversion repository to specified folder
113 ansible.builtin.subversion:
114 repo: svn+ssh://an.example.org/path/to/repo
115 dest: /src/checkout
116
117 - name: Export subversion directory to folder
118 ansible.builtin.subversion:
119 repo: svn+ssh://an.example.org/path/to/repo
120 dest: /src/export
121 export: yes
122
123 - name: Get information about the repository whether or not it has already been cloned locally
124 ansible.builtin.subversion:
125 repo: svn+ssh://an.example.org/path/to/repo
126 dest: /src/checkout
127 checkout: no
128 update: no
129 """
130
131 RETURN = r"""#"""
132
133 import os
134 import re
135
136 from ansible.module_utils.basic import AnsibleModule
137 from ansible.module_utils.common.locale import get_best_parsable_locale
138 from ansible.module_utils.compat.version import LooseVersion
139
140
141 class Subversion(object):
142
143 # Example text matched by the regexp:
144 # Révision : 1889134
145 # 版本: 1889134
146 # Revision: 1889134
147 REVISION_RE = r'^\w+\s?:\s+\d+$'
148
149 def __init__(self, module, dest, repo, revision, username, password, svn_path, validate_certs):
150 self.module = module
151 self.dest = dest
152 self.repo = repo
153 self.revision = revision
154 self.username = username
155 self.password = password
156 self.svn_path = svn_path
157 self.validate_certs = validate_certs
158
159 def has_option_password_from_stdin(self):
160 rc, version, err = self.module.run_command([self.svn_path, '--version', '--quiet'], check_rc=True)
161 return LooseVersion(version) >= LooseVersion('1.10.0')
162
163 def _exec(self, args, check_rc=True):
164 """Execute a subversion command, and return output. If check_rc is False, returns the return code instead of the output."""
165 bits = [
166 self.svn_path,
167 '--non-interactive',
168 '--no-auth-cache',
169 ]
170 if not self.validate_certs:
171 bits.append('--trust-server-cert')
172 stdin_data = None
173 if self.username:
174 bits.extend(["--username", self.username])
175 if self.password:
176 if self.has_option_password_from_stdin():
177 bits.append("--password-from-stdin")
178 stdin_data = self.password
179 else:
180 self.module.warn("The authentication provided will be used on the svn command line and is not secure. "
181 "To securely pass credentials, upgrade svn to version 1.10.0 or greater.")
182 bits.extend(["--password", self.password])
183 bits.extend(args)
184 rc, out, err = self.module.run_command(bits, check_rc, data=stdin_data)
185
186 if check_rc:
187 return out.splitlines()
188 else:
189 return rc
190
191 def is_svn_repo(self):
192 """Checks if path is a SVN Repo."""
193 rc = self._exec(["info", self.dest], check_rc=False)
194 return rc == 0
195
196 def checkout(self, force=False):
197 """Creates new svn working directory if it does not already exist."""
198 cmd = ["checkout"]
199 if force:
200 cmd.append("--force")
201 cmd.extend(["-r", self.revision, self.repo, self.dest])
202 self._exec(cmd)
203
204 def export(self, force=False):
205 """Export svn repo to directory"""
206 cmd = ["export"]
207 if force:
208 cmd.append("--force")
209 cmd.extend(["-r", self.revision, self.repo, self.dest])
210
211 self._exec(cmd)
212
213 def switch(self):
214 """Change working directory's repo."""
215 # switch to ensure we are pointing at correct repo.
216 # it also updates!
217 output = self._exec(["switch", "--revision", self.revision, self.repo, self.dest])
218 for line in output:
219 if re.search(r'^[ABDUCGE]\s', line):
220 return True
221 return False
222
223 def update(self):
224 """Update existing svn working directory."""
225 output = self._exec(["update", "-r", self.revision, self.dest])
226
227 for line in output:
228 if re.search(r'^[ABDUCGE]\s', line):
229 return True
230 return False
231
232 def revert(self):
233 """Revert svn working directory."""
234 output = self._exec(["revert", "-R", self.dest])
235 for line in output:
236 if re.search(r'^Reverted ', line) is None:
237 return True
238 return False
239
240 def get_revision(self):
241 """Revision and URL of subversion working directory."""
242 text = '\n'.join(self._exec(["info", self.dest]))
243 rev = re.search(self.REVISION_RE, text, re.MULTILINE)
244 if rev:
245 rev = rev.group(0)
246 else:
247 rev = 'Unable to get revision'
248
249 url = re.search(r'^URL\s?:.*$', text, re.MULTILINE)
250 if url:
251 url = url.group(0)
252 else:
253 url = 'Unable to get URL'
254
255 return rev, url
256
257 def get_remote_revision(self):
258 """Revision and URL of subversion working directory."""
259 text = '\n'.join(self._exec(["info", self.repo]))
260 rev = re.search(self.REVISION_RE, text, re.MULTILINE)
261 if rev:
262 rev = rev.group(0)
263 else:
264 rev = 'Unable to get remote revision'
265 return rev
266
267 def has_local_mods(self):
268 """True if revisioned files have been added or modified. Unrevisioned files are ignored."""
269 lines = self._exec(["status", "--quiet", "--ignore-externals", self.dest])
270 # The --quiet option will return only modified files.
271 # Match only revisioned files, i.e. ignore status '?'.
272 regex = re.compile(r'^[^?X]')
273 # Has local mods if more than 0 modified revisioned files.
274 return len(list(filter(regex.match, lines))) > 0
275
276 def needs_update(self):
277 curr, url = self.get_revision()
278 out2 = '\n'.join(self._exec(["info", "-r", self.revision, self.dest]))
279 head = re.search(self.REVISION_RE, out2, re.MULTILINE)
280 if head:
281 head = head.group(0)
282 else:
283 head = 'Unable to get revision'
284 rev1 = int(curr.split(':')[1].strip())
285 rev2 = int(head.split(':')[1].strip())
286 change = False
287 if rev1 < rev2:
288 change = True
289 return change, curr, head
290
291
292 def main():
293 module = AnsibleModule(
294 argument_spec=dict(
295 dest=dict(type='path'),
296 repo=dict(type='str', required=True, aliases=['name', 'repository']),
297 revision=dict(type='str', default='HEAD', aliases=['rev', 'version']),
298 force=dict(type='bool', default=False),
299 username=dict(type='str'),
300 password=dict(type='str', no_log=True),
301 executable=dict(type='path'),
302 export=dict(type='bool', default=False),
303 checkout=dict(type='bool', default=True),
304 update=dict(type='bool', default=True),
305 switch=dict(type='bool', default=True),
306 in_place=dict(type='bool', default=False),
307 validate_certs=dict(type='bool', default=False),
308 ),
309 supports_check_mode=True,
310 )
311
312 dest = module.params['dest']
313 repo = module.params['repo']
314 revision = module.params['revision']
315 force = module.params['force']
316 username = module.params['username']
317 password = module.params['password']
318 svn_path = module.params['executable'] or module.get_bin_path('svn', True)
319 export = module.params['export']
320 switch = module.params['switch']
321 checkout = module.params['checkout']
322 update = module.params['update']
323 in_place = module.params['in_place']
324 validate_certs = module.params['validate_certs']
325
326 # We screenscrape a huge amount of svn commands so use C locale anytime we
327 # call run_command()
328 locale = get_best_parsable_locale(module)
329 module.run_command_environ_update = dict(LANG=locale, LC_MESSAGES=locale)
330
331 if not dest and (checkout or update or export):
332 module.fail_json(msg="the destination directory must be specified unless checkout=no, update=no, and export=no")
333
334 svn = Subversion(module, dest, repo, revision, username, password, svn_path, validate_certs)
335
336 if not export and not update and not checkout:
337 module.exit_json(changed=False, after=svn.get_remote_revision())
338 if export or not os.path.exists(dest):
339 before = None
340 local_mods = False
341 if module.check_mode:
342 module.exit_json(changed=True)
343 elif not export and not checkout:
344 module.exit_json(changed=False)
345 if not export and checkout:
346 svn.checkout()
347 files_changed = True
348 else:
349 svn.export(force=force)
350 files_changed = True
351 elif svn.is_svn_repo():
352 # Order matters. Need to get local mods before switch to avoid false
353 # positives. Need to switch before revert to ensure we are reverting to
354 # correct repo.
355 if not update:
356 module.exit_json(changed=False)
357 if module.check_mode:
358 if svn.has_local_mods() and not force:
359 module.fail_json(msg="ERROR: modified files exist in the repository.")
360 check, before, after = svn.needs_update()
361 module.exit_json(changed=check, before=before, after=after)
362 files_changed = False
363 before = svn.get_revision()
364 local_mods = svn.has_local_mods()
365 if switch:
366 files_changed = svn.switch() or files_changed
367 if local_mods:
368 if force:
369 files_changed = svn.revert() or files_changed
370 else:
371 module.fail_json(msg="ERROR: modified files exist in the repository.")
372 files_changed = svn.update() or files_changed
373 elif in_place:
374 before = None
375 svn.checkout(force=True)
376 files_changed = True
377 local_mods = svn.has_local_mods()
378 if local_mods and force:
379 svn.revert()
380 else:
381 module.fail_json(msg="ERROR: %s folder already exists, but its not a subversion repository." % (dest,))
382
383 if export:
384 module.exit_json(changed=True)
385 else:
386 after = svn.get_revision()
387 changed = files_changed or local_mods
388 module.exit_json(changed=changed, before=before, after=after)
389
390
391 if __name__ == '__main__':
392 main()