Skip to content

Instantly share code, notes, and snippets.

@mithrandi
Created February 20, 2016 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mithrandi/dd6011a3d24a3ff79376 to your computer and use it in GitHub Desktop.
Save mithrandi/dd6011a3d24a3ff79376 to your computer and use it in GitHub Desktop.
Legacy declaration generator
#!/usr/bin/env python
from twisted.python.reflect import namedAny
template = """
declareLegacyItem(
typeName=%r,
schemaVersion=%d,
attributes=dict(
%s))
"""
_attributeDefaults = [
('allowNone', True),
('default', None),
('defaultFactory', None)]
_attributeDefaultsDict = dict(_attributeDefaults)
def getAttributeAttributes(attr):
attrs = ((name, getattr(attr, name))
for name, default
in _attributeDefaults)
for name, value in attrs:
if value != _attributeDefaultsDict[name]:
if name == 'defaultFactory':
#raise ValueError('defaultFactory is hard: %r' % (attr,))
continue
yield name, value
def emitAttribute((attrName, attr)):
attrs = ['%s=%r' % (key, value)
for key, value
in getAttributeAttributes(attr)]
return '%s=%s(%s)' % (
attrName,
attr.__class__.__name__,
', '.join(attrs))
def legacyItemCode(itemClass):
calculatedAttributes = ',\n '.join(
map(emitAttribute, itemClass.getSchema()))
fmt = template % (itemClass.typeName, itemClass.schemaVersion,
calculatedAttributes)
return fmt
if __name__ == '__main__':
import sys
f = sys.stdout
f.write(legacyItemCode(namedAny(sys.argv[1])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment