summaryrefslogtreecommitdiffstats
path: root/python/mozbuild/mozpack/packager/formats.py
blob: d22848717656ebe8dc0191b4c7d05e1f36cb7eee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.

from __future__ import absolute_import, print_function, unicode_literals

from mozpack.chrome.manifest import (
    Manifest,
    ManifestInterfaces,
    ManifestChrome,
    ManifestBinaryComponent,
    ManifestResource,
    ManifestMultiContent,
)
from mozpack.errors import errors
from six.moves.urllib.parse import urlparse
import mozpack.path as mozpath
from mozpack.files import ManifestFile
from mozpack.copier import (
    FileRegistry,
    FileRegistrySubtree,
    Jarrer,
)

"""
Formatters are classes receiving packaging instructions and creating the
appropriate package layout.

There are three distinct formatters, each handling one of the different chrome
formats:
    - flat: essentially, copies files from the source with the same file system
      layout. Manifests entries are grouped in a single manifest per directory,
      as well as XPT interfaces.
    - jar: chrome content is packaged in jar files.
    - omni: chrome content, modules, non-binary components, and many other
      elements are packaged in an omnijar file for each base directory.

The base interface provides the following methods:
    - add_base(path [, addon])
        Register a base directory for an application or GRE, or an addon.
        Base directories usually contain a root manifest (manifests not
        included in any other manifest) named chrome.manifest.
        The optional addon argument tells whether the base directory
        is that of a packed addon (True), unpacked addon ('unpacked') or
        otherwise (False).
        The method may only be called in sorted order of `path` (alphanumeric
        order, parents before children).
    - add(path, content)
        Add the given content (BaseFile instance) at the given virtual path
    - add_interfaces(path, content)
        Add the given content (BaseFile instance) as an interface. Equivalent
        to add(path, content) with the right add_manifest().
    - add_manifest(entry)
        Add a ManifestEntry.
    - contains(path)
        Returns whether the given virtual path is known of the formatter.

The virtual paths mentioned above are paths as they would be with a flat
chrome.

Formatters all take a FileCopier instance they will fill with the packaged
data.
"""


class PiecemealFormatter(object):
    """
    Generic formatter that dispatches across different sub-formatters
    according to paths.
    """

    def __init__(self, copier):
        assert isinstance(copier, (FileRegistry, FileRegistrySubtree))
        self.copier = copier
        self._sub_formatter = {}
        self._frozen_bases = False

    def add_base(self, base, addon=False):
        # Only allow to add a base directory before calls to _get_base()
        assert not self._frozen_bases
        assert base not in self._sub_formatter
        assert all(base > b for b in self._sub_formatter)
        self._add_base(base, addon)

    def _get_base(self, path):
        """
        Return the deepest base directory containing the given path.
        """
        self._frozen_bases = True
        base = mozpath.basedir(path, self._sub_formatter.keys())
        relpath = mozpath.relpath(path, base) if base else path
        return base, relpath

    def add(self, path, content):
        base, relpath = self._get_base(path)
        if base is None:
            return self.copier.add(relpath, content)
        return self._sub_formatter[base].add(relpath, content)

    def add_manifest(self, entry):
        base, relpath = self._get_base(entry.base)
        assert base is not None
        return self._sub_formatter[base].add_manifest(entry.move(relpath))

    def add_interfaces(self, path, content):
        base, relpath = self._get_base(path)
        assert base is not None
        return self._sub_formatter[base].add_interfaces(relpath, content)

    def contains(self, path):
        assert "*" not in path
        base, relpath = self._get_base(path)
        if base is None:
            return self.copier.contains(relpath)
        return self._sub_formatter[base].contains(relpath)


class FlatFormatter(PiecemealFormatter):
    """
    Formatter for the flat package format.
    """

    def _add_base(self, base, addon=False):
        self._sub_formatter[base] = FlatSubFormatter(
            FileRegistrySubtree(base, self.copier)
        )


