Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # (c) 2017 David Gunter <[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
9 from __future__ import annotations
10
11 DOCUMENTATION = r"""
12 module: yarn
13 short_description: Manage Node.js packages with Yarn
14 description:
15 - Manage Node.js packages with the Yarn package manager U(https://yarnpkg.com/).
16 - Note that at the moment, this module B(only works with Yarn Classic).
17 author:
18 - "David Gunter (@verkaufer)"
19 - "Chris Hoffman (@chrishoffman), creator of NPM Ansible module)"
20 extends_documentation_fragment:
21 - community.general._attributes
22 attributes:
23 check_mode:
24 support: full
25 diff_mode:
26 support: none
27 options:
28 name:
29 type: str
30 description:
31 - The name of a Node.js library to install.
32 - If omitted all packages in package.json are installed.
33 - To globally install from local Node.js library. Prepend C(file:) to the path of the Node.js library.
34 path:
35 type: path
36 description:
37 - The base path where Node.js installs libraries.
38 - This is where the C(node_modules) folder lives.
39 version:
40 type: str
41 description:
42 - The version of the library to be installed.
43 - Must be in semver format. If "latest" is desired, use O(state) arg instead.
44 global:
45 description:
46 - Install the Node.js library globally.
47 default: false
48 type: bool
49 executable:
50 type: path
51 description:
52 - The executable location for yarn.
53 ignore_scripts:
54 description:
55 - Use the C(--ignore-scripts) flag when installing.
56 type: bool
57 default: false
58 production:
59 description:
60 - Install dependencies in production mode.
61 - C(yarn) ignores any dependencies under devDependencies in C(package.json).
62 type: bool
63 default: false
64 registry:
65 type: str
66 description:
67 - The registry to install modules from.
68 state:
69 type: str
70 description:
71 - Installation state of the named Node.js library.
72 - If V(absent) is selected, a O(name) option must be provided.
73 default: present
74 choices: ["present", "absent", "latest"]
75 requirements:
76 - Yarn Classic installed in bin path (typically C(/usr/local/bin))
77 """
78
79 EXAMPLES = r"""
80 - name: Install "imagemin" Node.js package.
81 community.general.yarn:
82 name: imagemin
83 path: /app/location
84
85 - name: Install "imagemin" Node.js package on version 5.3.1
86 community.general.yarn:
87 name: imagemin
88 version: '5.3.1'
89 path: /app/location
90
91 - name: Install "imagemin" Node.js package globally.
92 community.general.yarn:
93 name: imagemin
94 global: true
95
96 - name: Remove the globally-installed package "imagemin".
97 community.general.yarn:
98 name: imagemin
99 global: true
100 state: absent
101
102 - name: Install "imagemin" Node.js package from custom registry.
103 community.general.yarn:
104 name: imagemin
105 registry: 'http://registry.mysite.com'
106
107 - name: Install packages based on package.json.
108 community.general.yarn:
109 path: /app/location
110
111 - name: Update all packages in package.json to their latest version.
112 community.general.yarn:
113 path: /app/location
114 state: latest
115 """
116
117 RETURN = r"""
118 out:
119 description: Output generated from Yarn.
120 returned: always
121 type: str
122 sample: "yarn add v0.16.1[1/4] Resolving packages...[2/4] Fetching packages...[3/4] Linking dependencies...[4/4] Building
123 fresh packages...success Saved lockfile.success Saved 1 new [email protected] Done in 0.59s."
124 """
125
126 import json
127 import os
128
129 from ansible.module_utils.basic import AnsibleModule
130
131
132 class Yarn:
133 def __init__(self, module, **kwargs):
134 self.module = module
135 self.globally = kwargs["globally"]
136 self.name = kwargs["name"]
137 self.version = kwargs["version"]
138 self.path = kwargs["path"]
139 self.registry = kwargs["registry"]
140 self.production = kwargs["production"]
141 self.ignore_scripts = kwargs["ignore_scripts"]
142 self.executable = kwargs["executable"]
143
144 # Specify a version of package if version arg passed in
145 self.name_version = None
146
147 if kwargs["version"] and self.name is not None:
148 self.name_version = f"{self.name}@{self.version!s}"
149 elif self.name is not None:
150 self.name_version = self.name
151
152 def _exec(self, args, run_in_check_mode=False, check_rc=True, unsupported_with_global=False):
153 if not self.module.check_mode or (self.module.check_mode and run_in_check_mode):
154 with_global_arg = self.globally and not unsupported_with_global
155
156 if with_global_arg:
157 # Yarn global arg is inserted before the command (e.g. `yarn global {some-command}`)
158 args.insert(0, "global")
159
160 cmd = self.executable + args
161
162 if self.production:
163 cmd.append("--production")
164 if self.ignore_scripts:
165 cmd.append("--ignore-scripts")
166 if self.registry:
167 cmd.append("--registry")
168 cmd.append(self.registry)
169
170 # If path is specified, cd into that path and run the command.
171 cwd = None
172 if self.path and not with_global_arg:
173 if not os.path.exists(self.path):
174 # Module will make directory if not exists.
175 os.makedirs(self.path)
176 if not os.path.isdir(self.path):
177 self.module.fail_json(msg=f"Path provided {self.path} is not a directory")
178 cwd = self.path
179
180 if not os.path.isfile(os.path.join(self.path, "package.json")):
181 self.module.fail_json(msg="Package.json does not exist in provided path.")
182
183 rc, out, err = self.module.run_command(cmd, check_rc=check_rc, cwd=cwd)
184 return out, err
185
186 return None, None
187
188 def _process_yarn_error(self, err):
189 try:
190 # We need to filter for errors, since Yarn warnings are included in stderr.
191 # Non-JSON lines (e.g. Node.js runtime warnings) are surfaced via module.warn()
192 # rather than treated as errors, since their meaning is unknown.
193 for line in err.splitlines():
194 if not line.startswith("{"):
195 self.module.warn(f"yarn stderr: {line}")
196 continue
197 if json.loads(line)["type"] == "error":
198 self.module.fail_json(msg=err)
199 except Exception:
200 self.module.fail_json(msg=f"Unexpected stderr output from Yarn: {err}", stderr=err)
201
202 def list(self):
203 cmd = ["list", "--depth=0", "--json"]
204
205 installed = list()
206 missing = list()
207
208 if not os.path.isfile(os.path.join(self.path, "yarn.lock")):
209 missing.append(self.name)
210 return installed, missing
211
212 # `yarn global list` should be treated as "unsupported with global" even though it exists,
213 # because it only only lists binaries, but `yarn global add` can install libraries too.
214 result, error = self._exec(cmd, run_in_check_mode=True, check_rc=False, unsupported_with_global=True)
215
216 self._process_yarn_error(error)
217
218 for json_line in result.strip().split("\n"):
219 data = json.loads(json_line)
220 if data["type"] == "tree":
221 dependencies = data["data"]["trees"]
222
223 for dep in dependencies:
224 name, version = dep["name"].rsplit("@", 1)
225 installed.append(name)
226
227 if self.name not in installed:
228 missing.append(self.name)
229
230 return installed, missing
231
232 def install(self):
233 if self.name_version:
234 # Yarn has a separate command for installing packages by name...
235 return self._exec(["add", self.name_version])
236 # And one for installing all packages in package.json
237 return self._exec(["install", "--non-interactive"])
238
239 def update(self):
240 return self._exec(["upgrade", "--latest"])
241
242 def uninstall(self):
243 return self._exec(["remove", self.name])
244
245 def list_outdated(self):
246 outdated = list()
247
248 if not os.path.isfile(os.path.join(self.path, "yarn.lock")):
249 return outdated
250
251 cmd_result, err = self._exec(["outdated", "--json"], True, False, unsupported_with_global=True)
252
253 # the package.json in the global dir is missing a license field, so warnings are expected on stderr
254 self._process_yarn_error(err)
255
256 if not cmd_result:
257 return outdated
258
259 outdated_packages_data = cmd_result.splitlines()[1]
260
261 data = json.loads(outdated_packages_data)
262
263 try:
264 outdated_dependencies = data["data"]["body"]
265 except KeyError:
266 return outdated
267
268 for dep in outdated_dependencies:
269 # Outdated dependencies returned as a list of lists, where
270 # item at index 0 is the name of the dependency
271 outdated.append(dep[0])
272 return outdated
273
274
275 def main():
276 arg_spec = dict(
277 name=dict(),
278 path=dict(type="path"),
279 version=dict(),
280 production=dict(default=False, type="bool"),
281 executable=dict(type="path"),
282 registry=dict(),
283 state=dict(default="present", choices=["present", "absent", "latest"]),
284 ignore_scripts=dict(default=False, type="bool"),
285 )
286 arg_spec["global"] = dict(default=False, type="bool")
287 module = AnsibleModule(argument_spec=arg_spec, supports_check_mode=True)
288 module.run_command_environ_update = {"LANGUAGE": "C", "LC_ALL": "C"}
289
290 name = module.params["name"]
291 path = module.params["path"]
292 version = module.params["version"]
293 globally = module.params["global"]
294 production = module.params["production"]
295 registry = module.params["registry"]
296 state = module.params["state"]
297 ignore_scripts = module.params["ignore_scripts"]
298
299 # When installing globally, users should not be able to define a path for installation.
300 # Require a path if global is False, though!
301 if path is None and globally is False:
302 module.fail_json(msg="Path must be specified when not using global arg")
303 elif path and globally is True:
304 module.fail_json(msg="Cannot specify path if doing global installation")
305
306 if state == "absent" and not name:
307 module.fail_json(msg="Package must be explicitly named when uninstalling.")
308 if state == "latest":
309 version = "latest"
310
311 if module.params["executable"]:
312 executable = module.params["executable"].split(" ")
313 else:
314 executable = [module.get_bin_path("yarn", True)]
315
316 # When installing globally, use the defined path for global node_modules
317 if globally:
318 _rc, out, _err = module.run_command(executable + ["global", "dir"], check_rc=True)
319 path = out.strip()
320
321 yarn = Yarn(
322 module,
323 name=name,
324 path=path,
325 version=version,
326 globally=globally,
327 production=production,
328 executable=executable,
329 registry=registry,
330 ignore_scripts=ignore_scripts,
331 )
332
333 changed = False
334 out = ""
335 err = ""
336 if state == "present":
337 if not name:
338 changed = True
339 out, err = yarn.install()
340 else:
341 installed, missing = yarn.list()
342 if len(missing):
343 changed = True
344 out, err = yarn.install()
345
346 elif state == "latest":
347 if not name:
348 changed = True
349 out, err = yarn.install()
350 else:
351 installed, missing = yarn.list()
352 outdated = yarn.list_outdated()
353 if len(missing):
354 changed = True
355 out, err = yarn.install()
356 if len(outdated):
357 changed = True
358 out, err = yarn.update()
359 else:
360 # state == absent
361 installed, missing = yarn.list()
362 if name in installed:
363 changed = True
364 out, err = yarn.uninstall()
365
366 module.exit_json(changed=changed, out=out, err=err)
367
368
369 if __name__ == "__main__":
370 main()