blob: 426a139653d4a346df98a17435841c014fb72cb7 [file] [log] [blame]
Andrew Geissler82c905d2020-04-13 13:39:40 -05001# Copyright (C) 2020 Savoir-Faire Linux
2#
3# SPDX-License-Identifier: GPL-2.0-only
4#
5"""
6BitBake 'Fetch' npm shrinkwrap implementation
7
8npm fetcher support the SRC_URI with format of:
9SRC_URI = "npmsw://some.registry.url;OptionA=xxx;OptionB=xxx;..."
10
11Supported SRC_URI options are:
12
13- dev
14 Set to 1 to also install devDependencies.
15
16- destsuffix
17 Specifies the directory to use to unpack the dependencies (default: ${S}).
18"""
19
20import json
21import os
22import re
23import bb
24from bb.fetch2 import Fetch
25from bb.fetch2 import FetchMethod
26from bb.fetch2 import ParameterError
Andrew Geisslereff27472021-10-29 15:35:00 -050027from bb.fetch2 import runfetchcmd
Andrew Geissler82c905d2020-04-13 13:39:40 -050028from bb.fetch2 import URI
29from bb.fetch2.npm import npm_integrity
30from bb.fetch2.npm import npm_localfile
31from bb.fetch2.npm import npm_unpack
32from bb.utils import is_semver
Andrew Geisslereff27472021-10-29 15:35:00 -050033from bb.utils import lockfile
34from bb.utils import unlockfile
Andrew Geissler82c905d2020-04-13 13:39:40 -050035
36def foreach_dependencies(shrinkwrap, callback=None, dev=False):
37 """
38 Run a callback for each dependencies of a shrinkwrap file.
39 The callback is using the format:
40 callback(name, params, deptree)
41 with:
42 name = the package name (string)
43 params = the package parameters (dictionary)
44 deptree = the package dependency tree (array of strings)
45 """
46 def _walk_deps(deps, deptree):
47 for name in deps:
48 subtree = [*deptree, name]
49 _walk_deps(deps[name].get("dependencies", {}), subtree)
50 if callback is not None:
51 if deps[name].get("dev", False) and not dev:
52 continue
53 elif deps[name].get("bundled", False):
54 continue
55 callback(name, deps[name], subtree)
56
57 _walk_deps(shrinkwrap.get("dependencies", {}), [])
58
59class NpmShrinkWrap(FetchMethod):
60 """Class to fetch all package from a shrinkwrap file"""
61
62 def supports(self, ud, d):
63 """Check if a given url can be fetched with npmsw"""
64 return ud.type in ["npmsw"]
65
66 def urldata_init(self, ud, d):
67 """Init npmsw specific variables within url data"""
68
69 # Get the 'shrinkwrap' parameter
70 ud.shrinkwrap_file = re.sub(r"^npmsw://", "", ud.url.split(";")[0])
71
72 # Get the 'dev' parameter
73 ud.dev = bb.utils.to_boolean(ud.parm.get("dev"), False)
74
75 # Resolve the dependencies
76 ud.deps = []
77
78 def _resolve_dependency(name, params, deptree):
79 url = None
80 localpath = None
81 extrapaths = []
82 destsubdirs = [os.path.join("node_modules", dep) for dep in deptree]
83 destsuffix = os.path.join(*destsubdirs)
Andrew Geisslereff27472021-10-29 15:35:00 -050084 unpack = True
Andrew Geissler82c905d2020-04-13 13:39:40 -050085
86 integrity = params.get("integrity", None)
87 resolved = params.get("resolved", None)
88 version = params.get("version", None)
89
90 # Handle registry sources
91 if is_semver(version) and resolved and integrity:
92 localfile = npm_localfile(name, version)
93
94 uri = URI(resolved)
95 uri.params["downloadfilename"] = localfile
96
97 checksum_name, checksum_expected = npm_integrity(integrity)
98 uri.params[checksum_name] = checksum_expected
99
100 url = str(uri)
101
102 localpath = os.path.join(d.getVar("DL_DIR"), localfile)
103
104 # Create a resolve file to mimic the npm fetcher and allow
105 # re-usability of the downloaded file.
106 resolvefile = localpath + ".resolved"
107
108 bb.utils.mkdirhier(os.path.dirname(resolvefile))
109 with open(resolvefile, "w") as f:
110 f.write(url)
111
112 extrapaths.append(resolvefile)
113
114 # Handle http tarball sources
115 elif version.startswith("http") and integrity:
116 localfile = os.path.join("npm2", os.path.basename(version))
117
118 uri = URI(version)
119 uri.params["downloadfilename"] = localfile
120
121 checksum_name, checksum_expected = npm_integrity(integrity)
122 uri.params[checksum_name] = checksum_expected
123
124 url = str(uri)
125
126 localpath = os.path.join(d.getVar("DL_DIR"), localfile)
127
128 # Handle git sources
129 elif version.startswith("git"):
130 regex = re.compile(r"""
131 ^
132 git\+
133 (?P<protocol>[a-z]+)
134 ://
135 (?P<url>[^#]+)
136 \#
137 (?P<rev>[0-9a-f]+)
138 $
139 """, re.VERBOSE)
140
141 match = regex.match(version)
142
143 if not match:
144 raise ParameterError("Invalid git url: %s" % version, ud.url)
145
146 groups = match.groupdict()
147
148 uri = URI("git://" + str(groups["url"]))
149 uri.params["protocol"] = str(groups["protocol"])
150 uri.params["rev"] = str(groups["rev"])
151 uri.params["destsuffix"] = destsuffix
152
153 url = str(uri)
154
Andrew Geisslereff27472021-10-29 15:35:00 -0500155 # Handle local tarball and link sources
156 elif version.startswith("file"):
157 localpath = version[5:]
158 if not version.endswith(".tgz"):
159 unpack = False
160
Andrew Geissler82c905d2020-04-13 13:39:40 -0500161 else:
162 raise ParameterError("Unsupported dependency: %s" % name, ud.url)
163
164 ud.deps.append({
165 "url": url,
166 "localpath": localpath,
167 "extrapaths": extrapaths,
168 "destsuffix": destsuffix,
Andrew Geisslereff27472021-10-29 15:35:00 -0500169 "unpack": unpack,
Andrew Geissler82c905d2020-04-13 13:39:40 -0500170 })
171
172 try:
173 with open(ud.shrinkwrap_file, "r") as f:
174 shrinkwrap = json.load(f)
175 except Exception as e:
176 raise ParameterError("Invalid shrinkwrap file: %s" % str(e), ud.url)
177
178 foreach_dependencies(shrinkwrap, _resolve_dependency, ud.dev)
179
180 # Avoid conflicts between the environment data and:
181 # - the proxy url revision
182 # - the proxy url checksum
183 data = bb.data.createCopy(d)
184 data.delVar("SRCREV")
185 data.delVarFlags("SRC_URI")
186
187 # This fetcher resolves multiple URIs from a shrinkwrap file and then
188 # forwards it to a proxy fetcher. The management of the donestamp file,
189 # the lockfile and the checksums are forwarded to the proxy fetcher.
Andrew Geisslereff27472021-10-29 15:35:00 -0500190 ud.proxy = Fetch([dep["url"] for dep in ud.deps if dep["url"]], data)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500191 ud.needdonestamp = False
192
193 @staticmethod
194 def _foreach_proxy_method(ud, handle):
195 returns = []
196 for proxy_url in ud.proxy.urls:
197 proxy_ud = ud.proxy.ud[proxy_url]
198 proxy_d = ud.proxy.d
199 proxy_ud.setup_localpath(proxy_d)
Andrew Geisslereff27472021-10-29 15:35:00 -0500200 lf = lockfile(proxy_ud.lockfile)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500201 returns.append(handle(proxy_ud.method, proxy_ud, proxy_d))
Andrew Geisslereff27472021-10-29 15:35:00 -0500202 unlockfile(lf)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500203 return returns
204
205 def verify_donestamp(self, ud, d):
206 """Verify the donestamp file"""
207 def _handle(m, ud, d):
208 return m.verify_donestamp(ud, d)
209 return all(self._foreach_proxy_method(ud, _handle))
210
211 def update_donestamp(self, ud, d):
212 """Update the donestamp file"""
213 def _handle(m, ud, d):
214 m.update_donestamp(ud, d)
215 self._foreach_proxy_method(ud, _handle)
216
217 def need_update(self, ud, d):
218 """Force a fetch, even if localpath exists ?"""
219 def _handle(m, ud, d):
220 return m.need_update(ud, d)
221 return all(self._foreach_proxy_method(ud, _handle))
222
223 def try_mirrors(self, fetch, ud, d, mirrors):
224 """Try to use a mirror"""
225 def _handle(m, ud, d):
226 return m.try_mirrors(fetch, ud, d, mirrors)
227 return all(self._foreach_proxy_method(ud, _handle))
228
229 def download(self, ud, d):
230 """Fetch url"""
231 ud.proxy.download()
232
233 def unpack(self, ud, rootdir, d):
234 """Unpack the downloaded dependencies"""
235 destdir = d.getVar("S")
236 destsuffix = ud.parm.get("destsuffix")
237 if destsuffix:
238 destdir = os.path.join(rootdir, destsuffix)
239
240 bb.utils.mkdirhier(destdir)
241 bb.utils.copyfile(ud.shrinkwrap_file,
242 os.path.join(destdir, "npm-shrinkwrap.json"))
243
244 auto = [dep["url"] for dep in ud.deps if not dep["localpath"]]
245 manual = [dep for dep in ud.deps if dep["localpath"]]
246
247 if auto:
248 ud.proxy.unpack(destdir, auto)
249
250 for dep in manual:
251 depdestdir = os.path.join(destdir, dep["destsuffix"])
Andrew Geisslereff27472021-10-29 15:35:00 -0500252 if dep["url"]:
253 npm_unpack(dep["localpath"], depdestdir, d)
254 else:
255 depsrcdir= os.path.join(destdir, dep["localpath"])
256 if dep["unpack"]:
257 npm_unpack(depsrcdir, depdestdir, d)
258 else:
259 bb.utils.mkdirhier(depdestdir)
260 cmd = 'cp -fpPRH "%s/." .' % (depsrcdir)
261 runfetchcmd(cmd, d, workdir=depdestdir)
Andrew Geissler82c905d2020-04-13 13:39:40 -0500262
263 def clean(self, ud, d):
264 """Clean any existing full or partial download"""
265 ud.proxy.clean()
266
267 # Clean extra files
268 for dep in ud.deps:
269 for path in dep["extrapaths"]:
270 bb.utils.remove(path)
271
272 def done(self, ud, d):
273 """Is the download done ?"""
274 def _handle(m, ud, d):
275 return m.done(ud, d)
276 return all(self._foreach_proxy_method(ud, _handle))