Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_homebrew.py

raw
1 # Copyright (c) Ansible project
2 # Simplified BSD License (see LICENSES/BSD-2-Clause.txt or https://opensource.org/licenses/BSD-2-Clause)
3 # SPDX-License-Identifier: BSD-2-Clause
4
5 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import os
11 import re
12 import typing as t
13
14 if t.TYPE_CHECKING:
15 from ansible.module_utils.basic import AnsibleModule
16
17
18 def _create_regex_group_complement(s: str) -> re.Pattern:
19 lines = (line.strip() for line in s.split("\n") if line.strip())
20 chars = [_f for _f in (line.split("#")[0].strip() for line in lines) if _f]
21 group = rf"[^{''.join(chars)}]"
22 return re.compile(group)
23
24
25 class HomebrewValidate:
26 # class regexes ------------------------------------------------ {{{
27 VALID_PATH_CHARS = rf"""
28 \w # alphanumeric characters (i.e., [a-zA-Z0-9_])
29 \s # spaces
30 : # colons
31 {os.path.sep} # the OS-specific path separator
32 . # dots
33 \- # dashes
34 """
35
36 VALID_BREW_PATH_CHARS = rf"""
37 \w # alphanumeric characters (i.e., [a-zA-Z0-9_])
38 \s # spaces
39 {os.path.sep} # the OS-specific path separator
40 . # dots
41 \- # dashes
42 """
43
44 VALID_PACKAGE_CHARS = r"""
45 \w # alphanumeric characters (i.e., [a-zA-Z0-9_])
46 . # dots
47 / # slash (for taps)
48 \+ # plusses
49 \- # dashes
50 : # colons (for URLs)
51 @ # at-sign
52 """
53
54 INVALID_PATH_REGEX = _create_regex_group_complement(VALID_PATH_CHARS)
55 INVALID_BREW_PATH_REGEX = _create_regex_group_complement(VALID_BREW_PATH_CHARS)
56 INVALID_PACKAGE_REGEX = _create_regex_group_complement(VALID_PACKAGE_CHARS)
57 # /class regexes ----------------------------------------------- }}}
58
59 # class validations -------------------------------------------- {{{
60 @classmethod
61 def valid_path(cls, path: list[str] | str) -> bool:
62 """
63 `path` must be one of:
64 - list of paths
65 - a string containing only:
66 - alphanumeric characters
67 - dashes
68 - dots
69 - spaces
70 - colons
71 - os.path.sep
72 """
73
74 if isinstance(path, str):
75 return not cls.INVALID_PATH_REGEX.search(path)
76
77 try:
78 iter(path)
79 except TypeError:
80 return False
81 else:
82 paths = path
83 return all(cls.valid_brew_path(path_) for path_ in paths)
84
85 @classmethod
86 def valid_brew_path(cls, brew_path: str | None) -> bool:
87 """
88 `brew_path` must be one of:
89 - None
90 - a string containing only:
91 - alphanumeric characters
92 - dashes
93 - dots
94 - spaces
95 - os.path.sep
96 """
97
98 if brew_path is None:
99 return True
100
101 return isinstance(brew_path, str) and not cls.INVALID_BREW_PATH_REGEX.search(brew_path)
102
103 @classmethod
104 def valid_package(cls, package: str | None) -> bool:
105 """A valid package is either None or alphanumeric."""
106
107 if package is None:
108 return True
109
110 return isinstance(package, str) and not cls.INVALID_PACKAGE_REGEX.search(package)
111
112
113 def parse_brew_path(module: AnsibleModule) -> str:
114 """Attempt to find the Homebrew executable path.
115
116 Requires:
117 - module has a `path` parameter
118 - path is a valid path string for the target OS. Otherwise, module.fail_json()
119 is called with msg="Invalid_path: <path>".
120 """
121 path = module.params["path"]
122 if not HomebrewValidate.valid_path(path):
123 module.fail_json(msg=f"Invalid path: {path}")
124
125 if isinstance(path, str):
126 paths = path.split(":")
127 elif isinstance(path, list):
128 paths = path
129 else:
130 module.fail_json(msg=f"Invalid path: {path}")
131
132 brew_path = module.get_bin_path("brew", required=True, opt_dirs=paths)
133 if not HomebrewValidate.valid_brew_path(brew_path):
134 module.fail_json(msg=f"Invalid brew path: {brew_path}")
135
136 return brew_path