class FlatSubFormatter(object):
    """
    Sub-formatter for the flat package format.
    """

    def __init__(self, copier):
        assert isinstance(copier, (FileRegistry, FileRegistrySubtree))
        self.copier = copier
        self._chrome_db = {}

    def add(self, path, content):
        self.copier.add(path, content)

    def add_manifest(self, entry):
        # Store manifest entries in a single manifest per directory, named
        # after their parent directory, except for root manifests, all named
        # chrome.manifest.
        if entry.base:
            name = mozpath.basename(entry.base)
        else:
            name = "chrome"
        path = mozpath.normpath(mozpath.join(entry.base, "%s.manifest" % name))
        if not self.copier.contains(path):
            # Add a reference to the manifest file in the parent manifest, if
            # the manifest file is not a root manifest.
            if entry.base:
                parent = mozpath.dirname(entry.base)
                relbase = mozpath.basename(entry.base)
                relpath = mozpath.join(relbase, mozpath.basename(path))
                self.add_manifest(Manifest(parent, relpath))
            self.copier.add(path, ManifestFile(entry.base))

        if isinstance(entry, ManifestChrome):
            data = self._chrome_db.setdefault(entry.name, {})
            if isinstance(entry, ManifestMultiContent):
                entries = data.setdefault(entry.type, {}).setdefault(entry.id, [])
            else:
                entries = data.setdefault(entry.type, [])
            for e in entries:
                # Ideally, we'd actually check whether entry.flags are more
                # specific than e.flags, but in practice the following test
                # is enough for now.
                if entry == e:
                    errors.warn('"%s" is duplicated. Skipping.' % entry)
                    return
                if not entry.flags or e.flags and entry.flags == e.flags:
                    errors.fatal('"%s" overrides "%s"' % (entry, e))
            entries.append(entry)

        self.copier[path].add(entry)

    def add_interfaces(self, path, content):
        self.copier.add(path, content)
        self.add_manifest(
            ManifestInterfaces(mozpath.dirname(path), mozpath.basename(path))
        )

    def contains(self, path):
        assert "*" not in path
        return self.copier.contains(path)


class JarFormatter(PiecemealFormatter):
    """
    Formatter for the jar package format. Assumes manifest entries related to
    chrome are registered before the chrome data files are added. Also assumes
    manifest entries for resources are registered after chrome manifest
    entries.
    """

    def __init__(self, copier, compress=True):
        PiecemealFormatter.__init__(self, copier)
        self._compress = compress

    def _add_base(self, base, addon=False):
        if addon is True:
            jarrer = Jarrer(self._compress)
            self.copier.add(base + ".xpi", jarrer)
            self._sub_formatter[base] = FlatSubFormatter(jarrer)
        else:
            self._sub_formatter[base] = JarSubFormatter(
                FileRegistrySubtree(base, self.copier), self._compress
            )


class JarSubFormatter(PiecemealFormatter):
    """
    Sub-formatter for the jar package format. It is a PiecemealFormatter that
    dispatches between further sub-formatter for each of the jar files it
    dispatches the chrome data to, and a FlatSubFormatter for the non-chrome
    files.
    """

    def __init__(self, copier, compress=True):
        PiecemealFormatter.__init__(self, copier)
        self._frozen_chrome = False
        self._compress = compress
        self._sub_formatter[""] = FlatSubFormatter(copier)

    def _jarize(self, entry, relpath):
        """
        Transform a manifest entry in one pointing to chrome data in a jar.
        Return the corresponding chrome path and the new entry.
        """
        base = entry.base
        basepath = mozpath.split(relpath)[0]
        chromepath = mozpath.join(base, basepath)
        entry = (
            entry.rebase(chromepath)
            .move(mozpath.join(base, "jar:%s.jar!" % basepath))
            .rebase(base)
        )
        return chromepath, entry

    def add_manifest(self, entry):
        if isinstance(entry, ManifestChrome) and not urlparse(entry.relpath).scheme:
            chromepath, entry = self._jarize(entry, entry.relpath)
            assert not self._frozen_chrome
            if chromepath not in self._sub_formatter:
                jarrer = Jarrer(self._compress)
                self.copier.add(chromepath + ".jar", jarrer)
                self._sub_formatter[chromepath] = FlatSubFormatter(jarrer)
        elif isinstance(entry, ManifestResource) and not urlparse(entry.target).scheme:
            chromepath, new_entry = self._jarize(entry, entry.target)
            if chromepath in self._sub_formatter:
                entry = new_entry
        PiecemealFormatter.add_manifest(self, entry)


