File size: 12,542 Bytes
a65138c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# -*- coding: utf-8 -*-
from __future__ import with_statement
import logging
import os.path
from storage import open_storage
from storage import resolve_path
from storage import makedirs_to_file
from storage import put_file
from storage import copy_file
from storage import iterate_files_recursively
from storage._zipfile import ZipFileStorage
from storage.fs import FileSystemStorage
from manifest import Manifest
from description import Description


logger = logging.getLogger(__name__)


def is_package(folder):
    if 'META-INF' not in folder:
        return False
    if 'manifest.xml' not in folder['META-INF']:
        return False
    return True


MANIFEST_PATH = os.path.join('META-INF', 'manifest.xml')
DESCRIPTION_PATH = 'description.xml'


def add_file(stg, manifest, path, full_path, media_type):
    ''' add a file into the storage and manifest.

    :param stg: a storage
    :param manifest: an instance of Manifest
    :param path: path to the file on the filesystem.
    :param full_path: ``manifest:full-path`` value of ``manifest:file-entry``
    :param media_type: ``manifest:media-type`` value of ``manifest:file-entry``
    '''
    node = makedirs_to_file(stg, full_path)
    put_file(node, path)
    manifest[full_path] = media_type
    return node


def add_component_file(stg, manifest, path, full_path, type, platform=None):
    ''' add a component file.

    :param stg: a storage
    :param manifest: an instance of Manifest
    :param path: path to the file on the filesystem.
    :param full_path: ``manifest:full-path`` value of ``manifest:file-entry``
    :param type: ``native``, ``Java``, ``Python`` or None
    :param platform: supposed platform to run this component.

    if ``type`` is None, this component is meant to be registered with
    `Passive Component Registration
    <http://wiki.openoffice.org/wiki/Documentation/DevGuide/Extensions/Passive_Component_Registration>`_
    and the file specified with ``path`` should be an XML file, which is
    defined in the document above.

    For more informations, see `File Format
    <http://wiki.openoffice.org/wiki/Documentation/DevGuide/Extensions/File_Format>`_.
    '''
    mimetype = 'application/vnd.sun.star.uno-component'
    if type:
        mimetype += '; ' + type
    if platform:
        mimetype += '; ' + platform
    return add_file(stg, manifest, path, full_path, mimetype=mimetype)


def add_type_library(stg, manifest, path, full_path, type):
    ''' add a UNO type library.

    :param stg: a storage
    :param manifest: an instance of Manifest
    :param type: ``RDB`` or ``Java``
    '''

    typelib_extensions = dict(RDB='.rdb', Java='.jar')

    if type not in typelib_extensions.keys():
        raise ValueError('type: unsupported value of %r' % type)

    if not full_path.lower().endswith(typelib_extensions[type]):
        msg = 'adding %r type library %r with name %r: really intended?'
        logger.warning(msg, type, path, full_path)

    mimetype = 'application/vnd.sun.star.uno-typelibrary'
    mimetype += '; type=' + type
    return add_file(stg, manifest, path, full_path, mimetype)


def add_basic_library(stg, manifest, path, full_path):
    ''' add a basic library

    :param stg: a storage
    :param manifest: an instance of Manifest
    '''
    mimetype = 'application/vnd.sun.star.basic-library'
    return add_file(stg, manifest, path, full_path, mimetype=mimetype)


def add_dialog_library(stg, manifest, path, full_path):
    ''' add a dialog library

    :param stg: a storage
    :param manifest: an instance of Manifest
    '''
    mimetype = 'application/vnd.sun.star.dialog-library'
    return add_file(stg, manifest, path, full_path, mimetype=mimetype)


def add_configuration_data_file(stg, manifest, path, full_path):
    ''' add a configuration data file.

    :param stg: a storage
    :param manifest: an instance of Manifest
    '''
    mimetype = 'application/vnd.sun.star.configuration-data'
    return add_file(stg, manifest, path, full_path, mimetype=mimetype)


def add_configuration_schema_file(stg, manifest, path, full_path):
    ''' add a configuration schema file.

    :param stg: a storage
    :param manifest: an instance of Manifest
    '''
    mimetype = 'application/vnd.sun.star.configuration-schema'
    return add_file(stg, manifest, path, full_path, mimetype=mimetype)


def build(package_path, manifest, description, files=dict(),
          storage_factory=ZipFileStorage):
    ''' Build a OXT Package.

    :param package_path: path to an .oxt package to be built
    :param manifest: an instance of Manifest
    :param description: an instance of Description
    :param files: package files, in a form of (path, node) dict
    :param storage_factory: storage factory for the package.
                            Default to ZipFileStorage
    '''

    assert not any(node is None for node in files.values())
    assert all(path in files for path in manifest)
    assert all(path in files for path in description.required_files())

    logger.info('creating %s', package_path)
    with storage_factory(package_path, 'w') as stg:
        logger.info('writing %s', MANIFEST_PATH)
        manifest_node = makedirs_to_file(stg, MANIFEST_PATH)
        with manifest_node.open('w') as f:
            manifest.dump(f)

        logger.info('writing %s', DESCRIPTION_PATH)
        desc_node = makedirs_to_file(stg, DESCRIPTION_PATH)
        with desc_node.open('w') as f:
            description.write(f)

        for path in sorted(files):
            node = files[path]
            logger.info('writing %s', path)
            dest = makedirs_to_file(stg, path)
            copy_file(node, dest)


