move RichString and co to yams, keeping only a small monkeypatch for cw-page-template here
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Thu, 23 Jul 2009 15:57:15 +0200
changeset 2459 d088d0ff48a1
parent 2458 4d114865098f
child 2460 ce1a7ffc6c90
move RichString and co to yams, keeping only a small monkeypatch for cw-page-template here
common/mttransforms.py
entities/__init__.py
goa/skel/schema.py
schema.py
schemas/bootstrap.py
schemas/workflow.py
server/test/data/migrschema/Folder2.py
server/test/data/schema.py
web/formfields.py
--- a/common/mttransforms.py	Thu Jul 23 15:33:03 2009 +0200
+++ b/common/mttransforms.py	Thu Jul 23 15:57:15 2009 +0200
@@ -46,8 +46,8 @@
     from cubicweb.ext.tal import compile_template
 except ImportError:
     HAS_TAL = False
-    from cubicweb.schema import FormatConstraint
-    FormatConstraint.need_perm_formats.remove('text/cubicweb-page-template')
+    from cubicweb import schema
+    schema.NEED_PERM_FORMATS.remove('text/cubicweb-page-template')
 
 else:
     HAS_TAL = True
--- a/entities/__init__.py	Thu Jul 23 15:33:03 2009 +0200
+++ b/entities/__init__.py	Thu Jul 23 15:57:15 2009 +0200
@@ -15,7 +15,6 @@
 from cubicweb import Unauthorized, typed_eid
 from cubicweb.entity import Entity
 from cubicweb.utils import dump_class
-from cubicweb.schema import FormatConstraint
 
 from cubicweb.interfaces import IBreadCrumbs, IFeed
 
--- a/goa/skel/schema.py	Thu Jul 23 15:33:03 2009 +0200
+++ b/goa/skel/schema.py	Thu Jul 23 15:57:15 2009 +0200
@@ -5,7 +5,6 @@
 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
 :license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses
 """
-from cubicweb.schema import format_constraint
 
 class Blog(EntityType):
     title = String(maxsize=50, required=True)
@@ -14,8 +13,6 @@
 class BlogEntry(EntityType):
     title = String(maxsize=100, required=True)
     publish_date = Date(default='TODAY')
-    text_format = String(meta=True, internationalizable=True, maxsize=50,
-                         default='text/rest', constraints=[format_constraint])
-    text = String(fulltextindexed=True)
+    text = RichString(fulltextindexed=True)
     category = String(vocabulary=('important','business'))
     entry_of = SubjectRelation('Blog', cardinality='?*')
--- a/schema.py	Thu Jul 23 15:33:03 2009 +0200
+++ b/schema.py	Thu Jul 23 15:57:15 2009 +0200
@@ -17,7 +17,7 @@
 from logilab.common.deprecation import obsolete
 from logilab.common.compat import any
 
-from yams import BadSchemaDefinition, buildobjs as ybo
+from yams import BadSchemaDefinition, buildobjs as ybo, constraints
 from yams.schema import Schema, ERSchema, EntitySchema, RelationSchema
 from yams.constraints import BaseConstraint, StaticVocabularyConstraint
 from yams.reader import CONSTRAINTS, PyFileReader, SchemaLoader, \
@@ -62,50 +62,6 @@
         etype = ETYPE_NAME_MAP[etype]
     return etype
 
-
-## cubicweb provides a RichString class for convenience
-class RichString(ybo.String):
-    """Convenience RichString attribute type
-    The following declaration::
-
-      class Card(EntityType):
-          content = RichString(fulltextindexed=True, default_format='text/rest')
-
-    is equivalent to::
-
-      class Card(EntityType):
-          content_format = String(internationalizable=True,
-                                  default='text/rest', constraints=[format_constraint])
-          content  = String(fulltextindexed=True)
-    """
-    def __init__(self, default_format='text/plain', format_constraints=None, **kwargs):
-        self.default_format = default_format
-        self.format_constraints = format_constraints or [format_constraint]
-        super(RichString, self).__init__(**kwargs)
-
-PyFileReader.context['RichString'] = yobsolete(RichString)
-
-## need to monkeypatch yams' _add_relation function to handle RichString
-yams_add_relation = ybo._add_relation
-@monkeypatch(ybo)
-def _add_relation(relations, rdef, name=None, insertidx=None):
-    if isinstance(rdef, RichString):
-        format_attrdef = ybo.String(internationalizable=True,
-                                    default=rdef.default_format, maxsize=50,
-                                    constraints=rdef.format_constraints)
-        yams_add_relation(relations, format_attrdef, name+'_format', insertidx)
-    yams_add_relation(relations, rdef, name, insertidx)
-
-
-@monkeypatch(ybo.EntityType, methodname='add_relation')
-@classmethod
-def add_relation(cls, rdef, name=None):
-    ybo.add_relation_function(cls, rdef, name)
-    if isinstance(rdef, RichString) and not rdef in cls._defined:
-        format_attr_name = (name or rdef.name) + '_format'
-        rdef = cls.get_relations(format_attr_name).next()
-        cls._ensure_relation_type(rdef)
-
 def display_name(req, key, form=''):
     """return a internationalized string for the key (schema entity or relation
     name) in a given form
