Debian Codegraph @

ansible_collections/community/general/plugins/modules/hg.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2013, Yeukhon Wong <[email protected]>
4 # Copyright (c) 2014, Nate Coraor <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import annotations
9
10 DOCUMENTATION = r"""
11 module: hg
12 short_description: Manages Mercurial (hg) repositories
13 description:
14 - Manages Mercurial (hg) repositories. Supports SSH, HTTP/S and local address.
15 author: "Yeukhon Wong (@yeukhon)"
16 extends_documentation_fragment:
17 - community.general._attributes
18 attributes:
19 check_mode:
20 support: none
21 diff_mode:
22 support: none
23 options:
24 repo:
25 description:
26 - The repository address.
27 required: true
28 aliases: [name]
29 type: str
30 dest:
31 description:
32 - Absolute path of where the repository should be cloned to. This parameter is required, unless clone and update are
33 set to no.
34 type: path
35 revision:
36 description:
37 - Equivalent C(-r) option in hg command which could be the changeset, revision number, branch name or even tag.
38 aliases: [version]
39 type: str
40 force:
41 description:
42 - Discards uncommitted changes. Runs C(hg update -C).
43 type: bool
44 default: false
45 purge:
46 description:
47 - Deletes untracked files. Runs C(hg purge).
48 type: bool
49 default: false
50 update:
51 description:
52 - If V(false), do not retrieve new revisions from the origin repository.
53 type: bool
54 default: true
55 clone:
56 description:
57 - If V(false), do not clone the repository if it does not exist locally.
58 type: bool
59 default: true
60 executable:
61 description:
62 - Path to C(hg) executable to use. If not supplied, the normal mechanism for resolving binary paths is used.
63 type: str
64 notes:
65 - This module does not support push capability. See U(https://github.com/ansible/ansible/issues/31156).
66 - 'If the task seems to be hanging, first verify remote host is in C(known_hosts). SSH prompts user to authorize the first
67 contact with a remote host. To avoid this prompt, one solution is to add the remote host public key in C(/etc/ssh/ssh_known_hosts)
68 before calling the hg module, with the following command: C(ssh-keyscan remote_host.com >> /etc/ssh/ssh_known_hosts).'
69 - As per 01 Dec 2018, Bitbucket has dropped support for TLSv1 and TLSv1.1 connections. As such, if the underlying system
70 still uses a Python version below 2.7.9, you are bound to have issues checking out bitbucket repositories. See
71 U(https://bitbucket.org/blog/deprecating-tlsv1-tlsv1-1-2018-12-01).
72 """
73
74 EXAMPLES = r"""
75 - name: Ensure the current working copy is inside the stable branch and deletes untracked files if any.
76 community.general.hg:
77 repo: https://bitbucket.org/user/repo1
78 dest: /home/user/repo1
79 revision: stable
80 purge: true
81
82 - name: Get information about the repository whether or not it has already been cloned locally.
83 community.general.hg:
84 repo: git://bitbucket.org/user/repo
85 dest: /srv/checkout
86 clone: false
87 update: false
88 """
89
90 import os
91
92 from ansible.module_utils.basic import AnsibleModule
93
94
95 class Hg:
96 def __init__(self, module, dest, repo, revision, hg_path):
97 self.module = module
98 self.dest = dest
99 self.repo = repo
100 self.revision = revision
101 self.hg_path = hg_path
102
103 def _command(self, args_list):
104 (rc, out, err) = self.module.run_command([self.hg_path] + args_list)
105 return (rc, out, err)
106
107 def _list_untracked(self):
108 args = ["purge", "--config", "extensions.purge=", "-R", self.dest, "--print"]
109 return self._command(args)
110
111 def get_revision(self):
112 """
113 hg id -b -i -t returns a string in the format:
114 "<changeset>[+] <branch_name> <tag>"
115 This format lists the state of the current working copy,
116 and indicates whether there are uncommitted changes by the
117 plus sign. Otherwise, the sign is omitted.
118
119 Read the full description via hg id --help
120 """
121 (rc, out, err) = self._command(["id", "-b", "-i", "-t", "-R", self.dest])
122 if rc != 0:
123 self.module.fail_json(msg=err)
124 else:
125 return out.strip("\n")
126
127 def get_remote_revision(self):
128 (rc, out, err) = self._command(["id", self.repo])
129 if rc != 0:
130 self.module.fail_json(msg=err)
131 else:
132 return out.strip("\n")
133
134 def has_local_mods(self):
135 now = self.get_revision()
136 return "+" in now
137
138 def discard(self):
139 before = self.has_local_mods()
140 if not before:
141 return False
142
143 args = ["update", "-C", "-R", self.dest, "-r", "."]
144 (rc, out, err) = self._command(args)
145 if rc != 0:
146 self.module.fail_json(msg=err)
147
148 after = self.has_local_mods()
149 if before != after and not after: # no more local modification
150 return True
151
152 def purge(self):
153 # before purge, find out if there are any untracked files
154 (rc1, out1, err1) = self._list_untracked()
155 if rc1 != 0:
156 self.module.fail_json(msg=err1)
157
158 # there are some untrackd files
159 if out1 != "":
160 args = ["purge", "--config", "extensions.purge=", "-R", self.dest]
161 (rc2, out2, err2) = self._command(args)
162 if rc2 != 0:
163 self.module.fail_json(msg=err2)
164 return True
165 else:
166 return False
167
168 def cleanup(self, force, purge):
169 discarded = False
170 purged = False
171
172 if force:
173 discarded = self.discard()
174 if purge:
175 purged = self.purge()
176 return discarded or purged
177
178 def pull(self):
179 return self._command(["pull", "-R", self.dest, self.repo])
180
181 def update(self):
182 if self.revision is not None:
183 return self._command(["update", "-r", self.revision, "-R", self.dest])
184 return self._command(["update", "-R", self.dest])
185
186 def clone(self):
187 if self.revision is not None:
188 return self._command(["clone", self.repo, self.dest, "-r", self.revision])
189 return self._command(["clone", self.repo, self.dest])
190
191 @property
192 def at_revision(self):
193 """
194 There is no point in pulling from a potentially down/slow remote site
195 if the desired changeset is already the current changeset.
196 """
197 if self.revision is None or len(self.revision) < 7:
198 # Assume it is a rev number, tag, or branch
199 return False
200 (rc, out, err) = self._command(["--debug", "id", "-i", "-R", self.dest])
201 if rc != 0:
202 self.module.fail_json(msg=err)
203 return out.startswith(self.revision)
204
205
206 # ===========================================
207
208
209 def main():
210 module = AnsibleModule(
211 argument_spec=dict(
212 repo=dict(type="str", required=True, aliases=["name"]),
213 dest=dict(type="path"),
214 revision=dict(type="str", aliases=["version"]),
215 force=dict(type="bool", default=False),
216 purge=dict(type="bool", default=False),
217 update=dict(type="bool", default=True),
218 clone=dict(type="bool", default=True),
219 executable=dict(type="str"),
220 ),
221 )
222 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
223 repo = module.params["repo"]
224 dest = module.params["dest"]
225 revision = module.params["revision"]
226 force = module.params["force"]
227 purge = module.params["purge"]
228 update = module.params["update"]
229 clone = module.params["clone"]
230 hg_path = module.params["executable"] or module.get_bin_path("hg", True)
231 if dest is not None:
232 hgrc = os.path.join(dest, ".hg/hgrc")
233
234 # initial states
235 before = ""
236 changed = False
237 cleaned = False
238
239 if not dest and (clone or update):
240 module.fail_json(msg="the destination directory must be specified unless clone=false and update=false")
241
242 hg = Hg(module, dest, repo, revision, hg_path)
243
244 # If there is no hgrc file, then assume repo is absent
245 # and perform clone. Otherwise, perform pull and update.
246 if not clone and not update:
247 out = hg.get_remote_revision()
248 module.exit_json(after=out, changed=False)
249 if not os.path.exists(hgrc):
250 if clone:
251 (rc, out, err) = hg.clone()
252 if rc != 0:
253 module.fail_json(msg=err)
254 else:
255 module.exit_json(changed=False)
256 elif not update:
257 # Just return having found a repo already in the dest path
258 before = hg.get_revision()
259 elif hg.at_revision:
260 # no update needed, don't pull
261 before = hg.get_revision()
262
263 # but force and purge if desired
264 cleaned = hg.cleanup(force, purge)
265 else:
266 # get the current state before doing pulling
267 before = hg.get_revision()
268
269 # can perform force and purge
270 cleaned = hg.cleanup(force, purge)
271
272 (rc, out, err) = hg.pull()
273 if rc != 0:
274 module.fail_json(msg=err)
275
276 (rc, out, err) = hg.update()
277 if rc != 0:
278 module.fail_json(msg=err)
279
280 after = hg.get_revision()
281 if before != after or cleaned:
282 changed = True
283
284 module.exit_json(before=before, after=after, changed=changed, cleaned=cleaned)
285
286
287 if __name__ == "__main__":
288 main()