class OmniJarFormatter(JarFormatter):
    """
    Formatter for the omnijar package format.
    """

    def __init__(self, copier, omnijar_name, compress=True, non_resources=()):
        JarFormatter.__init__(self, copier, compress)
        self._omnijar_name = omnijar_name
        self._non_resources = non_resources

    def _add_base(self, base, addon=False):
        if addon:
            # Because add_base is always called with parents before children,
            # all the possible ancestry of `base` is already present in
            # `_sub_formatter`.
            parent_base = mozpath.basedir(base, self._sub_formatter.keys())
            rel_base = mozpath.relpath(base, parent_base)
            # If the addon is under a resource directory, package it in the
            # omnijar.
            parent_sub_formatter = self._sub_formatter[parent_base]
            if parent_sub_formatter.is_resource(rel_base):
                omnijar_sub_formatter = parent_sub_formatter._sub_formatter[
                    self._omnijar_name
                ]
                self._sub_formatter[base] = FlatSubFormatter(
                    FileRegistrySubtree(rel_base, omnijar_sub_formatter.copier)
                )
                return
            JarFormatter._add_base(self, base, addon)
        else:
            self._sub_formatter[base] = OmniJarSubFormatter(
                FileRegistrySubtree(base, self.copier),
                self._omnijar_name,
                self._compress,
                self._non_resources,
            )


class OmniJarSubFormatter(PiecemealFormatter):
    """
    Sub-formatter for the omnijar package format. It is a PiecemealFormatter
    that dispatches between a FlatSubFormatter for the resources data and
    another FlatSubFormatter for the other files.
    """

    def __init__(self, copier, omnijar_name, compress=True, non_resources=()):
        PiecemealFormatter.__init__(self, copier)
        self._omnijar_name = omnijar_name
        self._compress = compress
        self._non_resources = non_resources
        self._sub_formatter[""] = FlatSubFormatter(copier)
        jarrer = Jarrer(self._compress)
        self._sub_formatter[omnijar_name] = FlatSubFormatter(jarrer)

    def _get_base(self, path):
        base = self._omnijar_name if self.is_resource(path) else ""
        # Only add the omnijar file if something ends up in it.
        if base and not self.copier.contains(base):
            self.copier.add(base, self._sub_formatter[base].copier)
        return base, path

    def add_manifest(self, entry):
        base = ""
        if not isinstance(entry, ManifestBinaryComponent):
            base = self._omnijar_name
        formatter = self._sub_formatter[base]
        return formatter.add_manifest(entry)

    def is_resource(self, path):
        """
        Return whether the given path corresponds to a resource to be put in an
        omnijar archive.
        """
        if any(mozpath.match(path, p.replace("*", "**")) for p in self._non_resources):
            return False
        path = mozpath.split(path)
        if path[0] == "chrome":
            return len(path) == 1 or path[1] != "icons"
        if path[0] == "components":
            return path[-1].endswith((".js", ".xpt"))
        if path[0] == "res":
            return len(path) == 1 or (
                path[1] != "cursors"
                and path[1] != "touchbar"
                and path[1] != "MainMenu.nib"
            )
        if path[0] == "defaults":
            return len(path) != 3 or not (
                path[2] == "channel-prefs.js" and path[1] in ["pref", "preferences"]
            )
        if len(path) <= 2 and path[-1] == "greprefs.js":
            # Accommodate `greprefs.js` and `$ANDROID_CPU_ARCH/greprefs.js`.
            return True
        return path[0] in [
            "modules",
            "actors",
            "dictionaries",
            "hyphenation",
            "localization",
            "update.locale",
            "contentaccessible",
        ]