summaryrefslogtreecommitdiffstats
path: root/ontogen.py
blob: ca1cd796f22063bd078d3f6ace9575ea99be3447 (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
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
# vim: set fileencoding=UTF-8:
# Copyright 2013 Red Hat, Inc.
# Author: Jan Pokorný <jpokorny at redhat dot com>
# Licensed under LGPL v2.1 (the same as original ns-schema.xsl)

from sys import modules, stdout, stderr
from datetime import date
from textwrap import TextWrapper, dedent
from os import extsep, getcwd, mkdir, symlink, remove
from os.path import basename, dirname, exists, isdir, islink, join, splitext, \
                    sep as pathsep
from subprocess import call
from shlex import split
#import codecs

import logging

logging.basicConfig()
log = logging.getLogger(__name__)


#VERSIONSEP = sep  # non-unix paths -> problems
VERSIONSEP = '/'
ONTSEP = '#'
INDEX = 'index.html'

TEMPLATE_GENSHI = join(dirname(__file__), 'ontogen.template')
TEMPLATE_XSLT = join(dirname(__file__), 'ns-schema.xsl')
TEXT_INDENT = '      '
TW = TextWrapper(initial_indent=TEXT_INDENT, subsequent_indent=TEXT_INDENT)
tw = lambda x: TW.fill(x)
twd = lambda x: tw(dedent(x))
norm = lambda x: reduce(
    lambda a, b: a and a + (b.islower() and b or '-' + b.lower()) or b.lower(),
    x,
    ''
).replace('_', '-')


#
# Helpers
#


# classics: http://stackoverflow.com/a/1383402
class ClassProperty(property):
    def __get__(self, this, owner):
        return self.fget.__get__(None, owner)()


# another common fixer (adjusted): http://stackoverflow.com/a/13937525
class InheritDocstring(type):
    """Allows docstrings to be inherited (restricted to external classes)"""
    def __init__(this, name, bases, attrs):
        if __name__ not in (this.__module__, this.__base__.__module__):
            if not getattr(this, '__doc__', None):
                this.__doc__ = super(this, this).__doc__
        super(InheritDocstring, InheritDocstring).__init__(this, name,
                                                           bases, attrs)


def custom_symlink(source, link_name, report=False):
    """symlink + overwriting (unlink-new) of existing symlinks"""
    if exists(link_name):
        if islink(link_name):
            remove(link_name)
        else:
            raise RuntimeError('{0} is in our way'.format(link_name))
    if report is not False:
        print '{0}: {1}'.format(report, link_name)
    symlink(source, link_name)


#
# Pure documentation level
#


class Example(object):
    """Important data regarding examples"""
    @ClassProperty
    @classmethod
    def comment(this):
        return tw('\n'.join(this.__doc__.strip().splitlines()[:1]))

    @ClassProperty
    @classmethod
    def pfx(this):
        return ''

    @ClassProperty
    @classmethod
    def code(this):
        return '\n'.join(map(str.rstrip, this.__doc__.strip().splitlines()[2:]))

    @ClassProperty
    @classmethod
    def image(this):
        return ''


# combine this "example" with Makefile to trigger the magic
class ExampleSelfFigureProto(type):
    def __new__(self, ontology):
        base = ontology.base

        class ExampleSelfFigure(Example):
            """Illustrative figure of the vocabulary"""
            image_full = ontology.version + VERSIONSEP + base + extsep + 'svg'
            image = base + extsep + 'svg'  # referenced from html
            symlink = base + extsep + 'svg'

        return ExampleSelfFigure


#
# Abstract RDF level
#


class RDFEntity(object):
    """Common base for property, class and ontology"""

    __metaclass__ = InheritDocstring

    @ClassProperty
    @classmethod
    def id(this):
        return ONTSEP + norm(this.__name__)

    @ClassProperty
    @classmethod
    def namespaces(this):
        return {}

    @ClassProperty
    @classmethod
    def documentation(this):
        return this.__doc__

    @ClassProperty
    @classmethod
    def label(this):
        return '\n'.join(this.documentation.strip().splitlines()[:1]).strip()

    @ClassProperty
    @classmethod
    def comment(this):
        return '\n\n'.join(
            map(
                twd,
                '\n'.join(map(
                    str.rstrip,
                    this.documentation.strip().splitlines()[2:])).split('\n\n')
            )
        )

    @ClassProperty
    @classmethod
    def status(this):
        return ''


#
# RDF entities
#


class Class(RDFEntity):
    """Important data regarding RDF class"""

    # decorators

    @classmethod
    def inDomainOf(this, prop):
        """Tells that decorated Property has decorating Class as a domain"""
        assert issubclass(prop, Property)
        if not prop.domain:
            prop.domain = this.id
        else:
            log.warning('{0} already has domain set'
                        .format(prop))
        return prop

    @classmethod
    def inRangeOf(this, prop):
        """Tells that decorated Property has decorating Class as a range"""
        assert issubclass(prop, Property)
        if not prop.range:
            prop.range = this.id
        else:
            log.warning('{0} already has range set'
                        .format(prop))
        return prop

    # members

    @ClassProperty
    @classmethod
    def subClassOf(this):
        return '' if this.__base__ == Class else this.__base__.id


class Property(RDFEntity):
    """Important data regarding RDF property"""

    # members

    @ClassProperty
    @classmethod
    def domain(this):
        return ''

    @ClassProperty
    @classmethod
    def range(this):
        return ''

    @ClassProperty
    @classmethod
    def subPropertyOf(this):
        return '' if this.__base__ == Property else this.__base__.id


class Ontology(RDFEntity):
    """Important data regarding ontology"""

    # decorators

    @classmethod
    def supersededBy(this, onto):
        """Tells that decorated Ontology supersedes the decorating Ontology"""
        assert issubclass(onto, Ontology)
        if onto.priorVersion is None:
            onto.priorVersion = this
        else:
            log.warning('{0} already has priorVersion set'.format(onto))
        return onto

    # members - override

    @ClassProperty
    @classmethod
    def documentation(this):
        ret = getattr(this, '__doc__', '') or modules[this.__module__].__doc__
        return ret

    # members

    @ClassProperty
    @classmethod
    def base_uri(this):
        module = modules[this.__module__]
        if hasattr(module, 'base_uri'):
            return module.base_uri
        raise NotImplementedError

    @ClassProperty
    @classmethod
    def version(this):
        # sorting key
        raise NotImplementedError

    @ClassProperty
    @classmethod
    def base_uri_full(this):
        return this.base_uri + VERSIONSEP + this.version

    @ClassProperty
    @classmethod
    def base(this):
        # TODO: cache me please?
        return this.base_uri.rpartition('/')[2]

    @ClassProperty
    @classmethod
    def creator(this):
        module = modules[this.__module__]
        if hasattr(module, '__author__'):
            return module.__author__
        return ''

    @ClassProperty
    @classmethod
    def issued(this):
        return ''

    @ClassProperty
    @classmethod
    def modified(this):
        return date.today().isoformat()

    @ClassProperty
    @classmethod
    def priorVersion(this):
        return None

    @ClassProperty
    @classmethod
    def classes(this):
        return []

    @ClassProperty
    @classmethod
    def properties(this):
        return []

    @ClassProperty
    @classmethod
    def examples(this):
        return []

    # extras

    @classmethod
    def valid(this):
        proper_subclasses = all((
            all(issubclass(c, Class) for c in this.classes),
            all(issubclass(p, Property) for p in this.properties),
            all(issubclass(e, Example) for e in this.examples),
        ))
        if not proper_subclasses:
            log.warning('Not proper subclasses used')

        ids = [
            x.id for x in
                reduce(lambda a, b: a + b,
                       (getattr(this, ent_name) for ent_name in ('classes',
                                                                 'properties')))
        ]
        unique_ids = len(ids) == len(set(ids))
        if not unique_ids:
            log.warning('Not unique IDs used')

        return proper_subclasses and unique_ids

    @classmethod
    def _prepare_targets(this):
        base = this.base
        version = this.version
        if not exists(version):
            mkdir(version)
        elif not isdir(version):
            raise RuntimeError('{0} is not a directory'.format(version))
        return (version + VERSIONSEP + base + extsep + 'rdf',
                base + extsep + 'rdf')

    @classmethod
    def gendoc(this, infile, outfile, template=TEMPLATE_XSLT):
        """Generate HTML as per RDF (ns-schema.xsl wrapper)"""
        cmd = 'xsltproc --stringparam xmlfile {reference} -o {outfile}' \
              ' {template} {infile}'.format(
                  reference=basename(infile),
                  infile=infile,
                  outfile=outfile,
                  template=template
              )
        log.debug('running {0}'.format(split(cmd)))
        if call(split(cmd)):
            raise RuntimeError('Something went wrong while running {0}; pwd={1}'
                               .format(cmd, getcwd()))

    @classmethod
    def generate(this, ontologies=(), template=None, outfile='-', gendoc=True):
        """Generate RDF as per declarations"""
        from genshi.template import MarkupTemplate

        namespaces = {}
        for ns, ns_uri in reduce(
                lambda a, b: a + b.namespaces.items(),
                [this] + this.classes + this.properties,
                []
        ):
            if namespaces.setdefault('xmlns:' + ns, ns_uri) != ns_uri:
                print >>stderr, 'NS clash: {0} vs {1}'.format(
                                namespaces['xmlns:' + ns], ns_uri)

        tmpl_filename = template or TEMPLATE_GENSHI
        tmpl_fileobj = open(tmpl_filename)
        #tmpl_fileobj = codecs.open(tmpl_filename, encoding='UTF-8')
        tmpl = MarkupTemplate(tmpl_fileobj, tmpl_filename)
        tmpl_fileobj.close()

        symfile = None
        if outfile is '-':
            outobj = stdout
        else:
            if outfile == 'AUTO':
                outfile, symfile = this._prepare_targets()
            outobj = open(outfile, "w")

        tmpldict = dict(Ontology=this, namespaces=namespaces)
        print >>outobj, \
              tmpl.generate(**tmpldict).render('xml', strip_whitespace=False)
        outobj.flush()  # usually failing without this

        # htmldoc
        htmlfile = None
        if gendoc and outfile != '-':
            htmlfile = join(dirname(outfile), INDEX)
            this.gendoc(outfile, htmlfile)

        # symlink to base (non-versioned) only for the newest ontology
        if ontologies[-1] is this and symfile:
            custom_symlink(outfile, symfile, 'output')
            if htmlfile:
                custom_symlink(htmlfile, splitext(symfile)[0] + extsep + 'html',
                               'html')
                for ex in [e for e in this.examples if e.image]:
                    img = ex.image
                    if ex.__name__ == 'ExampleSelfFigure':
                        custom_symlink(ex.image_full, ex.symlink, 'self-figure')
                    elif not pathsep in img:
                        custom_symlink(join(this.base, img), img, 'image')

        if outobj is not stdout:
            outobj.close()

    @classmethod
    def __str__(this):
        this.generate()


class PrependFigure(InheritDocstring):
    """Attaches self-figure (to be provided externally) as a first example"""
    def __new__(this, name, bases, attrs):
        ret = super(PrependFigure, PrependFigure).__new__(this, name, bases,
                                                          attrs)
        if attrs['__module__'] == __name__:
            return ret  # nothing more to do here for internal classes
        try:
            if all(map(lambda x: isinstance(x, basestring),
                       map(lambda x: getattr(ret, x, None),
                           ('base_uri_full',))
            )):
                setattr(ret, 'examples', [ExampleSelfFigureProto(ret)]
                                         + list(getattr(ret, 'examples', ())))
        except NotImplementedError:
            pass
        finally:
            return ret


class OntologyWithFigure(Ontology):
    __metaclass__ = PrependFigure


#
# Generalized view
#

class Ontologies(object):
    """Groups multiple versions of ontologies (presumably of the same base)"""
    def __init__(self, ontologies=()):
        self._ontologies = []
        if ontologies:
            self.include(*ontologies)

    # decorators

    def include(self, *ontologies):
        assert all(map(lambda o: o.valid(), ontologies))
        assert reduce(lambda a, b: issubclass(a, b) or issubclass(b, a),
                      ontologies)
        map(lambda a: setattr(a, '_final', True), ontologies)
        merge = self._ontologies + list(ontologies)
        self._ontologies = list(sorted(set(merge), key=lambda o: o.version))
        # make it decorator-compatible
        return (lambda first=None, *others: first)(*ontologies)

    # members

    def generate_latest(self, **kwargs):
        self._ontologies[-1].generate(tuple(self._ontologies), **kwargs)