Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2023 Aritra Sen <[email protected]>
4 # Copyright (c) 2017 Chris Hoffman <[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: pnpm
12 short_description: Manage Node.js packages with C(pnpm)
13 version_added: 7.4.0
14 description:
15 - Manage Node.js packages with the L(pnpm package manager, https://pnpm.io/).
16 author:
17 - "Aritra Sen (@aretrosen)"
18 - "Chris Hoffman (@chrishoffman), creator of NPM Ansible module"
19 extends_documentation_fragment:
20 - community.general._attributes
21 attributes:
22 check_mode:
23 support: full
24 diff_mode:
25 support: none
26 options:
27 name:
28 description:
29 - The name of a Node.js library to install.
30 - All packages in C(package.json) are installed if not provided.
31 type: str
32 alias:
33 description:
34 - Alias of the Node.js library.
35 type: str
36 path:
37 description:
38 - The base path to install the Node.js libraries.
39 type: path
40 version:
41 description:
42 - The version of the library to be installed, in semver format.
43 type: str
44 global:
45 description:
46 - Install the Node.js library globally.
47 default: false
48 type: bool
49 executable:
50 description:
51 - The executable location for pnpm.
52 - The default location it searches for is E(PATH), fails if not set.
53 type: path
54 ignore_scripts:
55 description:
56 - Use the C(--ignore-scripts) flag when installing.
57 type: bool
58 default: false
59 no_optional:
60 description:
61 - Do not install optional packages, equivalent to C(--no-optional).
62 type: bool
63 default: false
64 production:
65 description:
66 - Install dependencies in production mode.
67 - Pnpm ignores any dependencies under C(devDependencies) in package.json.
68 type: bool
69 default: false
70 dev:
71 description:
72 - Install dependencies in development mode.
73 - Pnpm ignores any regular dependencies in C(package.json).
74 default: false
75 type: bool
76 optional:
77 description:
78 - Install dependencies in optional mode.
79 default: false
80 type: bool
81 state:
82 description:
83 - Installation state of the named Node.js library.
84 - If V(absent) is selected, a name option must be provided.
85 type: str
86 default: present
87 choices: ["present", "absent", "latest"]
88 requirements:
89 - Pnpm executable present in E(PATH).
90 """
91
92 EXAMPLES = r"""
93 - name: Install "tailwindcss" Node.js package.
94 community.general.pnpm:
95 name: tailwindcss
96 path: /app/location
97
98 - name: Install "tailwindcss" Node.js package on version 3.3.2
99 community.general.pnpm:
100 name: tailwindcss
101 version: 3.3.2
102 path: /app/location
103
104 - name: Install "tailwindcss" Node.js package globally.
105 community.general.pnpm:
106 name: tailwindcss
107 global: true
108
109 - name: Install "tailwindcss" Node.js package as dev dependency.
110 community.general.pnpm:
111 name: tailwindcss
112 path: /app/location
113 dev: true
114
115 - name: Install "tailwindcss" Node.js package as optional dependency.
116 community.general.pnpm:
117 name: tailwindcss
118 path: /app/location
119 optional: true
120
121 - name: Install "tailwindcss" Node.js package version 0.1.3 as tailwind-1
122 community.general.pnpm:
123 name: tailwindcss
124 alias: tailwind-1
125 version: 0.1.3
126 path: /app/location
127
128 - name: Remove the globally-installed package "tailwindcss".
129 community.general.pnpm:
130 name: tailwindcss
131 global: true
132 state: absent
133
134 - name: Install packages based on package.json.
135 community.general.pnpm:
136 path: /app/location
137
138 - name: Update all packages in package.json to their latest version.
139 community.general.pnpm:
140 path: /app/location
141 state: latest
142 """
143
144 import json
145 import os
146
147 from ansible.module_utils.basic import AnsibleModule
148
149
150 class Pnpm:
151 def __init__(self, module, **kwargs):
152 self.module = module
153 self.name = kwargs["name"]
154 self.alias = kwargs["alias"]
155 self.version = kwargs["version"]
156 self.path = kwargs["path"]
157 self.globally = kwargs["globally"]
158 self.executable = kwargs["executable"]
159 self.ignore_scripts = kwargs["ignore_scripts"]
160 self.no_optional = kwargs["no_optional"]
161 self.production = kwargs["production"]
162 self.dev = kwargs["dev"]
163 self.optional = kwargs["optional"]
164
165 self.alias_name_ver = None
166
167 if self.alias is not None:
168 self.alias_name_ver = f"{self.alias}@npm:"
169
170 if self.name is not None:
171 self.alias_name_ver = (self.alias_name_ver or "") + self.name
172 if self.version is not None:
173 self.alias_name_ver = f"{self.alias_name_ver}@{self.version!s}"
174 else:
175 self.alias_name_ver = f"{self.alias_name_ver}@latest"
176
177 def _exec(self, args, run_in_check_mode=False, check_rc=True):
178 if not self.module.check_mode or (self.module.check_mode and run_in_check_mode):
179 cmd = self.executable + args
180
181 if self.globally:
182 cmd.append("-g")
183
184 if self.ignore_scripts:
185 cmd.append("--ignore-scripts")
186
187 if self.no_optional:
188 cmd.append("--no-optional")
189
190 if self.production:
191 cmd.append("-P")
192
193 if self.dev:
194 cmd.append("-D")
195
196 if self.name and self.optional:
197 cmd.append("-O")
198
199 # If path is specified, cd into that path and run the command.
200 cwd = None
201 if self.path:
202 if not os.path.exists(self.path):
203 os.makedirs(self.path)
204
205 if not os.path.isdir(self.path):
206 self.module.fail_json(msg=f"Path {self.path} is not a directory")
207
208 if not self.alias_name_ver and not os.path.isfile(os.path.join(self.path, "package.json")):
209 self.module.fail_json(msg="package.json does not exist in provided path")
210
211 cwd = self.path
212
213 _rc, out, err = self.module.run_command(cmd, check_rc=check_rc, cwd=cwd)
214 return out, err
215
216 return None, None
217
218 def missing(self):
219 if not os.path.isfile(os.path.join(self.path, "pnpm-lock.yaml")):
220 return True
221
222 cmd = ["list", "--json"]
223
224 if self.name is not None:
225 cmd.append(self.name)
226
227 try:
228 out, err = self._exec(cmd, True, False)
229 if err is not None and err != "":
230 raise Exception(out)
231
232 data = json.loads(out)
233 except Exception as e:
234 self.module.fail_json(msg=f"Failed to parse pnpm output with error {e}")
235
236 if "error" in data:
237 return True
238
239 data = data[0]
240
241 for typedep in [
242 "dependencies",
243 "devDependencies",
244 "optionalDependencies",
245 "unsavedDependencies",
246 ]:
247 if typedep not in data:
248 continue
249
250 for dep, prop in data[typedep].items():
251 if self.alias is not None and self.alias != dep:
252 continue
253
254 name = prop["from"] if self.alias is not None else dep
255 if self.name != name:
256 continue
257
258 if self.version is None or self.version == prop["version"]:
259 return False
260
261 break
262
263 return True
264
265 def install(self):
266 if self.alias_name_ver is not None:
267 return self._exec(["add", self.alias_name_ver])
268 return self._exec(["install"])
269
270 def update(self):
271 return self._exec(["update", "--latest"])
272
273 def uninstall(self):
274 if self.alias is not None:
275 return self._exec(["remove", self.alias])
276 return self._exec(["remove", self.name])
277
278 def list_outdated(self):
279 if not os.path.isfile(os.path.join(self.path, "pnpm-lock.yaml")):
280 return list()
281
282 cmd = ["outdated", "--format", "json"]
283 try:
284 out, err = self._exec(cmd, True, False)
285
286 # BUG: It will not show correct error sometimes, like when it has
287 # plain text output intermingled with a {}
288 if err is not None and err != "":
289 raise Exception(out)
290
291 # HACK: To fix the above bug, the following hack is implemented
292 data_lines = out.splitlines(True)
293
294 out = None
295 for line in data_lines:
296 if len(line) > 0 and line[0] == "{":
297 out = line
298 continue
299
300 if len(line) > 0 and line[0] == "}":
301 out += line
302 break
303
304 if out is not None:
305 out += line
306
307 data = json.loads(out)
308 except Exception as e:
309 self.module.fail_json(msg=f"Failed to parse pnpm output with error {e}")
310
311 return data.keys()
312
313
314 def main():
315 arg_spec = dict(
316 name=dict(),
317 alias=dict(),
318 path=dict(type="path"),
319 version=dict(),
320 executable=dict(type="path"),
321 ignore_scripts=dict(default=False, type="bool"),
322 no_optional=dict(default=False, type="bool"),
323 production=dict(default=False, type="bool"),
324 dev=dict(default=False, type="bool"),
325 optional=dict(default=False, type="bool"),
326 state=dict(default="present", choices=["present", "absent", "latest"]),
327 )
328 arg_spec["global"] = dict(default=False, type="bool")
329 module = AnsibleModule(argument_spec=arg_spec, supports_check_mode=True)
330 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
331
332 name = module.params["name"]
333 alias = module.params["alias"]
334 path = module.params["path"]
335 version = module.params["version"]
336 globally = module.params["global"]
337 ignore_scripts = module.params["ignore_scripts"]
338 no_optional = module.params["no_optional"]
339 production = module.params["production"]
340 dev = module.params["dev"]
341 optional = module.params["optional"]
342 state = module.params["state"]
343
344 if module.params["executable"]:
345 executable = module.params["executable"].split(" ")
346 else:
347 executable = [module.get_bin_path("pnpm", True)]
348
349 if name is None and version is not None:
350 module.fail_json(msg="version is meaningless when name is not provided")
351
352 if name is None and alias is not None:
353 module.fail_json(msg="alias is meaningless when name is not provided")
354
355 if path is None and not globally:
356 module.fail_json(msg="path must be specified when not using global")
357 elif path is not None and globally:
358 module.fail_json(msg="Cannot specify path when doing global installation")
359
360 if globally and (production or dev or optional):
361 module.fail_json(msg="Options production, dev, and optional is meaningless when installing packages globally")
362
363 if name is not None and path is not None and globally:
364 module.fail_json(msg="path should not be mentioned when installing globally")
365
366 if production and dev and optional:
367 module.fail_json(msg="Options production and dev and optional don't go together")
368
369 if production and dev:
370 module.fail_json(msg="Options production and dev don't go together")
371
372 if production and optional:
373 module.fail_json(msg="Options production and optional don't go together")
374
375 if dev and optional:
376 module.fail_json(msg="Options dev and optional don't go together")
377
378 if name is not None and name[0:4] == "http" and version is not None:
379 module.fail_json(msg="Semver not supported on remote url downloads")
380
381 if name is None and optional:
382 module.fail_json(msg="Optional not available when package name not provided, use no_optional instead")
383
384 if state == "absent" and name is None:
385 module.fail_json(msg="Package name is required for uninstalling")
386
387 if globally:
388 _rc, out, _err = module.run_command(executable + ["root", "-g"], check_rc=True)
389 path, _tail = os.path.split(out.strip())
390
391 pnpm = Pnpm(
392 module,
393 name=name,
394 alias=alias,
395 path=path,
396 version=version,
397 globally=globally,
398 executable=executable,
399 ignore_scripts=ignore_scripts,
400 no_optional=no_optional,
401 production=production,
402 dev=dev,
403 optional=optional,
404 )
405
406 changed = False
407 out = ""
408 err = ""
409 if state == "present":
410 if pnpm.missing():
411 changed = True
412 out, err = pnpm.install()
413 elif state == "latest":
414 outdated = pnpm.list_outdated()
415 if name is not None:
416 if pnpm.missing() or name in outdated:
417 changed = True
418 out, err = pnpm.install()
419 elif len(outdated):
420 changed = True
421 out, err = pnpm.update()
422 else: # absent
423 if not pnpm.missing():
424 changed = True
425 out, err = pnpm.uninstall()
426
427 module.exit_json(changed=changed, out=out, err=err)
428
429
430 if __name__ == "__main__":
431 main()