@@ -926,49 +882,22 @@
                 self.handle_file(filepath)
 
 
+set_log_methods(CubicWebSchemaLoader, getLogger('cubicweb.schemaloader'))
+set_log_methods(BootstrapSchemaLoader, getLogger('cubicweb.bootstrapschemaloader'))
+set_log_methods(RQLExpression, getLogger('cubicweb.schema'))
+
 # _() is just there to add messages to the catalog, don't care about actual
 # translation
 PERM_USE_TEMPLATE_FORMAT = _('use_template_format')
-
-class FormatConstraint(StaticVocabularyConstraint):
-    need_perm_formats = [_('text/cubicweb-page-template')]
-
-    regular_formats = (_('text/rest'),
-                       _('text/html'),
-                       _('text/plain'),
-                       )
-    def __init__(self):
-        pass
-
-    def serialize(self):
-        """called to make persistent valuable data of a constraint"""
-        return None
+NEED_PERM_FORMATS = [_('text/cubicweb-page-template')]
 
-    @classmethod
-    def deserialize(cls, value):
-        """called to restore serialized data of a constraint. Should return
-        a `cls` instance
-        """
-        return cls()
-
-    def vocabulary(self, entity=None, req=None):
-        if req is None and entity is not None:
-            req = entity.req
-        if req is not None and req.user.has_permission(PERM_USE_TEMPLATE_FORMAT):
-            return self.regular_formats + tuple(self.need_perm_formats)
-        return self.regular_formats
-
-    def __str__(self):
-        return 'value in (%s)' % u', '.join(repr(unicode(word)) for word in self.vocabulary())
-
-
-format_constraint = FormatConstraint()
-CONSTRAINTS['FormatConstraint'] = FormatConstraint
-PyFileReader.context['format_constraint'] = format_constraint
-
-set_log_methods(CubicWebSchemaLoader, getLogger('cubicweb.schemaloader'))
-set_log_methods(BootstrapSchemaLoader, getLogger('cubicweb.bootstrapschemaloader'))
-set_log_methods(RQLExpression, getLogger('cubicweb.schema'))
+@monkeypatch(constraints.FormatConstraint)
+def vocabulary(self, entity=None, req=None):
+    if req is None and entity is not None:
+        req = entity.req
+    if req is not None and req.user.has_permission(PERM_USE_TEMPLATE_FORMAT):
+        return self.regular_formats + tuple(NEED_PERM_FORMATS)
+    return self.regular_formats
 
 # XXX monkey patch PyFileReader.import_erschema until bw_normalize_etype is
 # necessary
