Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2013, Patrik Lundin <[email protected]>
4 #
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: openbsd_pkg
12 author:
13 - Patrik Lundin (@eest)
14 short_description: Manage packages on OpenBSD
15 description:
16 - Manage packages on OpenBSD using the pkg tools.
17 extends_documentation_fragment:
18 - community.general._attributes
19 attributes:
20 check_mode:
21 support: full
22 diff_mode:
23 support: partial
24 version_added: 9.1.0
25 details:
26 - Only works when check mode is not enabled.
27 options:
28 name:
29 description:
30 - A name or a list of names of the packages.
31 required: true
32 type: list
33 elements: str
34 state:
35 description:
36 - V(present) ensures the package is installed.
37 - V(latest) ensures the latest version of the package is installed.
38 - V(absent) ensures the specified package is not installed.
39 choices: [absent, latest, present, installed, removed]
40 default: present
41 type: str
42 build:
43 description:
44 - Build the package from source instead of downloading and installing a binary. Requires that the port source tree is
45 already installed. Automatically builds and installs the C(sqlports) package, if it is not already installed.
46 - Mutually exclusive with O(snapshot).
47 type: bool
48 default: false
49 snapshot:
50 description:
51 - Force C(%c) and C(%m) to expand to C(snapshots), even on a release kernel.
52 - Mutually exclusive with O(build).
53 type: bool
54 default: false
55 version_added: 1.3.0
56 ports_dir:
57 description:
58 - When used in combination with the O(build) option, allows overriding the default ports source directory.
59 default: /usr/ports
60 type: path
61 clean:
62 description:
63 - When updating or removing packages, delete the extra configuration file(s) in the old packages which are annotated
64 with C(@extra) in the packaging-list.
65 type: bool
66 default: false
67 quick:
68 description:
69 - Replace or delete packages quickly; do not bother with checksums before removing normal files.
70 type: bool
71 default: false
72 autoremove:
73 description:
74 - Calls C(pkg_delete -a) to remove automatically installed packages which are no longer needed.
75 type: bool
76 default: false
77 version_added: 11.3.0
78 notes:
79 - When used with a C(loop:) each package is processed individually, it is much more efficient to pass the list directly
80 to the O(name) option.
81 """
82
83 EXAMPLES = r"""
84 - name: Make sure nmap is installed
85 community.general.openbsd_pkg:
86 name: nmap
87 state: present
88
89 - name: Make sure nmap is the latest version
90 community.general.openbsd_pkg:
91 name: nmap
92 state: latest
93
94 - name: Make sure nmap is not installed
95 community.general.openbsd_pkg:
96 name: nmap
97 state: absent
98
99 - name: Make sure nmap is installed, build it from source if it is not
100 community.general.openbsd_pkg:
101 name: nmap
102 state: present
103 build: true
104
105 - name: Specify a pkg flavour with '--'
106 community.general.openbsd_pkg:
107 name: vim--no_x11
108 state: present
109
110 - name: Specify the default flavour to avoid ambiguity errors
111 community.general.openbsd_pkg:
112 name: vim--
113 state: present
114
115 - name: Specify a package branch (requires at least OpenBSD 6.0)
116 community.general.openbsd_pkg:
117 name: python%3.5
118 state: present
119
120 - name: Update all packages on the system
121 community.general.openbsd_pkg:
122 name: '*'
123 state: latest
124
125 - name: Purge a package and its configuration files
126 community.general.openbsd_pkg:
127 name: mpd
128 clean: true
129 state: absent
130
131 - name: Quickly remove a package without checking checksums
132 community.general.openbsd_pkg:
133 name: qt5
134 quick: true
135 state: absent
136
137 - name: Install packages, remove unused dependencies
138 community.general.openbsd_pkg:
139 name: ["tree", "mtr"]
140 autoremove: true
141
142 - name: Remove all unused dependencies
143 community.general.openbsd_pkg:
144 name: '*'
145 autoremove: true
146 """
147
148 import os
149 import platform
150 import re
151 import shlex
152 import sqlite3
153
154 from ansible.module_utils.basic import AnsibleModule
155
156 from ansible_collections.community.general.plugins.module_utils._version import LooseVersion
157
158
159 # Function used for executing commands.
160 def execute_command(cmd, module):
161 # Break command line into arguments.
162 # This makes run_command() use shell=False which we need to not cause shell
163 # expansion of special characters like '*'.
164 cmd_args = shlex.split(cmd)
165
166 # We set TERM to 'dumb' to keep pkg_add happy if the machine running
167 # ansible is using a TERM that the managed machine does not know about,
168 # e.g.: "No progress meter: failed termcap lookup on xterm-kitty".
169 return module.run_command(cmd_args, environ_update={"TERM": "dumb", "LANGUAGE": "C", "LC_ALL": "C"})
170
171
172 def get_all_installed(module):
173 """
174 Get all installed packaged. Used to support diff mode
175 """
176 command = "pkg_info -Iq"
177
178 rc, stdout, stderr = execute_command(command, module)
179
180 if stderr:
181 module.fail_json(msg=f"failed in get_all_installed(): {stderr}")
182
183 return stdout
184
185
186 # Function used to find out if a package is currently installed.
187 def get_package_state(names, pkg_spec, module):
188 info_cmd = "pkg_info -Iq"
189
190 for name in names:
191 command = f"{info_cmd} inst:{name}"
192
193 rc, stdout, stderr = execute_command(command, module)
194
195 if stderr:
196 match = re.search(rf"^Can't find inst:{re.escape(name)}$", stderr)
197 if match:
198 pkg_spec[name]["installed_state"] = False
199 else:
200 module.fail_json(msg=f"failed in get_package_state(): {stderr}")
201
202 if stdout:
203 # If the requested package name is just a stem, like "python", we may
204 # find multiple packages with that name.
205 pkg_spec[name]["installed_names"] = stdout.splitlines()
206 module.debug(f"get_package_state(): installed_names = {pkg_spec[name]['installed_names']}")
207 pkg_spec[name]["installed_state"] = True
208 else:
209 pkg_spec[name]["installed_state"] = False
210
211
212 # Function used to make sure a package is present.
213 def package_present(names, pkg_spec, module):
214 build = module.params["build"]
215
216 for name in names:
217 # It is possible package_present() has been called from package_latest().
218 # In that case we do not want to operate on the whole list of names,
219 # only the leftovers.
220 if pkg_spec["package_latest_leftovers"]:
221 if name not in pkg_spec["package_latest_leftovers"]:
222 module.debug(f"package_present(): ignoring '{name}' which is not a package_latest() leftover")
223 continue
224 else:
225 module.debug(f"package_present(): handling package_latest() leftovers, installing '{name}'")
226
227 if module.check_mode:
228 install_cmd = "pkg_add -Imn"
229 else:
230 if build is True:
231 port_dir = f"{module.params['ports_dir']}/{get_package_source_path(name, pkg_spec, module)}"
232 if os.path.isdir(port_dir):
233 if pkg_spec[name]["flavor"]:
234 flavors = pkg_spec[name]["flavor"].replace("-", " ")
235 install_cmd = f'cd {port_dir} && make clean=depends && FLAVOR="{flavors}" make install && make clean=depends'
236 elif pkg_spec[name]["subpackage"]:
237 install_cmd = f'cd {port_dir} && make clean=depends && SUBPACKAGE="{pkg_spec[name]["subpackage"]}" make install && make clean=depends'
238 else:
239 install_cmd = f"cd {port_dir} && make install && make clean=depends"
240 else:
241 module.fail_json(msg=f"the port source directory {port_dir} does not exist")
242 else:
243 install_cmd = "pkg_add -Im"
244
245 if module.params["snapshot"] is True:
246 install_cmd += " -Dsnap"
247
248 if pkg_spec[name]["installed_state"] is False:
249 # Attempt to install the package
250 if build is True and not module.check_mode:
251 (pkg_spec[name]["rc"], pkg_spec[name]["stdout"], pkg_spec[name]["stderr"]) = module.run_command(
252 install_cmd, module, use_unsafe_shell=True
253 )
254 else:
255 (pkg_spec[name]["rc"], pkg_spec[name]["stdout"], pkg_spec[name]["stderr"]) = execute_command(
256 f"{install_cmd} {name}", module
257 )
258
259 # The behaviour of pkg_add is a bit different depending on if a
260 # specific version is supplied or not.
261 #
262 # When a specific version is supplied the return code will be 0 when
263 # a package is found and 1 when it is not. If a version is not
264 # supplied the tool will exit 0 in both cases.
265 #
266 # It is important to note that "version" relates to the
267 # packages-specs(7) notion of a version. If using the branch syntax
268 # (like "python%3.5") even though a branch name may look like a
269 # version string it is not used an one by pkg_add.
270 if pkg_spec[name]["version"] or build is True:
271 # Depend on the return code.
272 module.debug(f"package_present(): depending on return code for name '{name}'")
273 if pkg_spec[name]["rc"]:
274 pkg_spec[name]["changed"] = False
275 else:
276 # Depend on stderr instead.
277 module.debug(f"package_present(): depending on stderr for name '{name}'")
278 if pkg_spec[name]["stderr"]:
279 # There is a corner case where having an empty directory in
280 # installpath prior to the right location will result in a
281 # "file:/local/package/directory/ is empty" message on stderr
282 # while still installing the package, so we need to look for
283 # for a message like "packagename-1.0: ok" just in case.
284 match = re.search(rf"\W{re.escape(pkg_spec[name]['stem'])}-[^:]+: ok\W", pkg_spec[name]["stdout"])
285
286 if match:
287 # It turns out we were able to install the package.
288 module.debug(f"package_present(): we were able to install package for name '{name}'")
289 pkg_spec[name]["changed"] = True
290 else:
291 # We really did fail, fake the return code.
292 module.debug(f"package_present(): we really did fail for name '{name}'")
293 pkg_spec[name]["rc"] = 1
294 pkg_spec[name]["changed"] = False
295 else:
296 module.debug(f"package_present(): stderr was not set for name '{name}'")
297
298 if pkg_spec[name]["rc"] == 0:
299 pkg_spec[name]["changed"] = True
300
301 else:
302 pkg_spec[name]["rc"] = 0
303 pkg_spec[name]["stdout"] = ""
304 pkg_spec[name]["stderr"] = ""
305 pkg_spec[name]["changed"] = False
306
307
308 # Function used to make sure a package is the latest available version.
309 def package_latest(names, pkg_spec, module):
310 if module.params["build"] is True:
311 module.fail_json(msg=f"the combination of build={module.params['build']} and state=latest is not supported")
312
313 upgrade_cmd = "pkg_add -um"
314
315 if module.check_mode:
316 upgrade_cmd += "n"
317
318 if module.params["clean"]:
319 upgrade_cmd += "c"
320
321 if module.params["quick"]:
322 upgrade_cmd += "q"
323
324 if module.params["snapshot"]:
325 upgrade_cmd += " -Dsnap"
326
327 for name in names:
328 if pkg_spec[name]["installed_state"] is True:
329 # Attempt to upgrade the package.
330 (pkg_spec[name]["rc"], pkg_spec[name]["stdout"], pkg_spec[name]["stderr"]) = execute_command(
331 f"{upgrade_cmd} {name}", module
332 )
333
334 # Look for output looking something like "nmap-6.01->6.25: ok" to see if
335 # something changed (or would have changed). Use \W to delimit the match
336 # from progress meter output.
337 pkg_spec[name]["changed"] = False
338 for installed_name in pkg_spec[name]["installed_names"]:
339 module.debug(f"package_latest(): checking for pre-upgrade package name: {installed_name}")
340 match = re.search(rf"\W{re.escape(installed_name)}->.+: ok\W", pkg_spec[name]["stdout"])
341 if match:
342 module.debug(f"package_latest(): pre-upgrade package name match: {installed_name}")
343
344 pkg_spec[name]["changed"] = True
345 break
346
347 # FIXME: This part is problematic. Based on the issues mentioned (and
348 # handled) in package_present() it is not safe to blindly trust stderr
349 # as an indicator that the command failed, and in the case with
350 # empty installpath directories this will break.
351 #
352 # For now keep this safeguard here, but ignore it if we managed to
353 # parse out a successful update above. This way we will report a
354 # successful run when we actually modify something but fail
355 # otherwise.
356 if pkg_spec[name]["changed"] is not True:
357 if pkg_spec[name]["stderr"]:
358 pkg_spec[name]["rc"] = 1
359
360 else:
361 # Note packages that need to be handled by package_present
362 module.debug(f"package_latest(): package '{name}' is not installed, will be handled by package_present()")
363 pkg_spec["package_latest_leftovers"].append(name)
364
365 # If there were any packages that were not installed we call
366 # package_present() which will handle those.
367 if pkg_spec["package_latest_leftovers"]:
368 module.debug("package_latest(): calling package_present() to handle leftovers")
369 package_present(names, pkg_spec, module)
370
371
372 # Function used to make sure a package is not installed.
373 def package_absent(names, pkg_spec, module):
374 remove_cmd = "pkg_delete -I"
375
376 if module.check_mode:
377 remove_cmd += "n"
378
379 if module.params["clean"]:
380 remove_cmd += "c"
381
382 if module.params["quick"]:
383 remove_cmd += "q"
384
385 for name in names:
386 if pkg_spec[name]["installed_state"] is True:
387 # Attempt to remove the package.
388 (pkg_spec[name]["rc"], pkg_spec[name]["stdout"], pkg_spec[name]["stderr"]) = execute_command(
389 f"{remove_cmd} {name}", module
390 )
391
392 if pkg_spec[name]["rc"] == 0:
393 pkg_spec[name]["changed"] = True
394 else:
395 pkg_spec[name]["changed"] = False
396
397 else:
398 pkg_spec[name]["rc"] = 0
399 pkg_spec[name]["stdout"] = ""
400 pkg_spec[name]["stderr"] = ""
401 pkg_spec[name]["changed"] = False
402
403
404 # Function used to remove unused dependencies.
405 def package_rm_unused_deps(pkg_spec, module):
406 rm_unused_deps_cmd = "pkg_delete -Ia"
407
408 if module.check_mode:
409 rm_unused_deps_cmd += "n"
410
411 if module.params["clean"]:
412 rm_unused_deps_cmd += "c"
413
414 if module.params["quick"]:
415 rm_unused_deps_cmd += "q"
416
417 # If we run the commands, we set changed to true to let
418 # the package list change detection code do the actual work.
419
420 # Create a minimal pkg_spec entry for '*' to store return values.
421 pkg_spec["*"] = {}
422
423 # Attempt to remove unused dependencies.
424 pkg_spec["*"]["rc"], pkg_spec["*"]["stdout"], pkg_spec["*"]["stderr"] = execute_command(rm_unused_deps_cmd, module)
425 pkg_spec["*"]["changed"] = True
426
427
428 # Function used to parse the package name based on packages-specs(7).
429 # The general name structure is "stem-version[-flavors]".
430 #
431 # Names containing "%" are a special variation not part of the
432 # packages-specs(7) syntax. See pkg_add(1) on OpenBSD 6.0 or later for a
433 # description.
434 def parse_package_name(names, pkg_spec, module):
435 # Initialize empty list of package_latest() leftovers.
436 pkg_spec["package_latest_leftovers"] = []
437
438 for name in names:
439 module.debug(f"parse_package_name(): parsing name: {name}")
440 # Do some initial matches so we can base the more advanced regex on that.
441 version_match = re.search("-[0-9]", name)
442 versionless_match = re.search("--", name)
443
444 # Stop if someone is giving us a name that both has a version and is
445 # version-less at the same time.
446 if version_match and versionless_match:
447 module.fail_json(msg=f"package name both has a version and is version-less: {name}")
448
449 # All information for a given name is kept in the pkg_spec keyed by that name.
450 pkg_spec[name] = {}
451
452 # If name includes a version.
453 if version_match:
454 match = re.search(
455 "^(?P<stem>[^%]+)-(?P<version>[0-9][^-]*)(?P<flavor_separator>-)?(?P<flavor>[a-z].*)?(%(?P<branch>.+))?$",
456 name,
457 )
458 if match:
459 pkg_spec[name]["stem"] = match.group("stem")
460 pkg_spec[name]["version_separator"] = "-"
461 pkg_spec[name]["version"] = match.group("version")
462 pkg_spec[name]["flavor_separator"] = match.group("flavor_separator")
463 pkg_spec[name]["flavor"] = match.group("flavor")
464 pkg_spec[name]["branch"] = match.group("branch")
465 pkg_spec[name]["style"] = "version"
466 module.debug(
467 f"version_match: stem: {pkg_spec[name]['stem']}, version: {pkg_spec[name]['version']}, "
468 f"flavor_separator: {pkg_spec[name]['flavor_separator']}, flavor: {pkg_spec[name]['flavor']}, branch: {pkg_spec[name]['branch']}, "
469 f"style: {pkg_spec[name]['style']}"
470 )
471 else:
472 module.fail_json(msg=f"unable to parse package name at version_match: {name}")
473
474 # If name includes no version but is version-less ("--").
475 elif versionless_match:
476 match = re.search("^(?P<stem>[^%]+)--(?P<flavor>[a-z].*)?(%(?P<branch>.+))?$", name)
477 if match:
478 pkg_spec[name]["stem"] = match.group("stem")
479 pkg_spec[name]["version_separator"] = "-"
480 pkg_spec[name]["version"] = None
481 pkg_spec[name]["flavor_separator"] = "-"
482 pkg_spec[name]["flavor"] = match.group("flavor")
483 pkg_spec[name]["branch"] = match.group("branch")
484 pkg_spec[name]["style"] = "versionless"
485 module.debug(
486 f"versionless_match: stem: {pkg_spec[name]['stem']}, flavor: {pkg_spec[name]['flavor']}, "
487 f"branch: {pkg_spec[name]['branch']}, style: {pkg_spec[name]['style']}"
488 )
489 else:
490 module.fail_json(msg=f"unable to parse package name at versionless_match: {name}")
491
492 # If name includes no version, and is not version-less, it is all a
493 # stem, possibly with a branch (%branchname) tacked on at the
494 # end.
495 else:
496 match = re.search("^(?P<stem>[^%]+)(%(?P<branch>.+))?$", name)
497 if match:
498 pkg_spec[name]["stem"] = match.group("stem")
499 pkg_spec[name]["version_separator"] = None
500 pkg_spec[name]["version"] = None
501 pkg_spec[name]["flavor_separator"] = None
502 pkg_spec[name]["flavor"] = None
503 pkg_spec[name]["branch"] = match.group("branch")
504 pkg_spec[name]["style"] = "stem"
505 module.debug(
506 f"stem_match: stem: {pkg_spec[name]['stem']}, branch: {pkg_spec[name]['branch']}, style: {pkg_spec[name]['style']}"
507 )
508 else:
509 module.fail_json(msg=f"unable to parse package name at else: {name}")
510
511 # Verify that the managed host is new enough to support branch syntax.
512 if pkg_spec[name]["branch"]:
513 branch_release = "6.0"
514
515 if LooseVersion(platform.release()) < LooseVersion(branch_release):
516 module.fail_json(
517 msg=f"package name using 'branch' syntax requires at least OpenBSD {branch_release}: {name}"
518 )
519
520 # Sanity check that there are no trailing dashes in flavor.
521 # Try to stop strange stuff early so we can be strict later.
522 if pkg_spec[name]["flavor"]:
523 match = re.search("-$", pkg_spec[name]["flavor"])
524 if match:
525 module.fail_json(msg=f"trailing dash in flavor: {pkg_spec[name]['flavor']}")
526
527
528 # Function used for figuring out the port path.
529 def get_package_source_path(name, pkg_spec, module):
530 pkg_spec[name]["subpackage"] = None
531 if pkg_spec[name]["stem"] == "sqlports":
532 return "databases/sqlports"
533 else:
534 # try for an exact match first
535 sqlports_db_file = "/usr/local/share/sqlports"
536 if not os.path.isfile(sqlports_db_file):
537 module.fail_json(msg=f"sqlports file '{sqlports_db_file}' is missing")
538
539 conn = sqlite3.connect(sqlports_db_file)
540 first_part_of_query = "SELECT fullpkgpath, fullpkgname FROM ports WHERE fullpkgname"
541 query = f"{first_part_of_query} = ?"
542 module.debug(f"package_package_source_path(): exact query: {query}")
543 cursor = conn.execute(query, (name,))
544 results = cursor.fetchall()
545
546 # next, try for a fuzzier match
547 if len(results) < 1:
548 looking_for = (
549 pkg_spec[name]["stem"]
550 + (pkg_spec[name]["version_separator"] or "-")
551 + (pkg_spec[name]["version"] or "%")
552 )
553 query = f"{first_part_of_query} LIKE ?"
554 if pkg_spec[name]["flavor"]:
555 looking_for += pkg_spec[name]["flavor_separator"] + pkg_spec[name]["flavor"]
556 module.debug(f"package_package_source_path(): fuzzy flavor query: {query}")
557 cursor = conn.execute(query, (looking_for,))
558 elif pkg_spec[name]["style"] == "versionless":
559 query += " AND fullpkgname NOT LIKE ?"
560 module.debug(f"package_package_source_path(): fuzzy versionless query: {query}")
561 cursor = conn.execute(
562 query,
563 (
564 looking_for,
565 f"{looking_for}-%",
566 ),
567 )
568 else:
569 module.debug(f"package_package_source_path(): fuzzy query: {query}")
570 cursor = conn.execute(query, (looking_for,))
571 results = cursor.fetchall()
572
573 # error if we don't find exactly 1 match
574 conn.close()
575 if len(results) < 1:
576 module.fail_json(msg=f"could not find a port by the name '{name}'")
577 if len(results) > 1:
578 matches = map(lambda x: x[1], results)
579 module.fail_json(msg=f"too many matches, unsure which to build: {' OR '.join(matches)}")
580
581 # there's exactly 1 match, so figure out the subpackage, if any, then return
582 fullpkgpath = results[0][0]
583 parts = fullpkgpath.split(",")
584 if len(parts) > 1 and parts[1][0] == "-":
585 pkg_spec[name]["subpackage"] = parts[1]
586 return parts[0]
587
588
589 # Function used for upgrading all installed packages.
590 def upgrade_packages(pkg_spec, module):
591 if module.check_mode:
592 upgrade_cmd = "pkg_add -Imnu"
593 else:
594 upgrade_cmd = "pkg_add -Imu"
595
596 if module.params["snapshot"]:
597 upgrade_cmd += " -Dsnap"
598
599 # Create a minimal pkg_spec entry for '*' to store return values.
600 pkg_spec["*"] = {}
601
602 # Attempt to upgrade all packages.
603 pkg_spec["*"]["rc"], pkg_spec["*"]["stdout"], pkg_spec["*"]["stderr"] = execute_command(upgrade_cmd, module)
604
605 # Try to find any occurrence of a package changing version like:
606 # "bzip2-1.0.6->1.0.6p0: ok".
607 match = re.search(r"\W\w.+->.+: ok\W", pkg_spec["*"]["stdout"])
608 if match:
609 pkg_spec["*"]["changed"] = True
610
611 else:
612 pkg_spec["*"]["changed"] = False
613
614 # It seems we can not trust the return value, so depend on the presence of
615 # stderr to know if something failed.
616 if pkg_spec["*"]["stderr"]:
617 pkg_spec["*"]["rc"] = 1
618 else:
619 pkg_spec["*"]["rc"] = 0
620
621
622 # ===========================================
623 # Main control flow.
624 def main():
625 module = AnsibleModule(
626 argument_spec=dict(
627 name=dict(type="list", elements="str", required=True),
628 state=dict(type="str", default="present", choices=["absent", "installed", "latest", "present", "removed"]),
629 build=dict(type="bool", default=False),
630 snapshot=dict(type="bool", default=False),
631 ports_dir=dict(type="path", default="/usr/ports"),
632 quick=dict(type="bool", default=False),
633 clean=dict(type="bool", default=False),
634 autoremove=dict(type="bool", default=False),
635 ),
636 mutually_exclusive=[["snapshot", "build"]],
637 supports_check_mode=True,
638 )
639
640 name = module.params["name"]
641 state = module.params["state"]
642 build = module.params["build"]
643 ports_dir = module.params["ports_dir"]
644
645 result = {}
646 result["name"] = name
647 result["state"] = state
648 result["build"] = build
649 result["diff"] = {}
650
651 # The data structure used to keep track of package information.
652 pkg_spec = {}
653
654 new_package_list = original_package_list = get_all_installed(module)
655
656 if build is True:
657 if not os.path.isdir(ports_dir):
658 module.fail_json(msg=f"the ports source directory {ports_dir} does not exist")
659
660 # build sqlports if its not installed yet
661 parse_package_name(["sqlports"], pkg_spec, module)
662 get_package_state(["sqlports"], pkg_spec, module)
663 if not pkg_spec["sqlports"]["installed_state"]:
664 module.debug(f"main(): installing 'sqlports' because build={module.params['build']}")
665 package_present(["sqlports"], pkg_spec, module)
666
667 asterisk_name = False
668 for n in name:
669 if n == "*":
670 if len(name) != 1:
671 module.fail_json(msg="the package name '*' can not be mixed with other names")
672
673 asterisk_name = True
674
675 if asterisk_name:
676 if state != "latest" and not module.params["autoremove"]:
677 module.fail_json(msg="the package name '*' is only valid when using state=latest or autoremove=true")
678
679 if state == "latest":
680 # Perform an upgrade of all installed packages.
681 upgrade_packages(pkg_spec, module)
682
683 if module.params["autoremove"]:
684 # Remove unused dependencies.
685 package_rm_unused_deps(pkg_spec, module)
686 else:
687 # Parse package names and put results in the pkg_spec dictionary.
688 parse_package_name(name, pkg_spec, module)
689
690 # Not sure how the branch syntax is supposed to play together
691 # with build mode. Disable it for now.
692 for n in name:
693 if pkg_spec[n]["branch"] and module.params["build"] is True:
694 module.fail_json(
695 msg=f"the combination of 'branch' syntax and build={module.params['build']} is not supported: {n}"
696 )
697
698 # Get state for all package names.
699 get_package_state(name, pkg_spec, module)
700
701 # Perform requested action.
702 if state in ["installed", "present"]:
703 package_present(name, pkg_spec, module)
704 elif state in ["absent", "removed"]:
705 package_absent(name, pkg_spec, module)
706 elif state == "latest":
707 package_latest(name, pkg_spec, module)
708
709 # Handle autoremove if requested for non-asterisk packages
710 if module.params["autoremove"]:
711 package_rm_unused_deps(pkg_spec, module)
712
713 # The combined changed status for all requested packages. If anything
714 # is changed this is set to True.
715 combined_changed = False
716
717 # The combined failed status for all requested packages. If anything
718 # failed this is set to True.
719 combined_failed = False
720
721 # We combine all error messages in this comma separated string, for example:
722 # "msg": "Can't find nmapp\n, Can't find nmappp\n"
723 combined_error_message = ""
724
725 # Loop over all requested package names and check if anything failed or
726 # changed.
727 for n in name:
728 if pkg_spec[n]["rc"] != 0:
729 combined_failed = True
730 if pkg_spec[n]["stderr"]:
731 if combined_error_message:
732 combined_error_message += f", {pkg_spec[n]['stderr']}"
733 else:
734 combined_error_message = pkg_spec[n]["stderr"]
735 else:
736 if combined_error_message:
737 combined_error_message += f", {pkg_spec[n]['stdout']}"
738 else:
739 combined_error_message = pkg_spec[n]["stdout"]
740
741 if pkg_spec[n]["changed"] is True:
742 combined_changed = True
743
744 # If combined_error_message contains anything at least some part of the
745 # list of requested package names failed.
746 if combined_failed:
747 module.fail_json(msg=combined_error_message, **result)
748
749 result["changed"] = combined_changed
750
751 if not module.check_mode:
752 new_package_list = get_all_installed(module)
753 result["diff"] = dict(before=original_package_list, after=new_package_list)
754 result["changed"] = result["diff"]["before"] != result["diff"]["after"]
755
756 module.exit_json(**result)
757
758
759 if __name__ == "__main__":
760 main()