/
dtd.py
77 lines (70 loc) · 2.61 KB
/
dtd.py
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
##############################################################################
#
# Copyright (c) 2007 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Generate a DTD from the code
"""
import six
import zope.schema
from z3c.rml import attr, document, occurence
occurence2Symbol = {
occurence.ZeroOrMore: '*',
occurence.ZeroOrOne: '?',
occurence.OneOrMore: '+',
}
def generateElement(name, signature):
if signature is None:
return ''
# Create the list of sub-elements.
subElementList = []
for occurence in signature.queryTaggedValue('directives', ()):
subElementList.append(
occurence.tag + occurence2Symbol.get(occurence.__class__, '')
)
fields = zope.schema.getFieldsInOrder(signature)
for attrName, field in fields:
if isinstance(field, attr.TextNode):
subElementList.append('#PCDATA')
break
subElementList = ','.join(subElementList)
if subElementList:
subElementList = ' (' + subElementList + ')'
text = '\n<!ELEMENT %s%s>' %(name, subElementList)
# Create a list of attributes for this element.
for attrName, field in fields:
# Ignore text nodes, since they are not attributes.
if isinstance(field, attr.TextNode):
continue
# Create the type
if isinstance(field, attr.Choice):
type = '(' + '|'.join(field.choices.keys()) + ')'
else:
type = 'CDATA'
# Create required flag
if field.required:
required = '#REQUIRED'
else:
required = '#IMPLIED'
# Put it all together
text += '\n<!ATTLIST %s %s %s %s>' %(name, attrName, type, required)
text += '\n'
# Walk through all sub-elements, creating th eDTD entries for them.
for occurence in signature.queryTaggedValue('directives', ()):
text += generateElement(occurence.tag, occurence.signature)
return text
def generate(useWrapper=False):
text = generateElement('document', document.Document.signature)
if useWrapper:
text = '<!DOCTYPE RML [\n%s]>\n' %text
return text
def main():
six.print_(generate())