--- a/schemas/bootstrap.py	Thu Jul 23 15:33:03 2009 +0200
+++ b/schemas/bootstrap.py	Thu Jul 23 15:57:15 2009 +0200
@@ -9,8 +9,8 @@
 _ = unicode
 
 from yams.buildobjs import (EntityType, RelationType, SubjectRelation,
-                            ObjectRelation, String, Boolean, Int)
-from cubicweb.schema import RichString, RQLConstraint
+                            ObjectRelation, RichString, String, Boolean, Int)
+from cubicweb.schema import RQLConstraint
 from cubicweb.schemas import META_ETYPE_PERMS, META_RTYPE_PERMS
 
 # not restricted since as "is" is handled as other relations, guests need
--- a/schemas/workflow.py	Thu Jul 23 15:33:03 2009 +0200
+++ b/schemas/workflow.py	Thu Jul 23 15:57:15 2009 +0200
@@ -9,8 +9,8 @@
 _ = unicode
 
 from yams.buildobjs import (EntityType, RelationType, SubjectRelation,
-                            ObjectRelation, String)
-from cubicweb.schema import RichString, RQLConstraint
+                            ObjectRelation, RichString, String)
+from cubicweb.schema import RQLConstraint
 from cubicweb.schemas import META_ETYPE_PERMS, META_RTYPE_PERMS
 
 class State(EntityType):
--- a/server/test/data/migrschema/Folder2.py	Thu Jul 23 15:33:03 2009 +0200
+++ b/server/test/data/migrschema/Folder2.py	Thu Jul 23 15:57:15 2009 +0200
@@ -5,7 +5,6 @@
 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
 :license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses
 """
-from cubicweb.schema import format_constraint
 
 class Folder2(MetaUserEntityType):
     """folders are used to classify entities. They may be defined as a tree.
@@ -14,9 +13,7 @@
     """
     name = String(required=True, indexed=True, internationalizable=True,
                   constraints=[UniqueConstraint(), SizeConstraint(64)])
-    description_format = String(meta=True, internationalizable=True,
-                                default='text/rest', constraints=[format_constraint])
-    description = String(fulltextindexed=True)
+    description = RichString(fulltextindexed=True)
 
     filed_under2 = BothWayRelation(
         SubjectRelation('Folder2', description=_("parent folder")),
--- a/server/test/data/schema.py	Thu Jul 23 15:33:03 2009 +0200
+++ b/server/test/data/schema.py	Thu Jul 23 15:57:15 2009 +0200
@@ -5,7 +5,6 @@
 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
 :license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses
 """
-from cubicweb.schema import format_constraint
 
 class Affaire(WorkflowableEntityType):
     permissions = {
@@ -20,10 +19,8 @@
                  constraints=[SizeConstraint(16)])
     sujet = String(fulltextindexed=True,
                    constraints=[SizeConstraint(256)])
-    descr_format = String(meta=True, internationalizable=True,
-                                default='text/rest', constraints=[format_constraint])
-    descr = String(fulltextindexed=True,
-                   description=_('more detailed description'))
+    descr = RichString(fulltextindexed=True,
+                       description=_('more detailed description'))
 
     duration = Int()
     invoiced = Int()
--- a/web/formfields.py	Thu Jul 23 15:33:03 2009 +0200
+++ b/web/formfields.py	Thu Jul 23 15:57:15 2009 +0200
@@ -11,9 +11,9 @@
 from datetime import datetime
 
 from logilab.mtconverter import xml_escape
-from yams.constraints import SizeConstraint, StaticVocabularyConstraint
+from yams.constraints import (SizeConstraint, StaticVocabularyConstraint,
+                              FormatConstraint)
 
-from cubicweb.schema import FormatConstraint
 from cubicweb.utils import ustrftime, compute_cardinality
 from cubicweb.common import tags, uilib
 from cubicweb.web import INTERNAL_FIELD_VALUE