Debian Codegraph @

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

raw
1 # Copyright (c) Meta Platforms, Inc. and affiliates.
2 #
3 # This source code is licensed under the MIT license found in the
4 # LICENSE file in the root directory of this source tree.
5
6 import codecs
7 import collections
8 import email
9 import os
10 import re
11 import stat
12 from typing import Dict, List
13
14 from .builder import BuilderBase, CMakeBuilder
15
16
17 WheelNameInfo = collections.namedtuple(
18 "WheelNameInfo", ("distribution", "version", "build", "python", "abi", "platform")
19 )
20
21 CMAKE_HEADER = """
22 cmake_minimum_required(VERSION 3.8)
23
24 project("{manifest_name}" LANGUAGES C)
25
26 set(CMAKE_MODULE_PATH
27 "{cmake_dir}"
28 ${{CMAKE_MODULE_PATH}}
29 )
30 include(FBPythonBinary)
31
32 set(CMAKE_INSTALL_DIR lib/cmake/{manifest_name} CACHE STRING
33 "The subdirectory where CMake package config files should be installed")
34 """
35
36 CMAKE_FOOTER = """
37 install_fb_python_library({lib_name} EXPORT all)
38 install(
39 EXPORT all
40 FILE {manifest_name}-targets.cmake
41 NAMESPACE {namespace}::
42 DESTINATION ${{CMAKE_INSTALL_DIR}}
43 )
44
45 include(CMakePackageConfigHelpers)
46 configure_package_config_file(
47 ${{CMAKE_BINARY_DIR}}/{manifest_name}-config.cmake.in
48 {manifest_name}-config.cmake
49 INSTALL_DESTINATION ${{CMAKE_INSTALL_DIR}}
50 PATH_VARS
51 CMAKE_INSTALL_DIR
52 )
53 install(
54 FILES ${{CMAKE_CURRENT_BINARY_DIR}}/{manifest_name}-config.cmake
55 DESTINATION ${{CMAKE_INSTALL_DIR}}
56 )
57 """
58
59 CMAKE_CONFIG_FILE = """
60 @PACKAGE_INIT@
61
62 include(CMakeFindDependencyMacro)
63
64 set_and_check({upper_name}_CMAKE_DIR "@PACKAGE_CMAKE_INSTALL_DIR@")
65
66 if (NOT TARGET {namespace}::{lib_name})
67 include("${{{upper_name}_CMAKE_DIR}}/{manifest_name}-targets.cmake")
68 endif()
69
70 set({upper_name}_LIBRARIES {namespace}::{lib_name})
71
72 {find_dependency_lines}
73
74 if (NOT {manifest_name}_FIND_QUIETLY)
75 message(STATUS "Found {manifest_name}: ${{PACKAGE_PREFIX_DIR}}")
76 endif()
77 """
78
79
80 # Note: for now we are manually manipulating the wheel packet contents.
81 # The wheel format is documented here:
82 # https://www.python.org/dev/peps/pep-0491/#file-format
83 #
84 # We currently aren't particularly smart about correctly handling the full wheel
85 # functionality, but this is good enough to handle simple pure-python wheels,
86 # which is the main thing we care about right now.
87 #
88 # We could potentially use pip to install the wheel to a temporary location and
89 # then copy its "installed" files, but this has its own set of complications.
90 # This would require pip to already be installed and available, and we would
91 # need to correctly find the right version of pip or pip3 to use.
92 # If we did ever want to go down that path, we would probably want to use
93 # something like the following pip3 command:
94 # pip3 --isolated install --no-cache-dir --no-index --system \
95 # --target <install_dir> <wheel_file>
96 # pyre-fixme[13] fields initialized in _build
97 class PythonWheelBuilder(BuilderBase):
98 """This Builder can take Python wheel archives and install them as python libraries
99 that can be used by add_fb_python_library()/add_fb_python_executable() CMake rules.
100 """
101
102 dist_info_dir: str
103 template_format_dict: Dict[str, str]
104
105 def _build(self, install_dirs: List[str], reconfigure: bool) -> None:
106 # When we are invoked, self.src_dir contains the unpacked wheel contents.
107 #
108 # Since a wheel file is just a zip file, the Fetcher code recognizes it as such
109 # and goes ahead and unpacks it. (We could disable that Fetcher behavior in the
110 # future if we ever wanted to, say if we wanted to call pip here.)
111 wheel_name = self._parse_wheel_name()
112 name_version_prefix = "-".join((wheel_name.distribution, wheel_name.version))
113 dist_info_name = name_version_prefix + ".dist-info"
114 data_dir_name = name_version_prefix + ".data"
115 self.dist_info_dir = os.path.join(self.src_dir, dist_info_name)
116 wheel_metadata = self._read_wheel_metadata(wheel_name)
117
118 # Check that we can understand the wheel version.
119 # We don't really care about wheel_metadata["Root-Is-Purelib"] since
120 # we are generating our own standalone python archives rather than installing
121 # into site-packages.
122 version = wheel_metadata["Wheel-Version"]
123 if not version.startswith("1."):
124 raise Exception("unsupported wheel version %s" % (version,))
125
126 # Add a find_dependency() call for each of our dependencies.
127 # The dependencies are also listed in the wheel METADATA file, but it is simpler
128 # to pull this directly from the getdeps manifest.
129 dep_list = sorted(
130 self.manifest.get_section_as_dict("dependencies", self.ctx).keys()
131 )
132 find_dependency_lines = ["find_dependency({})".format(dep) for dep in dep_list]
133
134 getdeps_cmake_dir = os.path.join(
135 os.path.dirname(os.path.dirname(__file__)), "CMake"
136 )
137 self.template_format_dict = {
138 # Note that CMake files always uses forward slash separators in path names,
139 # even on Windows. Therefore replace path separators here.
140 "cmake_dir": _to_cmake_path(getdeps_cmake_dir),
141 "lib_name": self.manifest.name,
142 "manifest_name": self.manifest.name,
143 "namespace": self.manifest.name,
144 "upper_name": self.manifest.name.upper().replace("-", "_"),
145 "find_dependency_lines": "\n".join(find_dependency_lines),
146 }
147
148 # Find sources from the root directory
149 path_mapping = {}
150 for entry in os.listdir(self.src_dir):
151 if entry in (dist_info_name, data_dir_name):
152 continue
153 self._add_sources(path_mapping, os.path.join(self.src_dir, entry), entry)
154
155 # Files under the .data directory also need to be installed in the correct
156 # locations
157 if os.path.exists(data_dir_name):
158 # TODO: process the subdirectories of data_dir_name
159 # This isn't implemented yet since for now we have only needed dependencies
160 # on some simple pure Python wheels, so I haven't tested against wheels with
161 # additional files in the .data directory.
162 raise Exception(
163 "handling of the subdirectories inside %s is not implemented yet"
164 % data_dir_name
165 )
166
167 # Emit CMake files
168 self._write_cmakelists(path_mapping, dep_list)
169 self._write_cmake_config_template()
170
171 # Run the build
172 self._run_cmake_build(install_dirs, reconfigure)
173
174 def _run_cmake_build(self, install_dirs: List[str], reconfigure: bool) -> None:
175 cmake_builder = CMakeBuilder(
176 build_opts=self.build_opts,
177 ctx=self.ctx,
178 manifest=self.manifest,
179 # Note that we intentionally supply src_dir=build_dir,
180 # since we wrote out our generated CMakeLists.txt in the build directory
181 src_dir=self.build_dir,
182 build_dir=self.build_dir,
183 inst_dir=self.inst_dir,
184 loader=None,
185 defines={},
186 final_install_prefix=None,
187 )
188 cmake_builder.build(install_dirs=install_dirs, reconfigure=reconfigure)
189
190 def _write_cmakelists(self, path_mapping: Dict[str, str], dependencies) -> None:
191 cmake_path = os.path.join(self.build_dir, "CMakeLists.txt")
192 with open(cmake_path, "w") as f:
193 f.write(CMAKE_HEADER.format(**self.template_format_dict))
194 for dep in dependencies:
195 f.write("find_package({0} REQUIRED)\n".format(dep))
196
197 f.write(
198 "add_fb_python_library({lib_name}\n".format(**self.template_format_dict)
199 )
200 f.write(' BASE_DIR "%s"\n' % _to_cmake_path(self.src_dir))
201 f.write(" SOURCES\n")
202 for src_path, install_path in path_mapping.items():
203 f.write(
204 ' "%s=%s"\n'
205 % (_to_cmake_path(src_path), _to_cmake_path(install_path))
206 )
207 if dependencies:
208 f.write(" DEPENDS\n")
209 for dep in dependencies:
210 f.write(' "{0}::{0}"\n'.format(dep))
211 f.write(")\n")
212
213 f.write(CMAKE_FOOTER.format(**self.template_format_dict))
214
215 def _write_cmake_config_template(self) -> None:
216 config_path_name = self.manifest.name + "-config.cmake.in"
217 output_path = os.path.join(self.build_dir, config_path_name)
218
219 with open(output_path, "w") as f:
220 f.write(CMAKE_CONFIG_FILE.format(**self.template_format_dict))
221
222 def _add_sources(
223 self, path_mapping: Dict[str, str], src_path: str, install_path: str
224 ) -> None:
225 s = os.lstat(src_path)
226 if not stat.S_ISDIR(s.st_mode):
227 path_mapping[src_path] = install_path
228 return
229
230 for entry in os.listdir(src_path):
231 self._add_sources(
232 path_mapping,
233 os.path.join(src_path, entry),
234 os.path.join(install_path, entry),
235 )
236
237 def _parse_wheel_name(self) -> WheelNameInfo:
238 # The ArchiveFetcher prepends "manifest_name-", so strip that off first.
239 wheel_name = os.path.basename(self.src_dir)
240 prefix = self.manifest.name + "-"
241 if not wheel_name.startswith(prefix):
242 raise Exception(
243 "expected wheel source directory to be of the form %s-NAME.whl"
244 % (prefix,)
245 )
246 wheel_name = wheel_name[len(prefix) :]
247
248 wheel_name_re = re.compile(
249 r"(?P<distribution>[^-]+)"
250 r"-(?P<version>\d+[^-]*)"
251 r"(-(?P<build>\d+[^-]*))?"
252 r"-(?P<python>\w+\d+(\.\w+\d+)*)"
253 r"-(?P<abi>\w+)"
254 r"-(?P<platform>\w+(\.\w+)*)"
255 r"\.whl"
256 )
257 match = wheel_name_re.match(wheel_name)
258 if not match:
259 raise Exception(
260 "bad python wheel name %s: expected to have the form "
261 "DISTRIBUTION-VERSION-[-BUILD]-PYTAG-ABI-PLATFORM"
262 )
263
264 return WheelNameInfo(
265 distribution=match.group("distribution"),
266 version=match.group("version"),
267 build=match.group("build"),
268 python=match.group("python"),
269 abi=match.group("abi"),
270 platform=match.group("platform"),
271 )
272
273 def _read_wheel_metadata(self, wheel_name):
274 metadata_path = os.path.join(self.dist_info_dir, "WHEEL")
275 with codecs.open(metadata_path, "r", encoding="utf-8") as f:
276 return email.message_from_file(f)
277
278
279 def _to_cmake_path(path):
280 # CMake always uses forward slashes to separate paths in CMakeLists.txt files,
281 # even on Windows. It treats backslashes as character escapes, so using
282 # backslashes in the path will cause problems. Therefore replace all path
283 # separators with forward slashes to make sure the paths are correct on Windows.
284 # e.g. "C:\foo\bar.txt" becomes "C:/foo/bar.txt"
285 return path.replace(os.path.sep, "/")