Debian Codegraph @

thirdparty/folly/build/fbcode_builder/getdeps/cargo.py

raw
1 #!/usr/bin/env python3
2 # Copyright (c) Meta Platforms, Inc. and affiliates.
3 #
4 # This source code is licensed under the MIT license found in the
5 # LICENSE file in the root directory of this source tree.
6
7 import os
8 import re
9 import shutil
10 import typing
11
12 from .builder import BuilderBase
13
14 if typing.TYPE_CHECKING:
15 from .buildopts import BuildOptions
16
17
18 class CargoBuilder(BuilderBase):
19 def __init__(
20 self,
21 build_opts: "BuildOptions",
22 ctx,
23 manifest,
24 src_dir,
25 build_dir,
26 inst_dir,
27 build_doc,
28 workspace_dir,
29 manifests_to_build,
30 loader,
31 cargo_config_file,
32 ) -> None:
33 super(CargoBuilder, self).__init__(
34 build_opts, ctx, manifest, src_dir, build_dir, inst_dir
35 )
36 self.build_doc = build_doc
37 self.ws_dir = workspace_dir
38 self.manifests_to_build = manifests_to_build and manifests_to_build.split(",")
39 self.loader = loader
40 self.cargo_config_file_subdir = cargo_config_file
41
42 def run_cargo(self, install_dirs, operation, args=None) -> None:
43 args = args or []
44 env = self._compute_env(install_dirs)
45 # Enable using nightly features with stable compiler
46 env["RUSTC_BOOTSTRAP"] = "1"
47 env["LIBZ_SYS_STATIC"] = "1"
48 cmd = [
49 "cargo",
50 operation,
51 "--workspace",
52 "-j%s" % self.num_jobs,
53 ] + args
54 self._run_cmd(cmd, cwd=self.workspace_dir(), env=env)
55
56 def build_source_dir(self):
57 return os.path.join(self.build_dir, "source")
58
59 def workspace_dir(self):
60 return os.path.join(self.build_source_dir(), self.ws_dir or "")
61
62 def manifest_dir(self, manifest):
63 return os.path.join(self.build_source_dir(), manifest)
64
65 def recreate_dir(self, src, dst) -> None:
66 if os.path.isdir(dst):
67 if os.path.islink(dst):
68 os.remove(dst)
69 else:
70 shutil.rmtree(dst)
71 shutil.copytree(src, dst)
72
73 def cargo_config_file(self):
74 build_source_dir = self.build_dir
75 if self.cargo_config_file_subdir:
76 return os.path.join(build_source_dir, self.cargo_config_file_subdir)
77 else:
78 return os.path.join(build_source_dir, ".cargo", "config")
79
80 def _create_cargo_config(self):
81 cargo_config_file = self.cargo_config_file()
82 cargo_config_dir = os.path.dirname(cargo_config_file)
83 if not os.path.isdir(cargo_config_dir):
84 os.mkdir(cargo_config_dir)
85
86 dep_to_git = self._resolve_dep_to_git()
87
88 if os.path.isfile(cargo_config_file):
89 with open(cargo_config_file, "r") as f:
90 print(f"Reading {cargo_config_file}")
91 cargo_content = f.read()
92 else:
93 cargo_content = ""
94
95 new_content = cargo_content
96 if "# Generated by getdeps.py" not in cargo_content:
97 new_content += """\
98 # Generated by getdeps.py
99 [build]
100 target-dir = '''{}'''
101
102 [profile.dev]
103 debug = false
104 incremental = false
105 """.format(
106 self.build_dir.replace("\\", "\\\\")
107 )
108
109 # Point to vendored sources from getdeps manifests
110 for _dep, git_conf in dep_to_git.items():
111 if "cargo_vendored_sources" in git_conf:
112 vendored_dir = git_conf["cargo_vendored_sources"].replace("\\", "\\\\")
113 override = (
114 f'[source."{git_conf["repo_url"]}"]\ndirectory = "{vendored_dir}"\n'
115 )
116 if override not in cargo_content:
117 new_content += override
118
119 if new_content != cargo_content:
120 with open(cargo_config_file, "w") as f:
121 print(
122 f"Writing cargo config for {self.manifest.name} to {cargo_config_file}"
123 )
124 f.write(new_content)
125
126 if self.build_opts.fbsource_dir:
127 # Point to vendored crates.io if possible
128 try:
129 from .facebook.rust import vendored_crates
130
131 vendored_crates(self.build_opts.fbsource_dir, cargo_config_file)
132 except ImportError:
133 # This FB internal module isn't shippped to github,
134 # so just rely on cargo downloading crates on it's own
135 pass
136
137 return dep_to_git
138
139 def _prepare(self, install_dirs, reconfigure) -> None:
140 build_source_dir = self.build_source_dir()
141 self.recreate_dir(self.src_dir, build_source_dir)
142
143 dep_to_git = self._create_cargo_config()
144
145 if self.ws_dir is not None:
146 self._patchup_workspace(dep_to_git)
147
148 def _build(self, install_dirs, reconfigure) -> None:
149 # _prepare has been run already. Actually do the build
150 build_source_dir = self.build_source_dir()
151 if self.manifests_to_build is None:
152 self.run_cargo(
153 install_dirs,
154 "build",
155 ["--out-dir", os.path.join(self.inst_dir, "bin"), "-Zunstable-options"],
156 )
157 else:
158 for manifest in self.manifests_to_build:
159 self.run_cargo(
160 install_dirs,
161 "build",
162 [
163 "--out-dir",
164 os.path.join(self.inst_dir, "bin"),
165 "-Zunstable-options",
166 "--manifest-path",
167 self.manifest_dir(manifest),
168 ],
169 )
170
171 self.recreate_dir(build_source_dir, os.path.join(self.inst_dir, "source"))
172
173 def run_tests(
174 self, install_dirs, schedule_type, owner, test_filter, retry, no_testpilot
175 ) -> None:
176 if test_filter:
177 args = ["--", test_filter]
178 else:
179 args = []
180
181 if self.manifests_to_build is None:
182 self.run_cargo(install_dirs, "test", args)
183 if self.build_doc:
184 self.run_cargo(install_dirs, "doc", ["--no-deps"])
185 else:
186 for manifest in self.manifests_to_build:
187 margs = ["--manifest-path", self.manifest_dir(manifest)]
188 self.run_cargo(install_dirs, "test", args + margs)
189 if self.build_doc:
190 self.run_cargo(install_dirs, "doc", ["--no-deps"] + margs)
191
192 def _patchup_workspace(self, dep_to_git) -> None:
193 """
194 This method makes some assumptions about the state of the project and
195 its cargo dependendies:
196 1. Crates from cargo dependencies can be extracted from Cargo.toml files
197 using _extract_crates function. It is using a heuristic so check its
198 code to understand how it is done.
199 2. The extracted cargo dependencies crates can be found in the
200 dependency's install dir using _resolve_crate_to_path function
201 which again is using a heuristic.
202
203 Notice that many things might go wrong here. E.g. if someone depends
204 on another getdeps crate by writing in their Cargo.toml file:
205
206 my-rename-of-crate = { package = "crate", git = "..." }
207
208 they can count themselves lucky because the code will raise an
209 Exception. There might be more cases where the code will silently pass
210 producing bad results.
211 """
212 workspace_dir = self.workspace_dir()
213 git_url_to_crates_and_paths = self._resolve_config(dep_to_git)
214 if git_url_to_crates_and_paths:
215 patch_cargo = os.path.join(workspace_dir, "Cargo.toml")
216 if os.path.isfile(patch_cargo):
217 with open(patch_cargo, "r") as f:
218 manifest_content = f.read()
219 else:
220 manifest_content = ""
221
222 new_content = manifest_content
223 if "[package]" not in manifest_content:
224 # A fake manifest has to be crated to change the virtual
225 # manifest into a non-virtual. The virtual manifests are limited
226 # in many ways and the inability to define patches on them is
227 # one. Check https://github.com/rust-lang/cargo/issues/4934 to
228 # see if it is resolved.
229 null_file = "/dev/null"
230 if self.build_opts.is_windows():
231 null_file = "nul"
232 new_content += f"""
233 [package]
234 name = "fake_manifest_of_{self.manifest.name}"
235 version = "0.0.0"
236
237 [lib]
238 path = "{null_file}"
239 """
240 config = []
241 for git_url, crates_to_patch_path in git_url_to_crates_and_paths.items():
242 crates_patches = [
243 '{} = {{ path = "{}" }}'.format(
244 crate,
245 crates_to_patch_path[crate].replace("\\", "\\\\"),
246 )
247 for crate in sorted(crates_to_patch_path.keys())
248 ]
249 patch_key = f'[patch."{git_url}"]'
250 if patch_key not in manifest_content:
251 config.append(f"\n{patch_key}\n" + "\n".join(crates_patches))
252 new_content += "\n".join(config)
253 if new_content != manifest_content:
254 with open(patch_cargo, "w") as f:
255 print(f"writing patch to {patch_cargo}")
256 f.write(new_content)
257
258 def _resolve_config(self, dep_to_git) -> typing.Dict[str, typing.Dict[str, str]]:
259 """
260 Returns a configuration to be put inside root Cargo.toml file which
261 patches the dependencies git code with local getdeps versions.
262 See https://doc.rust-lang.org/cargo/reference/manifest.html#the-patch-section
263 """
264 dep_to_crates = self._resolve_dep_to_crates(self.build_source_dir(), dep_to_git)
265
266 git_url_to_crates_and_paths = {}
267 for dep_name in sorted(dep_to_git.keys()):
268 git_conf = dep_to_git[dep_name]
269 req_crates = sorted(dep_to_crates.get(dep_name, []))
270 if not req_crates:
271 continue # nothing to patch, move along
272
273 git_url = git_conf.get("repo_url", None)
274 crate_source_map = git_conf["crate_source_map"]
275 if git_url and crate_source_map:
276 crates_to_patch_path = git_url_to_crates_and_paths.get(git_url, {})
277 for c in req_crates:
278 if c in crate_source_map and c not in crates_to_patch_path:
279 crates_to_patch_path[c] = crate_source_map[c]
280 print(
281 f"{self.manifest.name}: Patching crate {c} via virtual manifest in {self.workspace_dir()}"
282 )
283 if crates_to_patch_path:
284 git_url_to_crates_and_paths[git_url] = crates_to_patch_path
285
286 return git_url_to_crates_and_paths
287
288 def _resolve_dep_to_git(self):
289 """
290 For each direct dependency of the currently build manifest check if it
291 is also cargo-builded and if yes then extract it's git configs and
292 install dir
293 """
294 dependencies = self.manifest.get_dependencies(self.ctx)
295 if not dependencies:
296 return []
297
298 dep_to_git = {}
299 for dep in dependencies:
300 dep_manifest = self.loader.load_manifest(dep)
301 dep_builder = dep_manifest.get("build", "builder", ctx=self.ctx)
302
303 dep_cargo_conf = dep_manifest.get_section_as_dict("cargo", self.ctx)
304 dep_crate_map = dep_manifest.get_section_as_dict("crate.pathmap", self.ctx)
305
306 if (
307 not (dep_crate_map or dep_cargo_conf)
308 and dep_builder not in ["cargo"]
309 or dep == "rust"
310 ):
311 # This dependency has no cargo rust content so ignore it.
312 # The "rust" dependency is an exception since it contains the
313 # toolchain.
314 continue
315
316 git_conf = dep_manifest.get_section_as_dict("git", self.ctx)
317 if dep != "rust" and "repo_url" not in git_conf:
318 raise Exception(
319 f"{dep}: A cargo dependency requires git.repo_url to be defined."
320 )
321
322 if dep_builder == "cargo":
323 dep_source_dir = self.loader.get_project_install_dir(dep_manifest)
324 dep_source_dir = os.path.join(dep_source_dir, "source")
325 else:
326 fetcher = self.loader.create_fetcher(dep_manifest)
327 dep_source_dir = fetcher.get_src_dir()
328
329 crate_source_map = {}
330 if dep_crate_map:
331 for (crate, subpath) in dep_crate_map.items():
332 if crate not in crate_source_map:
333 if self.build_opts.is_windows():
334 subpath = subpath.replace("/", "\\")
335 crate_path = os.path.join(dep_source_dir, subpath)
336 print(
337 f"{self.manifest.name}: Mapped crate {crate} to dep {dep} dir {crate_path}"
338 )
339 crate_source_map[crate] = crate_path
340 elif dep_cargo_conf:
341 # We don't know what crates are defined buy the dep, look for them
342 search_pattern = re.compile('\\[package\\]\nname = "(.*)"')
343 for crate_root, _, files in os.walk(dep_source_dir):
344 if "Cargo.toml" in files:
345 with open(os.path.join(crate_root, "Cargo.toml"), "r") as f:
346 content = f.read()
347 match = search_pattern.search(content)
348 if match:
349 crate = match.group(1)
350 if crate:
351 print(
352 f"{self.manifest.name}: Discovered crate {crate} in dep {dep} dir {crate_root}"
353 )
354 crate_source_map[crate] = crate_root
355
356 git_conf["crate_source_map"] = crate_source_map
357
358 if not dep_crate_map and dep_cargo_conf:
359 dep_cargo_dir = self.loader.get_project_build_dir(dep_manifest)
360 dep_cargo_dir = os.path.join(dep_cargo_dir, "source")
361 dep_ws_dir = dep_cargo_conf.get("workspace_dir", None)
362 if dep_ws_dir:
363 dep_cargo_dir = os.path.join(dep_cargo_dir, dep_ws_dir)
364 git_conf["cargo_vendored_sources"] = dep_cargo_dir
365
366 dep_to_git[dep] = git_conf
367 return dep_to_git
368
369 def _resolve_dep_to_crates(self, build_source_dir, dep_to_git):
370 """
371 This function traverse the build_source_dir in search of Cargo.toml
372 files, extracts the crate names from them using _extract_crates
373 function and returns a merged result containing crate names per
374 dependency name from all Cargo.toml files in the project.
375 """
376 if not dep_to_git:
377 return {} # no deps, so don't waste time traversing files
378
379 dep_to_crates = {}
380
381 # First populate explicit crate paths from dependencies
382 for name, git_conf in dep_to_git.items():
383 crates = git_conf["crate_source_map"].keys()
384 if crates:
385 dep_to_crates.setdefault(name, set()).update(crates)
386
387 # Now find from Cargo.tomls
388 for root, _, files in os.walk(build_source_dir):
389 for f in files:
390 if f == "Cargo.toml":
391 more_dep_to_crates = CargoBuilder._extract_crates_used(
392 os.path.join(root, f), dep_to_git
393 )
394 for dep_name, crates in more_dep_to_crates.items():
395 existing_crates = dep_to_crates.get(dep_name, set())
396 for c in crates:
397 if c not in existing_crates:
398 print(
399 f"Patch {self.manifest.name} uses {dep_name} crate {crates}"
400 )
401 existing_crates.add(c)
402 dep_to_crates.setdefault(name, set()).update(existing_crates)
403 return dep_to_crates
404
405 @staticmethod
406 def _extract_crates_used(cargo_toml_file, dep_to_git):
407 """
408 This functions reads content of provided cargo toml file and extracts
409 crate names per each dependency. The extraction is done by a heuristic
410 so it might be incorrect.
411 """
412 deps_to_crates = {}
413 with open(cargo_toml_file, "r") as f:
414 for line in f.readlines():
415 if line.startswith("#") or "git = " not in line:
416 continue # filter out commented lines and ones without git deps
417 for dep_name, conf in dep_to_git.items():
418 # Only redirect deps that point to git URLS
419 if 'git = "{}"'.format(conf["repo_url"]) in line:
420 pkg_template = ' package = "'
421 if pkg_template in line:
422 crate_name, _, _ = line.partition(pkg_template)[
423 2
424 ].partition('"')
425 else:
426 crate_name, _, _ = line.partition("=")
427 deps_to_crates.setdefault(dep_name, set()).add(
428 crate_name.strip()
429 )
430 return deps_to_crates
431
432 def _resolve_crate_to_path(self, crate, crate_source_map):
433 """
434 Tries to find <crate> in source_dir by searching a [package]
435 keyword followed by name = "<crate>".
436 """
437 search_pattern = '[package]\nname = "{}"'.format(crate)
438
439 for (_crate, crate_source_dir) in crate_source_map.items():
440 for crate_root, _, files in os.walk(crate_source_dir):
441 if "Cargo.toml" in files:
442 with open(os.path.join(crate_root, "Cargo.toml"), "r") as f:
443 content = f.read()
444 if search_pattern in content:
445 return crate_root
446
447 raise Exception(
448 f"{self.manifest.name}: Failed to find dep crate {crate} in paths {crate_source_map}"
449 )