Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2012, Franck Cuny <[email protected]>
4 # Copyright (c) 2021, Alexei Znamensky <[email protected]>
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: cpanm
12 short_description: Manages Perl library dependencies
13 description:
14 - Manage Perl library dependencies using cpanminus.
15 extends_documentation_fragment:
16 - community.general._attributes
17 attributes:
18 check_mode:
19 support: none
20 diff_mode:
21 support: none
22 options:
23 name:
24 type: str
25 description:
26 - The Perl library to install. Valid values change according to the O(mode), see notes for more details.
27 - Note that for installing from a local path the parameter O(from_path) should be used.
28 aliases: [pkg]
29 from_path:
30 type: path
31 description:
32 - The local directory or C(tar.gz) file to install from.
33 notest:
34 description:
35 - Do not run unit tests.
36 type: bool
37 default: false
38 locallib:
39 description:
40 - Specify the install base to install modules.
41 type: path
42 mirror:
43 description:
44 - Specifies the base URL for the CPAN mirror to use.
45 type: str
46 mirror_only:
47 description:
48 - Use the mirror's index file instead of the CPAN Meta DB.
49 type: bool
50 default: false
51 installdeps:
52 description:
53 - Only install dependencies.
54 type: bool
55 default: false
56 install_recommendations:
57 description:
58 - If V(true), installs dependencies declared as recommends per META spec.
59 - If V(false), it ensures the dependencies declared as recommends are not installed, overriding any decision made earlier
60 in E(PERL_CPANM_OPT).
61 - If parameter is not set, C(cpanm) uses its existing defaults.
62 - When these dependencies fail to install, cpanm continues the installation, since they are just recommendation.
63 type: bool
64 version_added: 10.3.0
65 install_suggestions:
66 description:
67 - If V(true), installs dependencies declared as suggests per META spec.
68 - If V(false), it ensures the dependencies declared as suggests are not installed, overriding any decision made earlier
69 in E(PERL_CPANM_OPT).
70 - If parameter is not set, C(cpanm) uses its existing defaults.
71 - When these dependencies fail to install, C(cpanm) continues the installation, since they are just suggestions.
72 type: bool
73 version_added: 10.3.0
74 version:
75 description:
76 - Version specification for the perl module. When O(mode=new), C(cpanm) version operators are accepted.
77 type: str
78 executable:
79 description:
80 - Override the path to the C(cpanm) executable.
81 type: path
82 mode:
83 description:
84 - Controls the module behavior. See notes below for more details.
85 - The default changed from V(compatibility) to V(new) in community.general 9.0.0.
86 V(compatibility) was removed from community.general 13.0.0.
87 - 'O(mode=new): The O(name) parameter may refer to a module name, a distribution file, a HTTP URL or a git repository
88 URL as described in C(cpanminus) documentation. C(cpanm) version specifiers are recognized. This is the default mode
89 from community.general 9.0.0 onwards.'
90 type: str
91 choices: [new]
92 default: new
93 version_added: 3.0.0
94 name_check:
95 description:
96 - When O(mode=new), this parameter can be used to check if there is a module O(name) installed (at O(version), when
97 specified).
98 type: str
99 version_added: 3.0.0
100 notes:
101 - Please note that U(http://search.cpan.org/dist/App-cpanminus/bin/cpanm, cpanm) must be installed on the remote host.
102 seealso:
103 - name: C(cpanm) command manual page
104 description: Manual page for the command.
105 link: https://metacpan.org/dist/App-cpanminus/view/bin/cpanm
106 author:
107 - "Franck Cuny (@fcuny)"
108 - "Alexei Znamensky (@russoz)"
109 """
110
111 EXAMPLES = r"""
112 - name: Install Dancer perl package
113 community.general.cpanm:
114 name: Dancer
115
116 - name: Install version 0.99_05 of the Plack perl package
117 community.general.cpanm:
118 name: MIYAGAWA/Plack-0.99_05.tar.gz
119
120 - name: Install Dancer into the specified locallib
121 community.general.cpanm:
122 name: Dancer
123 locallib: /srv/webapps/my_app/extlib
124
125 - name: Install perl dependencies from local directory
126 community.general.cpanm:
127 from_path: /srv/webapps/my_app/src/
128
129 - name: Install Dancer perl package without running the unit tests in indicated locallib
130 community.general.cpanm:
131 name: Dancer
132 notest: true
133 locallib: /srv/webapps/my_app/extlib
134
135 - name: Install Dancer perl package from a specific mirror
136 community.general.cpanm:
137 name: Dancer
138 mirror: 'http://cpan.cpantesters.org/'
139
140 - name: Install Dancer perl package into the system root path
141 become: true
142 community.general.cpanm:
143 name: Dancer
144
145 - name: Install Dancer if it is not already installed OR the installed version is older than version 1.0
146 community.general.cpanm:
147 name: Dancer
148 version: '1.0'
149 """
150
151 RETURN = r"""
152 cpanm_version:
153 description: Version of CPANMinus.
154 type: str
155 returned: always
156 sample: "1.7047"
157 version_added: 10.0.0
158 """
159
160
161 import os
162 import re
163
164 from ansible_collections.community.general.plugins.module_utils._cmd_runner import CmdRunner, cmd_runner_fmt
165 from ansible_collections.community.general.plugins.module_utils._module_helper import ModuleHelper
166
167
168 class CPANMinus(ModuleHelper):
169 output_params = ["name", "version"]
170 module = dict(
171 argument_spec=dict(
172 name=dict(type="str", aliases=["pkg"]),
173 version=dict(type="str"),
174 from_path=dict(type="path"),
175 notest=dict(type="bool", default=False),
176 locallib=dict(type="path"),
177 mirror=dict(type="str"),
178 mirror_only=dict(type="bool", default=False),
179 installdeps=dict(type="bool", default=False),
180 install_recommendations=dict(type="bool"),
181 install_suggestions=dict(type="bool"),
182 executable=dict(type="path"),
183 mode=dict(type="str", default="new", choices=["new"]),
184 name_check=dict(type="str"),
185 ),
186 required_one_of=[("name", "from_path")],
187 )
188 command = "cpanm"
189 command_args_formats = dict(
190 notest=cmd_runner_fmt.as_bool("--notest"),
191 locallib=cmd_runner_fmt.as_opt_val("--local-lib"),
192 mirror=cmd_runner_fmt.as_opt_val("--mirror"),
193 mirror_only=cmd_runner_fmt.as_bool("--mirror-only"),
194 installdeps=cmd_runner_fmt.as_bool("--installdeps"),
195 install_recommendations=cmd_runner_fmt.as_bool("--with-recommends", "--without-recommends", ignore_none=True),
196 install_suggestions=cmd_runner_fmt.as_bool("--with-suggests", "--without-suggests", ignore_none=True),
197 pkg_spec=cmd_runner_fmt.as_list(),
198 cpanm_version=cmd_runner_fmt.as_fixed("--version"),
199 )
200
201 def __init_module__(self):
202 v = self.vars
203 if v.name and v.from_path:
204 self.do_raise("Parameters 'name' and 'from_path' are mutually exclusive when 'mode=new'")
205
206 self.command = v.executable if v.executable else self.command
207 self.runner = CmdRunner(self.module, self.command, self.command_args_formats, check_rc=True)
208 self.vars.binary = self.runner.binary
209
210 with self.runner("cpanm_version") as ctx:
211 rc, out, err = ctx.run()
212 line = out.split("\n")[0]
213 match = re.search(r"version\s+([\d\.]+)\s+", line)
214 if not match:
215 self.do_raise(f"Failed to determine version number. First line of output: {line}")
216 self.vars.cpanm_version = match.group(1)
217
218 def _is_package_installed(self, name, locallib, version):
219 def process(rc, out, err):
220 return rc == 0
221
222 if name is None or name.endswith(".tar.gz"):
223 return False
224 version = "" if version is None else f" {version}"
225
226 env = {"PERL5LIB": f"{locallib}/lib/perl5"} if locallib else {}
227 runner = CmdRunner(
228 self.module, ["perl", "-le"], {"mod": cmd_runner_fmt.as_list()}, check_rc=False, environ_update=env
229 )
230 with runner("mod", output_process=process) as ctx:
231 return ctx.run(mod=f"use {name}{version};")
232
233 def sanitize_pkg_spec_version(self, pkg_spec, version):
234 if version is None:
235 return pkg_spec
236 if pkg_spec.endswith(".tar.gz"):
237 self.do_raise(msg="parameter 'version' must not be used when installing from a file")
238 if os.path.isdir(pkg_spec):
239 self.do_raise(msg="parameter 'version' must not be used when installing from a directory")
240 if pkg_spec.endswith(".git"):
241 if version.startswith("~"):
242 self.do_raise(msg="operator '~' not allowed in version parameter when installing from git repository")
243 version = version if version.startswith("@") else f"@{version}"
244 elif version[0] not in ("@", "~"):
245 version = f"~{version}"
246 return pkg_spec + version
247
248 def __run__(self):
249 def process(rc, out, err):
250 return "is up to date" not in err and "is up to date" not in out
251
252 v = self.vars
253 pkg_param = "from_path" if v.from_path else "name"
254
255 installed = self._is_package_installed(v.name_check, v.locallib, v.version) if v.name_check else False
256 if installed:
257 return
258 pkg_spec = self.sanitize_pkg_spec_version(v[pkg_param], v.version)
259
260 with self.runner(
261 [
262 "notest",
263 "locallib",
264 "mirror",
265 "mirror_only",
266 "installdeps",
267 "install_recommendations",
268 "install_suggestions",
269 "pkg_spec",
270 ],
271 output_process=process,
272 ) as ctx:
273 self.changed = ctx.run(pkg_spec=pkg_spec)
274
275
276 def main():
277 CPANMinus.execute()
278
279
280 if __name__ == "__main__":
281 main()