Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2013, André Paramés <[email protected]>
4 # Based on the Git module by Michael DeHaan <[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: bzr
12 author:
13 - André Paramés (@andreparames)
14 short_description: Deploy software (or files) from bzr branches
15 description:
16 - Manage C(bzr) branches to deploy files or software.
17 extends_documentation_fragment:
18 - community.general._attributes
19 attributes:
20 check_mode:
21 support: none
22 diff_mode:
23 support: none
24 options:
25 name:
26 description:
27 - SSH or HTTP protocol address of the parent branch.
28 aliases: [parent]
29 required: true
30 type: str
31 dest:
32 description:
33 - Absolute path of where the branch should be cloned to.
34 required: true
35 type: path
36 version:
37 description:
38 - What version of the branch to clone. This can be the bzr revno or revid.
39 default: head
40 type: str
41 force:
42 description:
43 - If V(true), any modified files in the working tree is discarded.
44 type: bool
45 default: false
46 executable:
47 description:
48 - Path to C(bzr) executable to use. If not supplied, the normal mechanism for resolving binary paths is used.
49 type: str
50 """
51
52 EXAMPLES = r"""
53 - name: Checkout
54 community.general.bzr:
55 name: bzr+ssh://foosball.example.org/path/to/branch
56 dest: /srv/checkout
57 version: 22
58 """
59
60 import os
61 import re
62
63 from ansible.module_utils.basic import AnsibleModule
64
65
66 class Bzr:
67 def __init__(self, module, parent, dest, version, bzr_path):
68 self.module = module
69 self.parent = parent
70 self.dest = dest
71 self.version = version
72 self.bzr_path = bzr_path
73
74 def _command(self, args_list, cwd=None, **kwargs):
75 (rc, out, err) = self.module.run_command([self.bzr_path] + args_list, cwd=cwd, **kwargs)
76 return (rc, out, err)
77
78 def get_version(self):
79 """samples the version of the bzr branch"""
80
81 cmd = [self.bzr_path, "revno"]
82 rc, stdout, stderr = self.module.run_command(cmd, cwd=self.dest)
83 revno = stdout.strip()
84 return revno
85
86 def clone(self):
87 """makes a new bzr branch if it does not already exist"""
88 dest_dirname = os.path.dirname(self.dest)
89 try:
90 os.makedirs(dest_dirname)
91 except Exception:
92 pass
93 if self.version.lower() != "head":
94 args_list = ["branch", "-r", self.version, self.parent, self.dest]
95 else:
96 args_list = ["branch", self.parent, self.dest]
97 return self._command(args_list, check_rc=True, cwd=dest_dirname)
98
99 def has_local_mods(self):
100 cmd = [self.bzr_path, "status", "-S"]
101 rc, stdout, stderr = self.module.run_command(cmd, cwd=self.dest)
102 lines = stdout.splitlines()
103 mods_re = re.compile("^\\?\\?.*$")
104
105 lines = [c for c in lines if not mods_re.search(c)]
106 return len(lines) > 0
107
108 def reset(self, force):
109 """
110 Resets the index and working tree to head.
111 Discards any changes to tracked files in the working
112 tree since that commit.
113 """
114 if not force and self.has_local_mods():
115 self.module.fail_json(msg="Local modifications exist in branch (force=false).")
116 return self._command(["revert"], check_rc=True, cwd=self.dest)
117
118 def fetch(self):
119 """updates branch from remote sources"""
120 if self.version.lower() != "head":
121 (rc, out, err) = self._command(["pull", "-r", self.version], cwd=self.dest)
122 else:
123 (rc, out, err) = self._command(["pull"], cwd=self.dest)
124 if rc != 0:
125 self.module.fail_json(msg="Failed to pull")
126 return (rc, out, err)
127
128 def switch_version(self):
129 """once pulled, switch to a particular revno or revid"""
130 if self.version.lower() != "head":
131 args_list = ["revert", "-r", self.version]
132 else:
133 args_list = ["revert"]
134 return self._command(args_list, check_rc=True, cwd=self.dest)
135
136
137 # ===========================================
138
139
140 def main():
141 module = AnsibleModule(
142 argument_spec=dict(
143 dest=dict(type="path", required=True),
144 name=dict(type="str", required=True, aliases=["parent"]),
145 version=dict(type="str", default="head"),
146 force=dict(type="bool", default=False),
147 executable=dict(type="str"),
148 )
149 )
150 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
151
152 dest = module.params["dest"]
153 parent = module.params["name"]
154 version = module.params["version"]
155 force = module.params["force"]
156 bzr_path = module.params["executable"] or module.get_bin_path("bzr", True)
157
158 bzrconfig = os.path.join(dest, ".bzr", "branch", "branch.conf")
159
160 rc, out, err = (0, None, None)
161
162 bzr = Bzr(module, parent, dest, version, bzr_path)
163
164 # if there is no bzr configuration, do a branch operation
165 # else pull and switch the version
166 before = None
167 local_mods = False
168 if not os.path.exists(bzrconfig):
169 (rc, out, err) = bzr.clone()
170
171 else:
172 # else do a pull
173 local_mods = bzr.has_local_mods()
174 before = bzr.get_version()
175 (rc, out, err) = bzr.reset(force)
176 if rc != 0:
177 module.fail_json(msg=err)
178 (rc, out, err) = bzr.fetch()
179 if rc != 0:
180 module.fail_json(msg=err)
181
182 # switch to version specified regardless of whether
183 # we cloned or pulled
184 (rc, out, err) = bzr.switch_version()
185
186 # determine if we changed anything
187 after = bzr.get_version()
188 changed = False
189
190 if before != after or local_mods:
191 changed = True
192
193 module.exit_json(changed=changed, before=before, after=after)
194
195
196 if __name__ == "__main__":
197 main()