Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2013, Jimmy Tang <[email protected]>
4 # Based on okpg (Patrick Pelletier <[email protected]>), pacman
5 # (Afterburn) and pkgin (Shaun Zinck) modules
6 #
7 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
8 # SPDX-License-Identifier: GPL-3.0-or-later
9
10 from __future__ import annotations
11
12 DOCUMENTATION = r"""
13 module: macports
14 author: "Jimmy Tang (@jcftang)"
15 short_description: Package manager for MacPorts
16 description:
17 - Manages MacPorts packages (ports).
18 extends_documentation_fragment:
19 - community.general._attributes
20 attributes:
21 check_mode:
22 support: none
23 diff_mode:
24 support: none
25 options:
26 name:
27 description:
28 - A list of port names.
29 aliases: ['port']
30 type: list
31 elements: str
32 selfupdate:
33 description:
34 - Update Macports and the ports tree, either prior to installing ports or as a separate step.
35 - Equivalent to running C(port selfupdate).
36 aliases: ['update_cache', 'update_ports']
37 default: false
38 type: bool
39 state:
40 description:
41 - Indicates the desired state of the port.
42 choices: ['present', 'absent', 'active', 'inactive', 'installed', 'removed']
43 default: present
44 type: str
45 upgrade:
46 description:
47 - Upgrade all outdated ports, either prior to installing ports or as a separate step.
48 - Equivalent to running C(port upgrade outdated).
49 default: false
50 type: bool
51 variant:
52 description:
53 - A port variant specification.
54 - O(variant) is only supported with O(state=installed) and O(state=present).
55 aliases: ['variants']
56 type: str
57 """
58
59 EXAMPLES = r"""
60 - name: Install the foo port
61 community.general.macports:
62 name: foo
63
64 - name: Install the universal, x11 variant of the foo port
65 community.general.macports:
66 name: foo
67 variant: +universal+x11
68
69 - name: Install a list of ports
70 community.general.macports:
71 name: "{{ ports }}"
72 vars:
73 ports:
74 - foo
75 - foo-tools
76
77 - name: Update Macports and the ports tree, then upgrade all outdated ports
78 community.general.macports:
79 selfupdate: true
80 upgrade: true
81
82 - name: Update Macports and the ports tree, then install the foo port
83 community.general.macports:
84 name: foo
85 selfupdate: true
86
87 - name: Remove the foo port
88 community.general.macports:
89 name: foo
90 state: absent
91
92 - name: Activate the foo port
93 community.general.macports:
94 name: foo
95 state: active
96
97 - name: Deactivate the foo port
98 community.general.macports:
99 name: foo
100 state: inactive
101 """
102
103 import re
104
105 from ansible.module_utils.basic import AnsibleModule
106
107
108 def selfupdate(module, port_path):
109 """Update Macports and the ports tree."""
110
111 rc, out, err = module.run_command([port_path, "-v", "selfupdate"])
112
113 if rc == 0:
114 updated = any(
115 re.search(r"Total number of ports parsed:\s+[^0]", s.strip())
116 or re.search(r"Installing new Macports release", s.strip())
117 for s in out.split("\n")
118 if s
119 )
120 if updated:
121 changed = True
122 msg = "Macports updated successfully"
123 else:
124 changed = False
125 msg = "Macports already up-to-date"
126
127 return (changed, msg, out, err)
128 else:
129 module.fail_json(msg="Failed to update Macports", stdout=out, stderr=err)
130
131
132 def upgrade(module, port_path):
133 """Upgrade outdated ports."""
134
135 rc, out, err = module.run_command([port_path, "upgrade", "outdated"])
136
137 # rc is 1 when nothing to upgrade so check stdout first.
138 if out.strip() == "Nothing to upgrade.":
139 changed = False
140 msg = "Ports already upgraded"
141 return (changed, msg, out, err)
142 elif rc == 0:
143 changed = True
144 msg = "Outdated ports upgraded successfully"
145 return (changed, msg, out, err)
146 else:
147 module.fail_json(msg="Failed to upgrade outdated ports", stdout=out, stderr=err)
148
149
150 def query_port(module, port_path, name, state="present"):
151 """Returns whether a port is installed or not."""
152
153 if state == "present":
154 rc, out, err = module.run_command([port_path, "-q", "installed", name])
155
156 return rc == 0 and out.strip().startswith(f"{name} ")
157
158 elif state == "active":
159 rc, out, err = module.run_command([port_path, "-q", "installed", name])
160
161 return rc == 0 and "(active)" in out
162
163
164 def remove_ports(module, port_path, ports, stdout, stderr):
165 """Uninstalls one or more ports if installed."""
166
167 remove_c = 0
168 # Using a for loop in case of error, we can report the port that failed
169 for port in ports:
170 # Query the port first, to see if we even need to remove
171 if not query_port(module, port_path, port):
172 continue
173
174 rc, out, err = module.run_command([port_path, "uninstall", port])
175 stdout += out
176 stderr += err
177 if query_port(module, port_path, port):
178 module.fail_json(msg=f"Failed to remove {port}: {err}", stdout=stdout, stderr=stderr)
179
180 remove_c += 1
181
182 if remove_c > 0:
183 module.exit_json(changed=True, msg=f"Removed {remove_c} port(s)", stdout=stdout, stderr=stderr)
184
185 module.exit_json(changed=False, msg="Port(s) already absent", stdout=stdout, stderr=stderr)
186
187
188 def install_ports(module, port_path, ports, variant, stdout, stderr):
189 """Installs one or more ports if not already installed."""
190
191 install_c = 0
192
193 for port in ports:
194 if query_port(module, port_path, port):
195 continue
196
197 rc, out, err = module.run_command([port_path, "install", port, variant])
198 stdout += out
199 stderr += err
200 if not query_port(module, port_path, port):
201 module.fail_json(msg=f"Failed to install {port}: {err}", stdout=stdout, stderr=stderr)
202
203 install_c += 1
204
205 if install_c > 0:
206 module.exit_json(changed=True, msg=f"Installed {install_c} port(s)", stdout=stdout, stderr=stderr)
207
208 module.exit_json(changed=False, msg="Port(s) already present", stdout=stdout, stderr=stderr)
209
210
211 def activate_ports(module, port_path, ports, stdout, stderr):
212 """Activate a port if it is inactive."""
213
214 activate_c = 0
215
216 for port in ports:
217 if not query_port(module, port_path, port):
218 module.fail_json(msg=f"Failed to activate {port}, port(s) not present", stdout=stdout, stderr=stderr)
219
220 if query_port(module, port_path, port, state="active"):
221 continue
222
223 rc, out, err = module.run_command([port_path, "activate", port])
224 stdout += out
225 stderr += err
226
227 if not query_port(module, port_path, port, state="active"):
228 module.fail_json(msg=f"Failed to activate {port}: {err}", stdout=stdout, stderr=stderr)
229
230 activate_c += 1
231
232 if activate_c > 0:
233 module.exit_json(changed=True, msg=f"Activated {activate_c} port(s)", stdout=stdout, stderr=stderr)
234
235 module.exit_json(changed=False, msg="Port(s) already active", stdout=stdout, stderr=stderr)
236
237
238 def deactivate_ports(module, port_path, ports, stdout, stderr):
239 """Deactivate a port if it is active."""
240
241 deactivated_c = 0
242
243 for port in ports:
244 if not query_port(module, port_path, port):
245 module.fail_json(msg=f"Failed to deactivate {port}, port(s) not present", stdout=stdout, stderr=stderr)
246
247 if not query_port(module, port_path, port, state="active"):
248 continue
249
250 rc, out, err = module.run_command([port_path, "deactivate", port])
251 stdout += out
252 stderr += err
253 if query_port(module, port_path, port, state="active"):
254 module.fail_json(msg=f"Failed to deactivate {port}: {err}", stdout=stdout, stderr=stderr)
255
256 deactivated_c += 1
257
258 if deactivated_c > 0:
259 module.exit_json(changed=True, msg=f"Deactivated {deactivated_c} port(s)", stdout=stdout, stderr=stderr)
260
261 module.exit_json(changed=False, msg="Port(s) already inactive", stdout=stdout, stderr=stderr)
262
263
264 def main():
265 module = AnsibleModule(
266 argument_spec=dict(
267 name=dict(type="list", elements="str", aliases=["port"]),
268 selfupdate=dict(aliases=["update_cache", "update_ports"], default=False, type="bool"),
269 state=dict(default="present", choices=["present", "installed", "absent", "removed", "active", "inactive"]),
270 upgrade=dict(default=False, type="bool"),
271 variant=dict(aliases=["variants"], type="str"),
272 )
273 )
274 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
275
276 stdout = ""
277 stderr = ""
278
279 port_path = module.get_bin_path("port", True, ["/opt/local/bin"])
280
281 p = module.params
282
283 if p["selfupdate"]:
284 (changed, msg, out, err) = selfupdate(module, port_path)
285 stdout += out
286 stderr += err
287 if not (p["name"] or p["upgrade"]):
288 module.exit_json(changed=changed, msg=msg, stdout=stdout, stderr=stderr)
289
290 if p["upgrade"]:
291 (changed, msg, out, err) = upgrade(module, port_path)
292 stdout += out
293 stderr += err
294 if not p["name"]:
295 module.exit_json(changed=changed, msg=msg, stdout=stdout, stderr=stderr)
296
297 pkgs = p["name"]
298
299 variant = p["variant"]
300
301 if p["state"] in ["present", "installed"]:
302 install_ports(module, port_path, pkgs, variant, stdout, stderr)
303
304 elif p["state"] in ["absent", "removed"]:
305 remove_ports(module, port_path, pkgs, stdout, stderr)
306
307 elif p["state"] == "active":
308 activate_ports(module, port_path, pkgs, stdout, stderr)
309
310 elif p["state"] == "inactive":
311 deactivate_ports(module, port_path, pkgs, stdout, stderr)
312
313
314 if __name__ == "__main__":
315 main()