Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2021, Alexei Znamensky <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: pipx
11 short_description: Manages applications installed with pipx
12 version_added: 3.8.0
13 description:
14 - Manage Python applications installed in isolated virtualenvs using pipx.
15 extends_documentation_fragment:
16 - community.general._attributes
17 - community.general._pipx
18 attributes:
19 check_mode:
20 support: full
21 diff_mode:
22 support: full
23 options:
24 state:
25 type: str
26 choices:
27 - present
28 - absent
29 - install
30 - install_all
31 - uninstall
32 - uninstall_all
33 - inject
34 - uninject
35 - upgrade
36 - upgrade_shared
37 - upgrade_all
38 - reinstall
39 - reinstall_all
40 - latest
41 - pin
42 - unpin
43 default: install
44 description:
45 - Desired state for the application.
46 - The states V(present) and V(absent) are aliases to V(install) and V(uninstall), respectively.
47 - The state V(latest) is equivalent to executing the task twice, with state V(install) and then V(upgrade). It was added
48 in community.general 5.5.0.
49 - The states V(install_all), V(uninject), V(upgrade_shared), V(pin) and V(unpin) are only available in C(pipx>=1.6.0),
50 make sure to have a compatible version when using this option. These states have been added in community.general 9.4.0.
51 name:
52 type: str
53 description:
54 - The name of the application and also the name of the Python package being installed.
55 - In C(pipx) documentation it is also referred to as the name of the virtual environment where the application is installed.
56 - If O(name) is a simple package name without version specifiers, then that name is used as the Python package name
57 to be installed.
58 - Starting in community.general 10.7.0, you can use package specifiers when O(state=present) or O(state=install). For
59 example, O(name=tox<4.0.0) or O(name=tox>3.0.27).
60 - Please note that when you use O(state=present) and O(name) with version specifiers, contrary to the behavior of C(pipx),
61 this module honors the version specifier and installs a version of the application that satisfies it. If you want
62 to ensure the reinstallation of the application even when the version specifier is met, then you must use O(force=true),
63 or perhaps use O(state=upgrade) instead.
64 - Use O(source) for installing from URLs or directories.
65 source:
66 type: str
67 description:
68 - Source for the package. This option is used when O(state=install) or O(state=latest), and it is ignored with other
69 states.
70 - Use O(source) when installing a Python package with version specifier, or from a local path, from a VCS URL or compressed
71 file.
72 - The value of this option is passed as-is to C(pipx).
73 - O(name) is still required when using O(source) to establish the application name without fetching the package from
74 a remote source.
75 - The module is not idempotent when using O(source).
76 install_apps:
77 description:
78 - Add apps from the injected packages.
79 - Only used when O(state=inject).
80 type: bool
81 default: false
82 version_added: 6.5.0
83 install_deps:
84 description:
85 - Include applications of dependent packages.
86 - Only used when O(state=install), O(state=latest), or O(state=inject).
87 type: bool
88 default: false
89 inject_packages:
90 description:
91 - Packages to be injected into an existing virtual environment.
92 - Only used when O(state=inject).
93 type: list
94 elements: str
95 force:
96 description:
97 - Force modification of the application's virtual environment. See C(pipx) for details.
98 - Only used when O(state=install), O(state=upgrade), O(state=upgrade_all), O(state=latest), or O(state=inject).
99 - The module is not idempotent when O(force=true).
100 type: bool
101 default: false
102 include_injected:
103 description:
104 - Upgrade the injected packages along with the application.
105 - Only used when O(state=upgrade), O(state=upgrade_all), or O(state=latest).
106 - This is used with O(state=upgrade) and O(state=latest) since community.general 6.6.0.
107 type: bool
108 default: false
109 index_url:
110 description:
111 - Base URL of Python Package Index.
112 - Only used when O(state=install), O(state=upgrade), O(state=latest), or O(state=inject).
113 type: str
114 python:
115 description:
116 - Python version to be used when creating the application virtual environment. Must be 3.6+.
117 - Only used when O(state=install), O(state=latest), O(state=reinstall), or O(state=reinstall_all).
118 type: str
119 system_site_packages:
120 description:
121 - Give application virtual environment access to the system site-packages directory.
122 - Only used when O(state=install) or O(state=latest).
123 type: bool
124 default: false
125 version_added: 6.6.0
126 editable:
127 description:
128 - Install the project in editable mode.
129 type: bool
130 default: false
131 version_added: 4.6.0
132 pip_args:
133 description:
134 - Arbitrary arguments to pass directly to C(pip).
135 type: str
136 version_added: 4.6.0
137 suffix:
138 description:
139 - Optional suffix for virtual environment and executable names.
140 - B(Warning:) C(pipx) documentation states this is an B(experimental) feature subject to change.
141 type: str
142 version_added: 9.3.0
143 global:
144 version_added: 9.4.0
145 spec_metadata:
146 description:
147 - Spec metadata file for O(state=install_all).
148 - This content of the file is usually generated with C(pipx list --json), and it can be obtained with M(community.general.pipx_info)
149 with O(community.general.pipx_info#module:include_raw=true) and obtaining the content from the RV(community.general.pipx_info#module:raw_output).
150 type: path
151 version_added: 9.4.0
152 requirements:
153 - When using O(name) with version specifiers, the Python package C(packaging) is required.
154 - If the package C(packaging) is at a version lesser than C(22.0.0), it fails silently when processing invalid specifiers,
155 like C(tox<<<<4.0).
156 author:
157 - "Alexei Znamensky (@russoz)"
158 """
159
160 EXAMPLES = r"""
161 - name: Install tox
162 community.general.pipx:
163 name: tox
164
165 - name: Install tox from git repository
166 community.general.pipx:
167 name: tox
168 source: git+https://github.com/tox-dev/tox.git
169
170 - name: Upgrade tox
171 community.general.pipx:
172 name: tox
173 state: upgrade
174
175 - name: Install or upgrade tox with extra 'docs'
176 community.general.pipx:
177 name: tox
178 source: tox[docs]
179 state: latest
180
181 - name: Reinstall black with specific Python version
182 community.general.pipx:
183 name: black
184 state: reinstall
185 python: 3.7
186
187 - name: Uninstall pycowsay
188 community.general.pipx:
189 name: pycowsay
190 state: absent
191
192 - name: Install multiple packages from list
193 vars:
194 pipx_packages:
195 - pycowsay
196 - black
197 - tox
198 community.general.pipx:
199 name: "{{ item }}"
200 state: latest
201 with_items: "{{ pipx_packages }}"
202 """
203
204 RETURN = r"""
205 version:
206 description: Version of pipx.
207 type: str
208 returned: always
209 sample: "1.7.1"
210 version_added: 10.1.0
211 """
212
213
214 from ansible_collections.community.general.plugins.module_utils._module_helper import StateModuleHelper
215 from ansible_collections.community.general.plugins.module_utils._pipx import (
216 make_process_dict,
217 pipx_common_argspec,
218 pipx_runner,
219 )
220 from ansible_collections.community.general.plugins.module_utils._pkg_req import PackageRequirement
221 from ansible_collections.community.general.plugins.module_utils._version import LooseVersion
222
223
224 def make_installed_name(name, suffix):
225 return name if suffix is None else f"{name}{suffix}"
226
227
228 class PipX(StateModuleHelper):
229 output_params = ["name", "source", "index_url", "force", "installdeps"]
230 argument_spec = dict(
231 state=dict(
232 type="str",
233 default="install",
234 choices=[
235 "present",
236 "absent",
237 "install",
238 "install_all",
239 "uninstall",
240 "uninstall_all",
241 "inject",
242 "uninject",
243 "upgrade",
244 "upgrade_shared",
245 "upgrade_all",
246 "reinstall",
247 "reinstall_all",
248 "latest",
249 "pin",
250 "unpin",
251 ],
252 ),
253 name=dict(type="str"),
254 source=dict(type="str"),
255 install_apps=dict(type="bool", default=False),
256 install_deps=dict(type="bool", default=False),
257 inject_packages=dict(type="list", elements="str"),
258 force=dict(type="bool", default=False),
259 include_injected=dict(type="bool", default=False),
260 index_url=dict(type="str"),
261 python=dict(type="str"),
262 system_site_packages=dict(type="bool", default=False),
263 editable=dict(type="bool", default=False),
264 pip_args=dict(type="str"),
265 suffix=dict(type="str"),
266 spec_metadata=dict(type="path"),
267 )
268 argument_spec.update(pipx_common_argspec)
269
270 module = dict(
271 argument_spec=argument_spec,
272 required_if=[
273 ("state", "present", ["name"]),
274 ("state", "install", ["name"]),
275 ("state", "install_all", ["spec_metadata"]),
276 ("state", "absent", ["name"]),
277 ("state", "uninstall", ["name"]),
278 ("state", "upgrade", ["name"]),
279 ("state", "reinstall", ["name"]),
280 ("state", "latest", ["name"]),
281 ("state", "inject", ["name", "inject_packages"]),
282 ("state", "pin", ["name"]),
283 ("state", "unpin", ["name"]),
284 ],
285 required_by=dict(
286 suffix="name",
287 ),
288 supports_check_mode=True,
289 )
290
291 def _retrieve_installed(self):
292 output_process = make_process_dict(include_injected=True)
293 installed, dummy = self.runner("_list global", output_process=output_process).run()
294
295 if self.app_name is None:
296 return installed
297
298 return {k: v for k, v in installed.items() if k == self.app_name}
299
300 def __init_module__(self):
301 self.runner = pipx_runner(self.module, self.vars.executable)
302
303 pkg_req = PackageRequirement(self.module, self.vars.name)
304 self.parsed_name = pkg_req.parsed_name
305 self.parsed_req = pkg_req.requirement
306 self.app_name = make_installed_name(self.parsed_name, self.vars.suffix)
307
308 self.vars.set("application", self._retrieve_installed(), change=True, diff=True)
309
310 with self.runner("version") as ctx:
311 rc, out, err = ctx.run()
312 self.vars.version = out.strip()
313
314 if LooseVersion(self.vars.version) < LooseVersion("1.7.0"):
315 self.do_raise("The pipx tool must be at least at version 1.7.0")
316
317 def __quit_module__(self):
318 self.vars.application = self._retrieve_installed()
319
320 def _capture_results(self, ctx):
321 self.vars.stdout = ctx.results_out
322 self.vars.stderr = ctx.results_err
323 self.vars.cmd = ctx.cmd
324 self.vars.set("run_info", ctx.run_info, verbosity=4)
325
326 def state_install(self):
327 # If we have a version spec and no source, use the version spec as source
328 if self.parsed_req and not self.vars.source:
329 self.vars.source = self.vars.name
330
331 if self.vars.application.get(self.app_name):
332 is_installed = True
333 version_match = (
334 self.vars.application[self.app_name]["version"] in self.parsed_req.specifier
335 if self.parsed_req
336 else True
337 )
338 force = self.vars.force or (not version_match)
339 else:
340 is_installed = False
341 version_match = False
342 force = self.vars.force
343
344 if is_installed and version_match and not force:
345 return
346
347 self.changed = True
348 args_order = (
349 "state global index_url install_deps force python system_site_packages editable pip_args suffix name_source"
350 )
351 with self.runner(args_order, check_mode_skip=True) as ctx:
352 ctx.run(name_source=[self.parsed_name, self.vars.source], force=force)
353 self._capture_results(ctx)
354
355 state_present = state_install
356
357 def state_install_all(self):
358 self.changed = True
359 with self.runner(
360 "state global index_url force python system_site_packages editable pip_args spec_metadata",
361 check_mode_skip=True,
362 ) as ctx:
363 ctx.run()
364 self._capture_results(ctx)
365
366 def state_upgrade(self):
367 name = make_installed_name(self.vars.name, self.vars.suffix)
368 if not self.vars.application:
369 self.do_raise(f"Trying to upgrade a non-existent application: {name}")
370 if self.vars.force:
371 self.changed = True
372
373 with self.runner(
374 "state global include_injected index_url force editable pip_args name", check_mode_skip=True
375 ) as ctx:
376 ctx.run(name=name)
377 self._capture_results(ctx)
378
379 def state_uninstall(self):
380 if self.vars.application:
381 name = make_installed_name(self.vars.name, self.vars.suffix)
382 with self.runner("state global name", check_mode_skip=True) as ctx:
383 ctx.run(name=name)
384 self._capture_results(ctx)
385
386 state_absent = state_uninstall
387
388 def state_reinstall(self):
389 name = make_installed_name(self.vars.name, self.vars.suffix)
390 if not self.vars.application:
391 self.do_raise(f"Trying to reinstall a non-existent application: {name}")
392 self.changed = True
393 with self.runner("state global name python", check_mode_skip=True) as ctx:
394 ctx.run(name=name)
395 self._capture_results(ctx)
396
397 def state_inject(self):
398 name = make_installed_name(self.vars.name, self.vars.suffix)
399 if not self.vars.application:
400 self.do_raise(f"Trying to inject packages into a non-existent application: {name}")
401 if self.vars.force:
402 self.changed = True
403 with self.runner(
404 "state global index_url install_apps install_deps force editable pip_args name inject_packages",
405 check_mode_skip=True,
406 ) as ctx:
407 ctx.run(name=name)
408 self._capture_results(ctx)
409
410 def state_uninject(self):
411 name = make_installed_name(self.vars.name, self.vars.suffix)
412 if not self.vars.application:
413 self.do_raise(f"Trying to uninject packages into a non-existent application: {name}")
414 with self.runner("state global name inject_packages", check_mode_skip=True) as ctx:
415 ctx.run(name=name)
416 self._capture_results(ctx)
417
418 def state_uninstall_all(self):
419 with self.runner("state global", check_mode_skip=True) as ctx:
420 ctx.run()
421 self._capture_results(ctx)
422
423 def state_reinstall_all(self):
424 with self.runner("state global python", check_mode_skip=True) as ctx:
425 ctx.run()
426 self._capture_results(ctx)
427
428 def state_upgrade_all(self):
429 if self.vars.force:
430 self.changed = True
431 with self.runner("state global include_injected force", check_mode_skip=True) as ctx:
432 ctx.run()
433 self._capture_results(ctx)
434
435 def state_upgrade_shared(self):
436 with self.runner("state global pip_args", check_mode_skip=True) as ctx:
437 ctx.run()
438 self._capture_results(ctx)
439
440 def state_latest(self):
441 if not self.vars.application or self.vars.force:
442 self.changed = True
443 args_order = "state global index_url install_deps force python system_site_packages editable pip_args suffix name_source"
444 with self.runner(args_order, check_mode_skip=True) as ctx:
445 ctx.run(state="install", name_source=[self.vars.name, self.vars.source])
446 self._capture_results(ctx)
447
448 with self.runner(
449 "state global include_injected index_url force editable pip_args name", check_mode_skip=True
450 ) as ctx:
451 ctx.run(state="upgrade")
452 self._capture_results(ctx)
453
454 def state_pin(self):
455 with self.runner("state global name", check_mode_skip=True) as ctx:
456 ctx.run()
457 self._capture_results(ctx)
458
459 def state_unpin(self):
460 with self.runner("state global name", check_mode_skip=True) as ctx:
461 ctx.run()
462 self._capture_results(ctx)
463
464
465 def main():
466 PipX.execute()
467
468
469 if __name__ == "__main__":
470 main()