Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2017 John Kwiatkoski (@JayKayy) <[email protected]>
4 # Copyright (c) 2018 Alexander Bethke (@oolongbrothers) <[email protected]>
5 # Copyright (c) 2017 Ansible Project
6 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
7 # SPDX-License-Identifier: GPL-3.0-or-later
8
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: flatpak
13 short_description: Manage flatpaks
14 description:
15 - Allows users to add or remove flatpaks.
16 - See the M(community.general.flatpak_remote) module for managing flatpak remotes.
17 author:
18 - John Kwiatkoski (@JayKayy)
19 - Alexander Bethke (@oolongbrothers)
20 requirements:
21 - flatpak
22 extends_documentation_fragment:
23 - community.general._attributes
24 attributes:
25 check_mode:
26 support: partial
27 details:
28 - If O(state=latest), the module always returns RV(ignore:changed=true).
29 diff_mode:
30 support: none
31 options:
32 executable:
33 description:
34 - The path to the C(flatpak) executable to use.
35 - By default, this module looks for the C(flatpak) executable on the path.
36 type: path
37 default: flatpak
38 method:
39 description:
40 - The installation method to use.
41 - Defines if the C(flatpak) is supposed to be installed globally for the whole V(system) or only for the current V(user).
42 type: str
43 choices: [system, user]
44 default: system
45 name:
46 description:
47 - The name of the flatpak to manage. To operate on several packages this can accept a list of packages.
48 - Should be specified as the unique reverse DNS name that identifies a flatpak (for example V(org.gnome.gedit)).
49 - When supplying a reverse DNS name, you can use the O(remote) option to specify on what remote to look for the flatpak.
50 - When used with O(state=present), O(name) can also be specified as a C(https://) or C(http://) URL to a C(flatpakref) file.
51 However, it is recommended you use O(from_url) instead to get reliable idempotency.
52 Passing URLs in O(name) will be deprecated in the future.
53 - When used with O(state=absent) or O(state=latest), always specify the name in the reverse DNS format.
54 - When supplying a URL with O(state=absent) or O(state=latest), the module tries to match the installed flatpak based
55 on the name of the flatpakref to remove or update it. However, there is no guarantee that the names of the flatpakref
56 file and the reverse DNS name of the installed flatpak do match.
57 type: list
58 elements: str
59 required: true
60 from_url:
61 description:
62 - A C(http://) or C(https://) URL pointing to a C(.flatpakref) file to install from.
63 - When this option is set, O(name) must contain exactly one entry specifying the reverse DNS application ID of the
64 flatpak (for example V(com.onepassword.OnePassword)). This is used to check whether the flatpak is already installed.
65 - O(name) and O(from_url) cannot both contain URLs.
66 - This option is recommended instead of passing a URL in O(name); passing URLs in O(name) will be deprecated in the future.
67 type: str
68 version_added: "12.6.0"
69 no_dependencies:
70 description:
71 - If installing runtime dependencies should be omitted or not.
72 - This parameter is primarily implemented for integration testing this module. There might however be some use cases
73 where you would want to have this, like when you are packaging your own flatpaks.
74 type: bool
75 default: false
76 version_added: 3.2.0
77 remote:
78 description:
79 - The flatpak remote (repository) to install the flatpak from.
80 - By default, V(flathub) is assumed, but you do need to add the flathub flatpak_remote before you can use this.
81 - See the M(community.general.flatpak_remote) module for managing flatpak remotes.
82 type: str
83 default: flathub
84 state:
85 description:
86 - Indicates the desired package state.
87 - The value V(latest) is supported since community.general 8.6.0.
88 choices: [absent, present, latest]
89 type: str
90 default: present
91 """
92
93 EXAMPLES = r"""
94 - name: Install the spotify flatpak
95 community.general.flatpak:
96 name: com.spotify.Client
97 from_url: https://s3.amazonaws.com/alexlarsson/spotify-repo/spotify.flatpakref
98 state: present
99
100 - name: Install the gedit flatpak package without dependencies (not recommended)
101 community.general.flatpak:
102 name: org.gnome.gedit
103 from_url: https://git.gnome.org/browse/gnome-apps-nightly/plain/gedit.flatpakref
104 state: present
105 no_dependencies: true
106
107 - name: Install the gedit package from flathub for current user
108 community.general.flatpak:
109 name: org.gnome.gedit
110 state: present
111 method: user
112
113 - name: Install the Gnome Calendar flatpak from the gnome remote system-wide
114 community.general.flatpak:
115 name: org.gnome.Calendar
116 state: present
117 remote: gnome
118
119 - name: Install GIMP using custom flatpak binary path
120 community.general.flatpak:
121 name: org.gimp.GIMP
122 state: present
123 executable: /usr/local/bin/flatpak-dev
124
125 - name: Install multiple packages
126 community.general.flatpak:
127 name:
128 - org.gimp.GIMP
129 - org.inkscape.Inkscape
130 - org.mozilla.firefox
131
132 - name: Update the spotify flatpak
133 community.general.flatpak:
134 name: com.spotify.Client
135 from_url: https://s3.amazonaws.com/alexlarsson/spotify-repo/spotify.flatpakref
136 state: latest
137
138 - name: Update the gedit flatpak package without dependencies (not recommended)
139 community.general.flatpak:
140 name: org.gnome.gedit
141 from_url: https://git.gnome.org/browse/gnome-apps-nightly/plain/gedit.flatpakref
142 state: latest
143 no_dependencies: true
144
145 - name: Update the gedit package from flathub for current user
146 community.general.flatpak:
147 name: org.gnome.gedit
148 state: latest
149 method: user
150
151 - name: Update the Gnome Calendar flatpak from the gnome remote system-wide
152 community.general.flatpak:
153 name: org.gnome.Calendar
154 state: latest
155 remote: gnome
156
157 - name: Update multiple packages
158 community.general.flatpak:
159 name:
160 - org.gimp.GIMP
161 - org.inkscape.Inkscape
162 - org.mozilla.firefox
163 state: latest
164
165 - name: Remove the gedit flatpak
166 community.general.flatpak:
167 name: org.gnome.gedit
168 state: absent
169
170 - name: Remove multiple packages
171 community.general.flatpak:
172 name:
173 - org.gimp.GIMP
174 - org.inkscape.Inkscape
175 - org.mozilla.firefox
176 state: absent
177 """
178
179 RETURN = r"""
180 command:
181 description: The exact flatpak command that was executed.
182 returned: When a flatpak command has been executed
183 type: str
184 sample: "/usr/bin/flatpak install --user --nontinteractive flathub org.gnome.Calculator"
185 """
186
187 from re import match
188 from urllib.parse import urlparse
189
190 from ansible.module_utils.basic import AnsibleModule
191
192 from ansible_collections.community.general.plugins.module_utils._version import LooseVersion
193
194 OUTDATED_FLATPAK_VERSION_ERROR_MESSAGE = "Unknown option --columns=application"
195
196
197 def install_flat(module, binary, remote, names, method, no_dependencies, from_url=None):
198 """Add new flatpaks."""
199 global result # pylint: disable=global-variable-not-assigned
200 uri_names = []
201 id_names = []
202 for name in names:
203 if name.startswith("http://") or name.startswith("https://"):
204 uri_names.append(name)
205 else:
206 id_names.append(name)
207 base_command = [binary, "install", f"--{method}"]
208 flatpak_version = _flatpak_version(module, binary)
209 if LooseVersion(flatpak_version) < LooseVersion("1.1.3"):
210 base_command += ["-y"]
211 else:
212 base_command += ["--noninteractive"]
213 if no_dependencies:
214 base_command += ["--no-deps"]
215 if from_url:
216 command = base_command + ["--from", from_url]
217 _flatpak_command(module, module.check_mode, command)
218 else:
219 if uri_names:
220 command = base_command + uri_names
221 _flatpak_command(module, module.check_mode, command)
222 if id_names:
223 command = base_command + [remote] + id_names
224 _flatpak_command(module, module.check_mode, command)
225 result["changed"] = True
226
227
228 def update_flat(module, binary, names, method, no_dependencies):
229 """Update existing flatpaks."""
230 global result # pylint: disable=global-variable-not-assigned
231 installed_flat_names = [_match_installed_flat_name(module, binary, name, method) for name in names]
232 command = [binary, "update", f"--{method}"]
233 flatpak_version = _flatpak_version(module, binary)
234 if LooseVersion(flatpak_version) < LooseVersion("1.1.3"):
235 command += ["-y"]
236 else:
237 command += ["--noninteractive"]
238 if no_dependencies:
239 command += ["--no-deps"]
240 command += installed_flat_names
241 stdout = _flatpak_command(module, module.check_mode, command)
242 result["changed"] = (
243 True if module.check_mode else (stdout.find("Nothing to do.") == -1 and stdout.find("Nothing to update.") == -1)
244 )
245
246
247 def uninstall_flat(module, binary, names, method):
248 """Remove existing flatpaks."""
249 global result # pylint: disable=global-variable-not-assigned
250 installed_flat_names = [_match_installed_flat_name(module, binary, name, method) for name in names]
251 command = [binary, "uninstall"]
252 flatpak_version = _flatpak_version(module, binary)
253 if LooseVersion(flatpak_version) < LooseVersion("1.1.3"):
254 command += ["-y"]
255 else:
256 command += ["--noninteractive"]
257 command += [f"--{method}"] + installed_flat_names
258 _flatpak_command(module, module.check_mode, command)
259 result["changed"] = True
260
261
262 def flatpak_exists(module, binary, names, method):
263 """Check if the flatpaks are installed."""
264 command = [binary, "list", f"--{method}"]
265 output = _flatpak_command(module, False, command)
266 installed = []
267 not_installed = []
268 for name in names:
269 parsed_name = _parse_flatpak_name(name).lower()
270 if parsed_name in output.lower():
271 installed.append(name)
272 else:
273 not_installed.append(name)
274 return installed, not_installed
275
276
277 def _match_installed_flat_name(module, binary, name, method):
278 # This is a difficult function, since if the user supplies a flatpakref url,
279 # we have to rely on a naming convention:
280 # The flatpakref file name needs to match the flatpak name
281 global result # pylint: disable=global-variable-not-assigned
282 parsed_name = _parse_flatpak_name(name)
283 # Try running flatpak list with columns feature
284 command = [binary, "list", f"--{method}", "--columns=application"]
285 _flatpak_command(module, False, command, ignore_failure=True)
286 if result["rc"] != 0 and OUTDATED_FLATPAK_VERSION_ERROR_MESSAGE in result["stderr"]:
287 # Probably flatpak before 1.2
288 matched_flatpak_name = _match_flat_using_flatpak_column_feature(module, binary, parsed_name, method)
289 else:
290 # Probably flatpak >= 1.2
291 matched_flatpak_name = _match_flat_using_outdated_flatpak_format(module, binary, parsed_name, method)
292
293 if matched_flatpak_name:
294 return matched_flatpak_name
295 else:
296 result["msg"] = (
297 "Flatpak removal failed: Could not match any installed flatpaks to "
298 f"the name `{_parse_flatpak_name(name)}`. "
299 "If you used a URL, try using the reverse DNS name of the flatpak"
300 )
301 module.fail_json(**result)
302
303
304 def _match_flat_using_outdated_flatpak_format(module, binary, parsed_name, method):
305 global result # pylint: disable=global-variable-not-assigned
306 command = [binary, "list", f"--{method}", "--columns=application"]
307 output = _flatpak_command(module, False, command)
308 for row in output.split("\n"):
309 if parsed_name.lower() == row.lower():
310 return row
311
312
313 def _match_flat_using_flatpak_column_feature(module, binary, parsed_name, method):
314 global result # pylint: disable=global-variable-not-assigned
315 command = [binary, "list", f"--{method}"]
316 output = _flatpak_command(module, False, command)
317 for row in output.split("\n"):
318 if parsed_name.lower() in row.lower():
319 return row.split()[0]
320
321
322 def _is_flatpak_id(part):
323 # For guidelines on application IDs, refer to the following resources:
324 # Flatpak:
325 # https://docs.flatpak.org/en/latest/conventions.html#application-ids
326 # Flathub:
327 # https://docs.flathub.org/docs/for-app-authors/requirements#application-id
328 return match(r"^[a-z]{2,}(\.\w+)+\.[\w-]+$", part)
329
330
331 def _parse_flatpak_name(name):
332 if name.startswith("http://") or name.startswith("https://"):
333 file_name = urlparse(name).path.split("/")[-1]
334 file_name_without_extension = file_name.split(".")[0:-1]
335 common_name = ".".join(file_name_without_extension)
336 else:
337 parts = name.split("/")
338 for part in parts:
339 if _is_flatpak_id(part):
340 common_name = part
341 break
342 else:
343 common_name = name
344 return common_name
345
346
347 def _flatpak_version(module, binary):
348 global result # pylint: disable=global-variable-not-assigned
349 command = [binary, "--version"]
350 output = _flatpak_command(module, False, command)
351 version_number = output.split()[1]
352 return version_number
353
354
355 def _flatpak_command(module, noop, command, ignore_failure=False):
356 global result # pylint: disable=global-variable-not-assigned
357 result["command"] = " ".join(command)
358 if noop:
359 result["rc"] = 0
360 return ""
361
362 result["rc"], result["stdout"], result["stderr"] = module.run_command(command, check_rc=not ignore_failure)
363 return result["stdout"]
364
365
366 def main():
367 # This module supports check mode
368 module = AnsibleModule(
369 argument_spec=dict(
370 name=dict(type="list", elements="str", required=True),
371 from_url=dict(type="str"),
372 remote=dict(type="str", default="flathub"),
373 method=dict(type="str", default="system", choices=["user", "system"]),
374 state=dict(type="str", default="present", choices=["absent", "present", "latest"]),
375 no_dependencies=dict(type="bool", default=False),
376 executable=dict(type="path", default="flatpak"),
377 ),
378 supports_check_mode=True,
379 )
380
381 name = module.params["name"]
382 from_url = module.params["from_url"]
383 state = module.params["state"]
384 remote = module.params["remote"]
385 no_dependencies = module.params["no_dependencies"]
386 method = module.params["method"]
387 executable = module.params["executable"]
388 binary = module.get_bin_path(executable, None)
389
390 global result
391 result = dict(changed=False)
392
393 # If the binary was not found, fail the operation
394 if not binary:
395 module.fail_json(msg=f"Executable '{executable}' was not found on the system.", **result)
396
397 url_names = [n for n in name if n.startswith("http://") or n.startswith("https://")]
398 if from_url is not None:
399 if not (from_url.startswith("http://") or from_url.startswith("https://")):
400 module.fail_json(msg="The 'from_url' parameter must be an http:// or https:// URL.", **result)
401 if url_names:
402 module.fail_json(msg="The 'name' and 'from_url' parameters cannot both contain URLs.", **result)
403 if len(name) != 1:
404 module.fail_json(msg="When 'from_url' is used, 'name' must contain exactly one entry.", **result)
405 module.run_command_environ_update = dict(LANGUAGE="C", LC_ALL="C")
406
407 installed, not_installed = flatpak_exists(module, binary, name, method)
408 if state == "absent" and installed:
409 uninstall_flat(module, binary, installed, method)
410 else:
411 if state == "latest" and installed:
412 update_flat(module, binary, installed, method, no_dependencies)
413 if state in ("present", "latest") and not_installed:
414 install_flat(module, binary, remote, not_installed, method, no_dependencies, from_url)
415
416 module.exit_json(**result)
417
418
419 if __name__ == "__main__":
420 main()