summaryrefslogtreecommitdiffstats
path: root/scripts/lib/recipetool/create_npm.py
diff options
context:
space:
mode:
Diffstat (limited to 'scripts/lib/recipetool/create_npm.py')
-rw-r--r--scripts/lib/recipetool/create_npm.py299
1 files changed, 0 insertions, 299 deletions
diff --git a/scripts/lib/recipetool/create_npm.py b/scripts/lib/recipetool/create_npm.py
deleted file mode 100644
index 3363a0e7ee..0000000000
--- a/scripts/lib/recipetool/create_npm.py
+++ /dev/null
@@ -1,299 +0,0 @@
1# Copyright (C) 2016 Intel Corporation
2# Copyright (C) 2020 Savoir-Faire Linux
3#
4# SPDX-License-Identifier: GPL-2.0-only
5#
6"""Recipe creation tool - npm module support plugin"""
7
8import json
9import logging
10import os
11import re
12import sys
13import tempfile
14import bb
15from bb.fetch2.npm import NpmEnvironment
16from bb.fetch2.npm import npm_package
17from bb.fetch2.npmsw import foreach_dependencies
18from recipetool.create import RecipeHandler
19from recipetool.create import match_licenses, find_license_files, generate_common_licenses_chksums
20from recipetool.create import split_pkg_licenses
21logger = logging.getLogger('recipetool')
22
23TINFOIL = None
24
25def tinfoil_init(instance):
26 """Initialize tinfoil"""
27 global TINFOIL
28 TINFOIL = instance
29
30class NpmRecipeHandler(RecipeHandler):
31 """Class to handle the npm recipe creation"""
32
33 @staticmethod
34 def _get_registry(lines):
35 """Get the registry value from the 'npm://registry' url"""
36 registry = None
37
38 def _handle_registry(varname, origvalue, op, newlines):
39 nonlocal registry
40 if origvalue.startswith("npm://"):
41 registry = re.sub(r"^npm://", "http://", origvalue.split(";")[0])
42 return origvalue, None, 0, True
43
44 bb.utils.edit_metadata(lines, ["SRC_URI"], _handle_registry)
45
46 return registry
47
48 @staticmethod
49 def _ensure_npm():
50 """Check if the 'npm' command is available in the recipes"""
51 if not TINFOIL.recipes_parsed:
52 TINFOIL.parse_recipes()
53
54 try:
55 d = TINFOIL.parse_recipe("nodejs-native")
56 except bb.providers.NoProvider:
57 bb.error("Nothing provides 'nodejs-native' which is required for the build")
58 bb.note("You will likely need to add a layer that provides nodejs")
59 sys.exit(14)
60
61 bindir = d.getVar("STAGING_BINDIR_NATIVE")
62 npmpath = os.path.join(bindir, "npm")
63
64 if not os.path.exists(npmpath):
65 TINFOIL.build_targets("nodejs-native", "addto_recipe_sysroot")
66
67 if not os.path.exists(npmpath):
68 bb.error("Failed to add 'npm' to sysroot")
69 sys.exit(14)
70
71 return bindir
72
73 @staticmethod
74 def _npm_global_configs(dev):
75 """Get the npm global configuration"""
76 configs = []
77
78 if dev:
79 configs.append(("also", "development"))
80 else:
81 configs.append(("only", "production"))
82
83 configs.append(("save", "false"))
84 configs.append(("package-lock", "false"))
85 configs.append(("shrinkwrap", "false"))
86 return configs
87
88 def _run_npm_install(self, d, srctree, registry, dev):
89 """Run the 'npm install' command without building the addons"""
90 configs = self._npm_global_configs(dev)
91 configs.append(("ignore-scripts", "true"))
92
93 if registry:
94 configs.append(("registry", registry))
95
96 bb.utils.remove(os.path.join(srctree, "node_modules"), recurse=True)
97
98 env = NpmEnvironment(d, configs=configs)
99 env.run("npm install", workdir=srctree)
100
101 def _generate_shrinkwrap(self, d, srctree, dev):
102 """Check and generate the 'npm-shrinkwrap.json' file if needed"""
103 configs = self._npm_global_configs(dev)
104
105 env = NpmEnvironment(d, configs=configs)
106 env.run("npm shrinkwrap", workdir=srctree)
107
108 return os.path.join(srctree, "npm-shrinkwrap.json")
109
110 def _handle_licenses(self, srctree, shrinkwrap_file, dev):
111 """Return the extra license files and the list of packages"""
112 licfiles = []
113 packages = {}
114 # Licenses from package.json will point to COMMON_LICENSE_DIR so we need
115 # to associate them explicitely to packages for split_pkg_licenses()
116 fallback_licenses = dict()
117
118 def _find_package_licenses(destdir):
119 """Either find license files, or use package.json metadata"""
120 def _get_licenses_from_package_json(package_json):
121 with open(os.path.join(srctree, package_json), "r") as f:
122 data = json.load(f)
123 if "license" in data:
124 licenses = data["license"].split(" ")
125 licenses = [license.strip("()") for license in licenses if license != "OR" and license != "AND"]
126 return [], licenses
127 else:
128 return [package_json], None
129
130 basedir = os.path.join(srctree, destdir)
131 licfiles = find_license_files(basedir)
132 if len(licfiles) > 0:
133 return licfiles, None
134 else:
135 # A license wasn't found in the package directory, so we'll use the package.json metadata
136 pkg_json = os.path.join(basedir, "package.json")
137 return _get_licenses_from_package_json(pkg_json)
138
139 def _get_package_licenses(destdir, package):
140 (package_licfiles, package_licenses) = _find_package_licenses(destdir)
141 if package_licfiles:
142 licfiles.extend(package_licfiles)
143 else:
144 fallback_licenses[package] = package_licenses
145
146 # Handle the dependencies
147 def _handle_dependency(name, params, destdir):
148 deptree = destdir.split('node_modules/')
149 suffix = "-".join([npm_package(dep) for dep in deptree])
150 packages["${PN}" + suffix] = destdir
151 _get_package_licenses(destdir, "${PN}" + suffix)
152
153 with open(shrinkwrap_file, "r") as f:
154 shrinkwrap = json.load(f)
155 foreach_dependencies(shrinkwrap, _handle_dependency, dev)
156
157 # Handle the parent package
158 packages["${PN}"] = ""
159 _get_package_licenses(srctree, "${PN}")
160
161 return licfiles, packages, fallback_licenses
162
163 # Handle the peer dependencies
164 def _handle_peer_dependency(self, shrinkwrap_file):
165 """Check if package has peer dependencies and show warning if it is the case"""
166 with open(shrinkwrap_file, "r") as f:
167 shrinkwrap = json.load(f)
168
169 packages = shrinkwrap.get("packages", {})
170 peer_deps = packages.get("", {}).get("peerDependencies", {})
171
172 for peer_dep in peer_deps:
173 peer_dep_yocto_name = npm_package(peer_dep)
174 bb.warn(peer_dep + " is a peer dependencie of the actual package. " +
175 "Please add this peer dependencie to the RDEPENDS variable as %s and generate its recipe with devtool"
176 % peer_dep_yocto_name)
177
178
179
180 def process(self, srctree, classes, lines_before, lines_after, handled, extravalues):
181 """Handle the npm recipe creation"""
182
183 if "buildsystem" in handled:
184 return False
185
186 files = RecipeHandler.checkfiles(srctree, ["package.json"])
187
188 if not files:
189 return False
190
191 with open(files[0], "r") as f:
192 data = json.load(f)
193
194 if "name" not in data or "version" not in data:
195 return False
196
197 extravalues["PN"] = npm_package(data["name"])
198 extravalues["PV"] = data["version"]
199
200 if "description" in data:
201 extravalues["SUMMARY"] = data["description"]
202
203 if "homepage" in data:
204 extravalues["HOMEPAGE"] = data["homepage"]
205
206 dev = bb.utils.to_boolean(str(extravalues.get("NPM_INSTALL_DEV", "0")), False)
207 registry = self._get_registry(lines_before)
208
209 bb.note("Checking if npm is available ...")
210 # The native npm is used here (and not the host one) to ensure that the
211 # npm version is high enough to ensure an efficient dependency tree
212 # resolution and avoid issue with the shrinkwrap file format.
213 # Moreover the native npm is mandatory for the build.
214 bindir = self._ensure_npm()
215
216 d = bb.data.createCopy(TINFOIL.config_data)
217 d.prependVar("PATH", bindir + ":")
218 d.setVar("S", srctree)
219
220 bb.note("Generating shrinkwrap file ...")
221 # To generate the shrinkwrap file the dependencies have to be installed
222 # first. During the generation process some files may be updated /
223 # deleted. By default devtool tracks the diffs in the srctree and raises
224 # errors when finishing the recipe if some diffs are found.
225 git_exclude_file = os.path.join(srctree, ".git", "info", "exclude")
226 if os.path.exists(git_exclude_file):
227 with open(git_exclude_file, "r+") as f:
228 lines = f.readlines()
229 for line in ["/node_modules/", "/npm-shrinkwrap.json"]:
230 if line not in lines:
231 f.write(line + "\n")
232
233 lock_file = os.path.join(srctree, "package-lock.json")
234 lock_copy = lock_file + ".copy"
235 if os.path.exists(lock_file):
236 bb.utils.copyfile(lock_file, lock_copy)
237
238 self._run_npm_install(d, srctree, registry, dev)
239 shrinkwrap_file = self._generate_shrinkwrap(d, srctree, dev)
240
241 with open(shrinkwrap_file, "r") as f:
242 shrinkwrap = json.load(f)
243
244 if os.path.exists(lock_copy):
245 bb.utils.movefile(lock_copy, lock_file)
246
247 # Add the shrinkwrap file as 'extrafiles'
248 shrinkwrap_copy = shrinkwrap_file + ".copy"
249 bb.utils.copyfile(shrinkwrap_file, shrinkwrap_copy)
250 extravalues.setdefault("extrafiles", {})
251 extravalues["extrafiles"]["npm-shrinkwrap.json"] = shrinkwrap_copy
252
253 url_local = "npmsw://%s" % shrinkwrap_file
254 url_recipe= "npmsw://${THISDIR}/${BPN}/npm-shrinkwrap.json"
255
256 if dev:
257 url_local += ";dev=1"
258 url_recipe += ";dev=1"
259
260 # Add the npmsw url in the SRC_URI of the generated recipe
261 def _handle_srcuri(varname, origvalue, op, newlines):
262 """Update the version value and add the 'npmsw://' url"""
263 value = origvalue.replace("version=" + data["version"], "version=${PV}")
264 value = value.replace("version=latest", "version=${PV}")
265 values = [line.strip() for line in value.strip('\n').splitlines()]
266 if "dependencies" in shrinkwrap.get("packages", {}).get("", {}):
267 values.append(url_recipe)
268 return values, None, 4, False
269
270 (_, newlines) = bb.utils.edit_metadata(lines_before, ["SRC_URI"], _handle_srcuri)
271 lines_before[:] = [line.rstrip('\n') for line in newlines]
272
273 # In order to generate correct licence checksums in the recipe the
274 # dependencies have to be fetched again using the npmsw url
275 bb.note("Fetching npm dependencies ...")
276 bb.utils.remove(os.path.join(srctree, "node_modules"), recurse=True)
277 fetcher = bb.fetch2.Fetch([url_local], d)
278 fetcher.download()
279 fetcher.unpack(srctree)
280
281 bb.note("Handling licences ...")
282 (licfiles, packages, fallback_licenses) = self._handle_licenses(srctree, shrinkwrap_file, dev)
283 licvalues = match_licenses(licfiles, srctree, d)
284 split_pkg_licenses(licvalues, packages, lines_after, fallback_licenses)
285 fallback_licenses_flat = [license for sublist in fallback_licenses.values() for license in sublist]
286 extravalues["LIC_FILES_CHKSUM"] = generate_common_licenses_chksums(fallback_licenses_flat, d)
287 extravalues["LICENSE"] = fallback_licenses_flat
288
289 classes.append("npm")
290 handled.append("buildsystem")
291
292 # Check if package has peer dependencies and inform the user
293 self._handle_peer_dependency(shrinkwrap_file)
294
295 return True
296
297def register_recipe_handlers(handlers):
298 """Register the npm handler"""
299 handlers.append((NpmRecipeHandler(), 60))