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/.
10 from abc
import ABCMeta
, abstractmethod
11 from contextlib
import contextmanager
13 import mozpack
.path
as mozpath
15 from mach
.mixin
.logging
import LoggingMixin
17 from mozbuild
.base
import ExecutionSummary
19 from ..frontend
.data
import ContextDerived
20 from ..frontend
.reader
import EmptyConfig
21 from ..preprocessor
import Preprocessor
22 from ..pythonutil
import iter_modules_in_path
23 from ..util
import FileAvoidWrite
, simple_diff
24 from .configenvironment
import ConfigEnvironment
27 class BuildBackend(LoggingMixin
):
28 """Abstract base class for build backends.
30 A build backend is merely a consumer of the build configuration (the output
31 of the frontend processing). It does something with said data. What exactly
32 is the discretion of the specific implementation.
35 __metaclass__
= ABCMeta
37 def __init__(self
, environment
):
38 assert isinstance(environment
, (ConfigEnvironment
, EmptyConfig
))
39 self
.populate_logger()
41 self
.environment
= environment
43 # Files whose modification should cause a new read and backend
45 self
.backend_input_files
= set()
47 # Files generated by the backend.
48 self
._backend
_output
_files
= set()
50 self
._environments
= {}
51 self
._environments
[environment
.topobjdir
] = environment
53 # The number of backend files created.
54 self
._created
_count
= 0
56 # The number of backend files updated.
57 self
._updated
_count
= 0
59 # The number of unchanged backend files.
60 self
._unchanged
_count
= 0
62 # The number of deleted backend files.
63 self
._deleted
_count
= 0
65 # The total wall time spent in the backend. This counts the time the
66 # backend writes out files, etc.
67 self
._execution
_time
= 0.0
69 # Mapping of changed file paths to diffs of the changes.
77 return ExecutionSummary(
78 self
.__class
__.__name
__.replace("Backend", "")
79 + " backend executed in {execution_time:.2f}s\n "
80 "{total:d} total backend files; "
81 "{created:d} created; "
82 "{updated:d} updated; "
83 "{unchanged:d} unchanged; "
84 "{deleted:d} deleted",
85 execution_time
=self
._execution
_time
,
86 total
=self
._created
_count
+ self
._updated
_count
+ self
._unchanged
_count
,
87 created
=self
._created
_count
,
88 updated
=self
._updated
_count
,
89 unchanged
=self
._unchanged
_count
,
90 deleted
=self
._deleted
_count
,
94 """Hook point for child classes to perform actions during __init__.
96 This exists so child classes don't need to implement __init__.
99 def consume(self
, objs
):
100 """Consume a stream of TreeMetadata instances.
102 This is the main method of the interface. This is what takes the
103 frontend output and does something with it.
105 Child classes are not expected to implement this method. Instead, the
106 base class consumes objects and calls methods (possibly) implemented by
110 # Previously generated files.
111 list_file
= mozpath
.join(
112 self
.environment
.topobjdir
, "backend.%s" % self
.__class
__.__name
__
114 backend_output_list
= set()
115 if os
.path
.exists(list_file
):
116 with
open(list_file
) as fh
:
117 backend_output_list
.update(
118 mozpath
.normsep(p
) for p
in fh
.read().splitlines()
122 obj_start
= time
.monotonic()
123 if not self
.consume_object(obj
) and not isinstance(self
, PartialBackend
):
124 raise Exception("Unhandled object of type %s" % type(obj
))
125 self
._execution
_time
+= time
.monotonic() - obj_start
127 if isinstance(obj
, ContextDerived
) and not isinstance(self
, PartialBackend
):
128 self
.backend_input_files |
= obj
.context_all_paths
130 # Pull in all loaded Python as dependencies so any Python changes that
131 # could influence our output result in a rescan.
132 self
.backend_input_files |
= set(
133 iter_modules_in_path(self
.environment
.topsrcdir
, self
.environment
.topobjdir
)
136 finished_start
= time
.monotonic()
137 self
.consume_finished()
138 self
._execution
_time
+= time
.monotonic() - finished_start
140 # Purge backend files created in previous run, but not created anymore
141 delete_files
= backend_output_list
- self
._backend
_output
_files
142 for path
in delete_files
:
143 full_path
= mozpath
.join(self
.environment
.topobjdir
, path
)
145 with io
.open(full_path
, mode
="r", encoding
="utf-8") as existing
:
146 old_content
= existing
.read()
148 self
.file_diffs
[full_path
] = simple_diff(
149 full_path
, old_content
.splitlines(), None
156 self
._deleted
_count
+= 1
159 # Remove now empty directories
160 for dir in set(mozpath
.dirname(d
) for d
in delete_files
):
166 # Write out the list of backend files generated, if it changed.
167 if backend_output_list
!= self
._backend
_output
_files
:
168 with self
._write
_file
(list_file
) as fh
:
169 fh
.write("\n".join(sorted(self
._backend
_output
_files
)))
171 # Always update its mtime if we're not in dry-run mode.
173 with
open(list_file
, "a"):
174 os
.utime(list_file
, None)
176 # Write out the list of input files for the backend
177 with self
._write
_file
("%s.in" % list_file
) as fh
:
179 "\n".join(sorted(mozpath
.normsep(f
) for f
in self
.backend_input_files
))
183 def consume_object(self
, obj
):
184 """Consumes an individual TreeMetadata instance.
186 This is the main method used by child classes to react to build
190 def consume_finished(self
):
191 """Called when consume() has completed handling all objects."""
193 def build(self
, config
, output
, jobs
, verbose
, what
=None):
194 """Called when 'mach build' is executed.
196 This should return the status value of a subprocess, where 0 denotes
197 success and any other value is an error code. A return value of None
198 indicates that the default 'make -f client.mk' should run.
202 def _write_purgecaches(self
, config
):
203 """Write .purgecaches sentinels.
205 The purgecaches mechanism exists to allow the platform to
206 invalidate the XUL cache (which includes some JS) at application
207 startup-time. The application checks for .purgecaches in the
208 application directory, which varies according to
209 --enable-application/--enable-project. There's a further wrinkle on
210 macOS, where the real application directory is part of a Cocoa bundle
211 produced from the regular application directory by the build
212 system. In this case, we write to both locations, since the
213 build system recreates the Cocoa bundle from the contents of the
214 regular application directory and might remove a sentinel
218 app
= config
.substs
["MOZ_BUILD_APP"]
219 if app
== "mobile/android":
220 # In order to take effect, .purgecaches sentinels would need to be
221 # written to the Android device file system.
224 root
= mozpath
.join(config
.topobjdir
, "dist", "bin")
227 root
= mozpath
.join(config
.topobjdir
, "dist", "bin", "browser")
229 purgecaches_dirs
= [root
]
230 if app
== "browser" and "cocoa" == config
.substs
["MOZ_WIDGET_TOOLKIT"]:
231 bundledir
= mozpath
.join(
234 config
.substs
["MOZ_MACBUNDLE_NAME"],
239 purgecaches_dirs
.append(bundledir
)
241 for dir in purgecaches_dirs
:
242 with
open(mozpath
.join(dir, ".purgecaches"), "wt") as f
:
245 def post_build(self
, config
, output
, jobs
, verbose
, status
):
246 """Called late during 'mach build' execution, after `build(...)` has finished.
248 `status` is the status value returned from `build(...)`.
250 In the case where `build` returns `None`, this is called after
251 the default `make` command has completed, with the status of
254 This should return the status value from `build(...)`, or the
255 status value of a subprocess, where 0 denotes success and any
256 other value is an error code.
258 If an exception is raised, ``mach build`` will fail with a
261 self
._write
_purgecaches
(config
)
266 def _write_file(self
, path
=None, fh
=None, readmode
="r"):
267 """Context manager to write a file.
269 This is a glorified wrapper around FileAvoidWrite with integration to
270 update the summary data on this instance.
274 with self._write_file('foo.txt') as fh:
275 fh.write('hello world')
281 path
, capture_diff
=True, dry_run
=self
.dry_run
, readmode
=readmode
284 assert fh
is not None
286 dirname
= mozpath
.dirname(fh
.name
)
289 except OSError as error
:
290 if error
.errno
!= errno
.EEXIST
:
295 self
._backend
_output
_files
.add(
296 mozpath
.relpath(fh
.name
, self
.environment
.topobjdir
)
298 existed
, updated
= fh
.close()
300 self
.file_diffs
[fh
.name
] = fh
.diff
302 self
._created
_count
+= 1
304 self
._updated
_count
+= 1
306 self
._unchanged
_count
+= 1
309 def _get_preprocessor(self
, obj
):
310 """Returns a preprocessor with a few predefined values depending on
311 the given BaseConfigSubstitution(-like) object, and all the substs
312 in the current environment."""
314 srcdir
= mozpath
.dirname(obj
.input_path
)
317 k
: " ".join(v
) if isinstance(v
, list) else v
318 for k
, v
in six
.iteritems(obj
.config
.substs
)
322 top_srcdir
=obj
.topsrcdir
,
323 topobjdir
=obj
.topobjdir
,
325 srcdir_rel
=mozpath
.relpath(srcdir
, mozpath
.dirname(obj
.output_path
)),
326 relativesrcdir
=mozpath
.relpath(srcdir
, obj
.topsrcdir
) or ".",
327 DEPTH
=mozpath
.relpath(obj
.topobjdir
, mozpath
.dirname(obj
.output_path
))
330 pp
.do_filter("attemptSubstitution")
332 with self
._write
_file
(obj
.output_path
) as fh
:
337 class PartialBackend(BuildBackend
):
338 """A PartialBackend is a BuildBackend declaring that its consume_object
339 method may not handle all build configuration objects it's passed, and
343 def HybridBackend(*backends
):
344 """A HybridBackend is the combination of one or more PartialBackends
345 with a non-partial BuildBackend.
347 Build configuration objects are passed to each backend, stopping at the
348 first of them that declares having handled them.
350 assert len(backends
) >= 2
351 assert all(issubclass(b
, PartialBackend
) for b
in backends
[:-1])
352 assert not (issubclass(backends
[-1], PartialBackend
))
353 assert all(issubclass(b
, BuildBackend
) for b
in backends
)
355 class TheHybridBackend(BuildBackend
):
356 def __init__(self
, environment
):
357 self
._backends
= [b(environment
) for b
in backends
]
358 super(TheHybridBackend
, self
).__init
__(environment
)
360 def consume_object(self
, obj
):
361 return any(b
.consume_object(obj
) for b
in self
._backends
)
363 def consume_finished(self
):
364 for backend
in self
._backends
:
365 backend
.consume_finished()
374 setattr(self
, attr
, sum(getattr(b
, attr
) for b
in self
._backends
))
376 for b
in self
._backends
:
377 self
.file_diffs
.update(b
.file_diffs
)
378 for attr
in ("backend_input_files", "_backend_output_files"):
379 files
= getattr(self
, attr
)
380 files |
= getattr(b
, attr
)
384 (b
.__name
__.replace("Backend", "") for b
in backends
[:-1]),
385 (b
.__name
__ for b
in backends
[-1:]),
389 return type(str(name
), (TheHybridBackend
,), {})