[server] Port BFSS to py3k
The BFSS API changes in python 3:
* 'defaultdir' MUST be a unicode object
* 'fsencoding' MUST NOT be set
In python 2, fsencoding handles both the encoding of file paths on the
file system (utf-8 by default, but the system may actually be using
something else) and the encoding of file paths that will be stored in
the database.
So in python 3, we wipe the slate clean:
* rely on sys.getfilesystemencoding() to convert unicode objects to
bytes
* always encode paths to utf-8 for storage in the database
Caveat emptor / here be dragons:
* sys.getfilesystemencoding() depends on the current locale, which
therefore MUST be set properly
* when migrating an existing instance from py2 to py3, one MAY need
to reencode file paths stored in the database
# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr## This file is part of CubicWeb.## CubicWeb is free software: you can redistribute it and/or modify it under the# terms of the GNU Lesser General Public License as published by the Free# Software Foundation, either version 2.1 of the License, or (at your option)# any later version.## CubicWeb is distributed in the hope that it will be useful, but WITHOUT# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more# details.## You should have received a copy of the GNU Lesser General Public License along# with CubicWeb. If not, see <http://www.gnu.org/licenses/>."""an helper class to display CubicWeb schema using ureports"""__docformat__="restructuredtext en"fromcubicwebimport_fromsiximportstring_typesfromlogilab.common.ureportsimportSection,Title,Table,Link,Span,Textfromyams.schema2dotimportCARD_MAPfromyams.schemaimportRelationDefinitionSchemafromoperatorimportattrgetterTYPE_GETTER=attrgetter('type')I18NSTRINGS=[_('read'),_('add'),_('delete'),_('update'),_('order')]classSchemaViewer(object):"""return a ureport layout for some part of a schema"""def__init__(self,req=None,encoding=None):self.req=reqifreqisnotNone:req.add_css('cubicweb.schema.css')ifencodingisNone:encoding=req.encodingself._=req._else:encoding='ascii'self._=unicodeself.encoding=encoding# no self.req managementsdefmay_read(self,rdef,action='read'):"""Return true if request user may read the given schema. Always return True when no request is provided. """ifself.reqisNone:returnTruereturnrdef.may_have_permission(action,self.req)defformat_eschema(self,eschema):text=eschema.typeifself.reqisNone:returnText(text)returnLink(self.req.build_url('cwetype/%s'%eschema),text)defformat_rschema(self,rschema,label=None):iflabelisNone:label=rschema.typeifself.reqisNone:returnText(label)returnLink(self.req.build_url('cwrtype/%s'%rschema),label)# end of no self.req managementsdefvisit_schema(self,schema,display_relations=0,skiptypes=()):"""get a layout for a whole schema"""title=Title(self._('Schema %s')%schema.name,klass='titleUnderline')layout=Section(children=(title,))esection=Section(children=(Title(self._('Entities'),klass='titleUnderline'),))layout.append(esection)eschemas=[eschemaforeschemainschema.entities()ifnot(eschema.finaloreschemainskiptypes)]foreschemainsorted(eschemas,key=TYPE_GETTER):esection.append(self.visit_entityschema(eschema,skiptypes))ifdisplay_relations:title=Title(self._('Relations'),klass='titleUnderline')rsection=Section(children=(title,))layout.append(rsection)relations=[rschemaforrschemainsorted(schema.relations(),key=TYPE_GETTER)ifnot(rschema.finalorrschema.typeinskiptypes)]keys=[(rschema.type,rschema)forrschemainrelations]forkey,rschemainsorted(keys,cmp=(lambdax,y:cmp(x[1],y[1]))):relstr=self.visit_relationschema(rschema)rsection.append(relstr)returnlayoutdef_entity_attributes_data(self,eschema):_=self._data=[_('attribute'),_('type'),_('default'),_('constraints')]attributes=sorted(eschema.attribute_definitions(),cmp=(lambdax,y:cmp(x[0].type,y[0].type)))forrschema,aschemainattributes:rdef=eschema.rdef(rschema)ifnotself.may_read(rdef):continueaname=rschema.typeifaname=='eid':continuedata.append('%s (%s)'%(aname,_(aname)))data.append(_(aschema.type))defaultval=eschema.default(aname)ifdefaultvalisnotNone:default=self.to_string(defaultval)elifrdef.cardinality[0]=='1':default=_('required field')else:default=''data.append(default)constraints=rschema.rproperty(eschema.type,aschema.type,'constraints')data.append(', '.join(str(constr)forconstrinconstraints))returndatadefstereotype(self,name):returnSpan((' <<%s>>'%name,),klass='stereotype')defvisit_entityschema(self,eschema,skiptypes=()):"""get a layout for an entity schema"""etype=eschema.typelayout=Section(children=' ',klass='clear')layout.append(Link(etype,' ',id=etype))# anchortitle=self.format_eschema(eschema)boxchild=[Section(children=(title,),klass='title')]data=[]data.append(Section(children=boxchild,klass='box'))data.append(Section(children='',klass='vl'))data.append(Section(children='',klass='hl'))t_vars=[]rels=[]first=Truerel_defs=sorted(eschema.relation_definitions(),cmp=(lambdax,y:cmp((x[0].type,x[0].cardinality),(y[0].type,y[0].cardinality))))forrschema,targetschemas,roleinrel_defs:ifrschema.typeinskiptypes:continueforoeschemainsorted(targetschemas,key=TYPE_GETTER):rdef=rschema.role_rdef(eschema,oeschema,role)ifnotself.may_read(rdef):continuelabel=rschema.typeifrole=='subject':cards=rschema.rdef(eschema,oeschema).cardinalityelse:cards=rschema.rdef(oeschema,eschema).cardinalitycards=cards[::-1]label='%s%s%s'%(CARD_MAP[cards[1]],label,CARD_MAP[cards[0]])rlink=self.format_rschema(rschema,label)elink=self.format_eschema(oeschema)iffirst:t_vars.append(Section(children=(elink,),klass='firstvar'))rels.append(Section(children=(rlink,),klass='firstrel'))first=Falseelse:t_vars.append(Section(children=(elink,),klass='var'))rels.append(Section(children=(rlink,),klass='rel'))data.append(Section(children=rels,klass='rels'))data.append(Section(children=t_vars,klass='vars'))layout.append(Section(children=data,klass='entityAttributes'))returnlayoutdefvisit_relationschema(self,rschema,title=True):"""get a layout for a relation schema"""_=self._iftitle:title=self.format_rschema(rschema)stereotypes=[]ifrschema.meta:stereotypes.append('meta')ifrschema.symmetric:stereotypes.append('symmetric')ifrschema.inlined:stereotypes.append('inlined')title=Section(children=(title,),klass='title')ifstereotypes:title.append(self.stereotype(','.join(stereotypes)))layout=Section(children=(title,),klass='schema')else:layout=Section(klass='schema')data=[_('from'),_('to')]schema=rschema.schemarschema_objects=rschema.objects()ifrschema_objects:# might be emptyproperties=[pforpinRelationDefinitionSchema.rproperty_defs(rschema_objects[0])ifnotpin('cardinality','composite','eid')]else:properties=[]data+=[_(prop)forpropinproperties]cols=len(data)done=set()forsubjtype,objtypesinsorted(rschema.associations()):forobjtypeinobjtypes:if(subjtype,objtype)indone:continuedone.add((subjtype,objtype))ifrschema.symmetric:done.add((objtype,subjtype))data.append(self.format_eschema(schema[subjtype]))data.append(self.format_eschema(schema[objtype]))rdef=rschema.rdef(subjtype,objtype)forpropinproperties:val=getattr(rdef,prop)ifvalisNone:val=''elifprop=='constraints':val=', '.join([c.expressionforcinval])elifisinstance(val,dict):forkey,valueinval.items():ifisinstance(value,(list,tuple)):val[key]=', '.join(sorted(str(v)forvinvalue))val=str(val)elifisinstance(val,(list,tuple)):val=sorted(val)val=', '.join(str(v)forvinval)elifvalandisinstance(val,string_types):val=_(val)else:val=str(val)data.append(Text(val))table=Table(cols=cols,rheaders=1,children=data,klass='listing')layout.append(Section(children=(table,),klass='relationDefinition'))layout.append(Section(children='',klass='clear'))returnlayoutdefto_string(self,value):"""used to converte arbitrary values to encoded string"""ifisinstance(value,unicode):returnvalue.encode(self.encoding,'replace')returnstr(value)