Debian Codegraph @

configure.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 import codecs
6 import itertools
7 import logging
8 import os
9 import pprint
10 import sys
11 import textwrap
12 from collections.abc import Iterable
13
14 base_dir = os.path.abspath(os.path.dirname(__file__))
15 sys.path.insert(0, os.path.join(base_dir, "python", "mach"))
16 sys.path.insert(0, os.path.join(base_dir, "python", "mozboot"))
17 sys.path.insert(0, os.path.join(base_dir, "python", "mozbuild"))
18 sys.path.insert(0, os.path.join(base_dir, "third_party", "python", "packaging"))
19 sys.path.insert(0, os.path.join(base_dir, "third_party", "python", "six"))
20 sys.path.insert(0, os.path.join(base_dir, "third_party", "python", "looseversion"))
21 sys.path.insert(0, os.path.join(base_dir, "third_party", "python", "filelock"))
22 import mozpack.path as mozpath
23 from mach.requirements import MachEnvRequirements
24 from mach.site import (
25 CommandSiteManager,
26 ExternalPythonSite,
27 MachSiteManager,
28 MozSiteMetadata,
29 SitePackagesSource,
30 )
31 from mozbuild.backend.configenvironment import PartialConfigEnvironment
32 from mozbuild.configure import TRACE, ConfigureSandbox
33 from mozbuild.pythonutil import iter_modules_in_path
34
35 if "MOZ_CONFIGURE_BUILDSTATUS" in os.environ:
36
37 def buildstatus(message):
38 print("BUILDSTATUS", message)
39
40 else:
41
42 def buildstatus(message):
43 return
44
45
46 def main(argv):
47 # Check for CRLF line endings.
48 with open(__file__) as fh:
49 data = fh.read()
50 if "\r" in data:
51 print(
52 "\n ***\n"
53 " * The source tree appears to have Windows-style line endings.\n"
54 " *\n"
55 " * If using Git, Git is likely configured to use Windows-style\n"
56 " * line endings.\n"
57 " *\n"
58 " * To convert the working copy to UNIX-style line endings, run\n"
59 " * the following:\n"
60 " *\n"
61 " * $ git config core.autocrlf false\n"
62 " * $ git config core.eof lf\n"
63 " * $ git rm --cached -r .\n"
64 " * $ git reset --hard\n"
65 " *\n"
66 " * If not using Git, the tool you used to obtain the source\n"
67 " * code likely converted files to Windows line endings. See\n"
68 " * usage information for that tool for more.\n"
69 " ***",
70 file=sys.stderr,
71 )
72 return 1
73
74 config = {}
75
76 sandbox = ConfigureSandbox(config, os.environ, argv)
77
78 if not sandbox._help:
79 # This limitation has mostly to do with GNU make. Since make can't represent
80 # variables with spaces without correct quoting and many paths are used
81 # without proper quoting, using paths with spaces commonly results in
82 # targets or dependencies being treated as multiple paths. This, of course,
83 # undermines the ability for make to perform up-to-date checks and makes
84 # the build system not work very efficiently. In theory, a non-make build
85 # backend will make this limitation go away. But there is likely a long tail
86 # of things that will need fixing due to e.g. lack of proper path quoting.
87 topsrcdir = os.path.realpath(os.path.dirname(__file__))
88 if len(topsrcdir.split()) > 1:
89 print(
90 "Source directory cannot be located in a path with spaces: %s"
91 % topsrcdir,
92 file=sys.stderr,
93 )
94 return 1
95 topobjdir = os.path.realpath(os.curdir)
96 if len(topobjdir.split()) > 1:
97 print(
98 "Object directory cannot be located in a path with spaces: %s"
99 % topobjdir,
100 file=sys.stderr,
101 )
102 return 1
103
104 # Do not allow topobjdir == topsrcdir
105 if os.path.samefile(topsrcdir, topobjdir):
106 print(
107 " ***\n"
108 " * Building directly in the main source directory is not allowed.\n"
109 " *\n"
110 " * To build, you must run configure from a separate directory\n"
111 " * (referred to as an object directory).\n"
112 " *\n"
113 " * If you are building with a mozconfig, you will need to change your\n"
114 " * mozconfig to point to a different object directory.\n"
115 " ***",
116 file=sys.stderr,
117 )
118 return 1
119 buildstatus("START_configure activate virtualenv")
120 _activate_build_virtualenv()
121 buildstatus("END_configure activate virtualenv")
122
123 clobber_file = "CLOBBER"
124 if not os.path.exists(clobber_file):
125 # Simply touch the file.
126 with open(clobber_file, "a"):
127 pass
128
129 if os.environ.get("MOZ_CONFIGURE_TRACE"):
130 sandbox._logger.setLevel(TRACE)
131
132 buildstatus("START_configure read moz.configure")
133 sandbox.include_file(os.path.join(os.path.dirname(__file__), "moz.configure"))
134 buildstatus("END_configure read moz.configure")
135 buildstatus("START_configure run moz.configure")
136 sandbox.run()
137 buildstatus("END_configure run moz.configure")
138
139 if sandbox._help:
140 return 0
141
142 buildstatus("START_configure config.status")
143 logging.getLogger("moz.configure").info("Creating config.status")
144 try:
145 js_config = config.copy()
146 pwd = os.getcwd()
147 try:
148 os.makedirs("js/src", exist_ok=True)
149 os.chdir("js/src")
150 # The build system frontend expects $objdir/js/src/config.status
151 # to have $objdir/js/src as topobjdir.
152 # We want forward slashes on all platforms.
153 js_config["TOPOBJDIR"] += "/js/src"
154 ret = config_status(js_config, execute=False)
155 if ret:
156 return ret
157 finally:
158 os.chdir(pwd)
159 return config_status(config)
160 finally:
161 buildstatus("END_configure config.status")
162
163
164 def check_unicode(obj):
165 """Recursively check that all strings in the object are unicode strings."""
166 if isinstance(obj, dict):
167 result = True
168 for k, v in obj.items():
169 if not check_unicode(k):
170 print("%s key is not unicode." % k, file=sys.stderr)
171 result = False
172 elif not check_unicode(v):
173 print("%s value is not unicode." % k, file=sys.stderr)
174 result = False
175 return result
176 if isinstance(obj, bytes):
177 return False
178 if isinstance(obj, str):
179 return True
180 if isinstance(obj, Iterable):
181 return all(check_unicode(o) for o in obj)
182 return True
183
184
185 def config_status(config, execute=True):
186 # Sanitize config data to feed config.status
187 # Ideally, all the backend and frontend code would handle the booleans, but
188 # there are so many things involved, that it's easier to keep config.status
189 # untouched for now.
190 def sanitize_config(v):
191 if v is True:
192 return "1"
193 if v is False:
194 return ""
195 # Serialize types that look like lists and tuples as lists.
196 if not isinstance(v, (bytes, str, dict)) and isinstance(v, Iterable):
197 return list(v)
198 return v
199
200 sanitized_config = {}
201 sanitized_config["substs"] = {
202 k: sanitize_config(v)
203 for k, v in config.items()
204 if k
205 not in (
206 "DEFINES",
207 "TOPSRCDIR",
208 "TOPOBJDIR",
209 "CONFIG_STATUS_DEPS",
210 )
211 }
212 sanitized_config["defines"] = {
213 k: sanitize_config(v) for k, v in config["DEFINES"].items()
214 }
215 sanitized_config["topsrcdir"] = config["TOPSRCDIR"]
216 sanitized_config["topobjdir"] = config["TOPOBJDIR"]
217 sanitized_config["mozconfig"] = config.get("MOZCONFIG")
218
219 if not check_unicode(sanitized_config):
220 print("Configuration should be all unicode.", file=sys.stderr)
221 print("Please file a bug for the above.", file=sys.stderr)
222 return 1
223
224 # Create config.status. Eventually, we'll want to just do the work it does
225 # here, when we're able to skip configure tests/use cached results/not rely
226 # on autoconf.
227 with codecs.open("config.status", "w", "utf-8") as fh:
228 fh.write(
229 textwrap.dedent(
230 """\
231 #!%(python)s
232 # coding=utf-8
233 from mozbuild.configure.constants import *
234 """
235 )
236 % {"python": config["PYTHON3"]}
237 )
238 for k, v in sorted(sanitized_config.items()):
239 fh.write("%s = " % k)
240 pprint.pprint(v, stream=fh, indent=4)
241 fh.write(
242 "__all__ = ['topobjdir', 'topsrcdir', 'defines', " "'substs', 'mozconfig']"
243 )
244
245 if execute:
246 fh.write(
247 textwrap.dedent(
248 """
249 if __name__ == '__main__':
250 from mozbuild.config_status import config_status
251 args = dict([(name, globals()[name]) for name in __all__])
252 config_status(**args)
253 """
254 )
255 )
256
257 partial_config = PartialConfigEnvironment(config["TOPOBJDIR"])
258 partial_config.write_vars(sanitized_config)
259
260 # Write out a file so the build backend knows to re-run configure when
261 # relevant Python changes.
262 with open("config_status_deps.in", "w", encoding="utf-8", newline="\n") as fh:
263 for f in sorted(
264 itertools.chain(
265 config["CONFIG_STATUS_DEPS"],
266 iter_modules_in_path(config["TOPOBJDIR"], config["TOPSRCDIR"]),
267 )
268 ):
269 fh.write("%s\n" % mozpath.normpath(f))
270
271 # Other things than us are going to run this file, so we need to give it
272 # executable permissions.
273 os.chmod("config.status", 0o755)
274 if execute:
275 from mozbuild.config_status import config_status
276
277 return config_status(args=[], **sanitized_config)
278 return 0
279
280
281 def _activate_build_virtualenv():
282 """Ensure that the build virtualenv is activated
283
284 configure.py may be executed through Mach, or via "./configure, make".
285 In the first case, the build virtualenv should already be activated.
286 In the second case, we're likely being executed with the system Python, and must
287 prepare the virtualenv and activate it ourselves.
288 """
289
290 version = ".".join(str(i) for i in sys.version_info[0:3])
291 print(f"Using Python {version} from {sys.executable}")
292
293 active_site = MozSiteMetadata.from_runtime()
294 if active_site and active_site.site_name == "build":
295 # We're already running within the "build" virtualenv, no additional work is
296 # needed.
297 return
298
299 # We're using the system python (or are nested within a non-build mach-managed
300 # virtualenv), so we should activate the build virtualenv as expected by the rest of
301 # configure.
302
303 topsrcdir = os.path.realpath(os.path.dirname(__file__))
304
305 mach_site = MachSiteManager(
306 topsrcdir,
307 None,
308 MachEnvRequirements(),
309 ExternalPythonSite(sys.executable),
310 SitePackagesSource.NONE,
311 )
312 mach_site.activate()
313
314 from mach.util import get_virtualenv_base_dir
315
316 build_site = CommandSiteManager.from_environment(
317 topsrcdir,
318 None,
319 "build",
320 get_virtualenv_base_dir(topsrcdir),
321 )
322 if not build_site.ensure():
323 print("Created Python 3 virtualenv")
324 build_site.activate()
325
326
327 if __name__ == "__main__":
328 sys.exit(main(sys.argv))