def build_from(package_path,
               src_folder,
               manifest_path=None,
               description_path=None,
               files=[],
               excludes=[],
               storage_factory=ZipFileStorage):

    if manifest_path:
        with file(manifest_path) as f:
            manifest = Manifest()
            manifest.load(f)
    else:
        node = resolve_path(src_folder, MANIFEST_PATH)
        if node:
            with node.open() as f:
                manifest = Manifest()
                manifest.load(f)
        else:
            logger.error('%s: not found' % MANIFEST_PATH)
            raise IOError('%s: not found' % MANIFEST_PATH)

    if description_path:
        with file(description_path) as f:
            description = Description.parse(f)
    else:
        node = resolve_path(src_folder, DESCRIPTION_PATH)
        if node:
            with node.open() as f:
                description = Description.parse(f)
        else:
            raise IOError('%s: not found' % DESCRIPTION_PATH)

    package_path = make_output_path(package_path, description)
    package_files = dict()

    from itertools import chain
    required_files = chain(manifest, description.required_files())
    for path in required_files:
        node = resolve_path(src_folder, path)
        if node is None:
            raise IOError('%s: not found' % path)
        package_files[path] = node

    files = ((path, resolve_path(src_folder, path)) for path in files)
    files = expand_folders(files)
    files = exclude_files(excludes, files)
    package_files.update(files)

    return build(package_path, manifest, description, package_files,
                 storage_factory=storage_factory)


def make_output_path(path, desc=None):
    if os.path.isdir(path):
        dirname = path
        name = ''
    else:
        dirname, name = os.path.split(path)

    # default name will be used if not given
    if name == '':
        if desc is None:
            raise ValueError('%s: invalid path' % path)
        name = package_name_from_desc(desc)

    return os.path.join(dirname, name)


def package_name_from_desc(desc):
    id = desc.identifier
    version = desc.version
    if version:
        return '-'.join([id, version]) + '.oxt'
    else:
        return id + '.oxt'


def expand_folders(resolved_nodes):
    for path, node in resolved_nodes:
        if hasattr(node, '__iter__'):
            for path, node in iterate_files_recursively(node, path):
                yield path, node
        else:
            yield path, node


def exclude_files(patterns, resolved_nodes):
    from fnmatch import fnmatch
    for path, node in resolved_nodes:
        excluded = False
        for pat in patterns:
            if fnmatch(path, pat):
                logger.info('exclude %s (by %s)', path, pat)
                excluded = True
        if not excluded:
            yield path, node


def init_main():
    doc = '''Usage: oxt-pkg-init [options] <package-path>

    --help      Print this screen.
    '''

    from docopt import docopt
    args = docopt(doc)
    logging.basicConfig(level=logging.INFO)

    package_path = args['<package-path>']

    manifest = Manifest()
    description = Description()

    with open_storage(package_path, 'w') as stg:
        with makedirs_to_file(stg, MANIFEST_PATH).open('w') as f:
            manifest.dump(f)
        with makedirs_to_file(stg, DESCRIPTION_PATH).open('w') as f:
            description.write(f)


def show_main():
    doc = '''Usage: oxt-pkg-show [options] <package-path>

    --help      Print this screen.
    '''

    from docopt import docopt
    args = docopt(doc)
    logging.basicConfig(level=logging.INFO)

    package_path = args['<package-path>']
    with open_storage(package_path) as pkg:
        with resolve_path(pkg, MANIFEST_PATH).open() as f:
            manifest = Manifest()
            manifest.load(f)

        with resolve_path(pkg, DESCRIPTION_PATH).open() as f:
            description = Description.parse(f)

        from description import print_human_readable
        print_human_readable(description, pkg)

        for path in manifest:
            item = manifest[path]
            print path, item['media-type'],
            node = resolve_path(pkg, path)
            if node:
                print '-- OK'
            else:
                print '-- MISSING'


def build_main():
    doc = '''Usage: oxt-pkg-build [options] <src-folder> <add-files>...

    -o OUTPUT-PATH                  Output path
    -m MANIFEST                     META-INF/manifest.xml
    -d DESCRIPT                     description.xml
    -E EXCLUDE, --exclude=EXCLUDE   exclude patterns; separated by %r.
                --help              Print this screen.

    <src-folder>                    root folder containing package files
    <add-files>                     additional files (relative to <src-folder>)
    ''' % os.pathsep

    from docopt import docopt
    args = docopt(doc)
    logging.basicConfig(level=logging.INFO)

    src_folder_path = args['<src-folder>']
    add_files = args['<add-files>']
    output_path = args['-o'] or '.'
    manifest_path = args['-m']
    description_path = args['-d']
    excludes = args['--exclude'] or ''
    excludes = excludes.strip().split(os.pathsep)

    with FileSystemStorage(src_folder_path) as src_folder:
        build_from(output_path,
                   src_folder,
                   manifest_path=manifest_path,
                   description_path=description_path,
                   files=add_files,
                   excludes=excludes)


def check_main():
    doc = '''Usage: oxt-pkg-show [options] <package-path>

    --help      Print this screen.
    '''

    from docopt import docopt
    args = docopt(doc)
    logging.basicConfig(level=logging.INFO)

    package_path = args['<package-path>']
    with open_storage(package_path) as pkg:
        with resolve_path(pkg, MANIFEST_PATH).open() as f:
            manifest = Manifest()
            manifest.load(f)

        with resolve_path(pkg, DESCRIPTION_PATH).open() as f:
            description = Description.parse(f)

        missing = dict()

        for path in manifest:
            node = resolve_path(pkg, path)
            if node is None:
                missing[path] = MANIFEST_PATH

        for path in description.required_files():
            node = resolve_path(pkg, path)
            if node is None:
                missing[path] = DESCRIPTION_PATH

        if missing:
            for path in sorted(missing):
                referer = missing[path]
                logger.error('%s: MISSING (refered in %s)',
                             path, referer)
            raise SystemExit(1)
        else:
            logger.info('%s: OK, identifier=%s, version=%s', package_path,
                        description.identifier, description.version)