[MERGE] lxml+etree instead of deprecated XML libs which prevent install on Ubuntu. Merged from old_trunk branch because on ne trunk, commits were not atomics anymore (after pig merge + bzr unability to track partial merge origins).

merge directive used was: bzr merge -r 1825..1826 lp:~openerp/openobject-server/old_trunk
tested main flows on manufacturing database + French -> no bug found; still will commit a few more commits related to trunk + etree

lp bug: https://launchpad.net/bugs/429519 fixed

bzr revid: rvalyi@gmail.com-20091028200443-2ciyhqaz7rczdusy
This commit is contained in:
Raphaël Valyi 2009-10-28 18:04:43 -02:00
parent db8f833229
commit c9d35c7012
4 changed files with 268 additions and 296 deletions

View File

@ -50,16 +50,15 @@ import pickle
import fields import fields
import tools import tools
from tools.translate import _
import sys import sys
try: try:
from xml import dom, xpath from lxml import etree
except ImportError: except ImportError:
sys.stderr.write("ERROR: Import xpath module\n") sys.stderr.write("ERROR: Import lxml module\n")
sys.stderr.write("ERROR: Try to install the old python-xml package\n") sys.stderr.write("ERROR: Try to install the python-lxml package\n")
sys.stderr.write('On Ubuntu Jaunty, try this: sudo cp /usr/lib/python2.6/dist-packages/oldxml/_xmlplus/utils/boolean.so /usr/lib/python2.5/site-packages/oldxml/_xmlplus/utils\n')
raise
from tools.config import config from tools.config import config
@ -997,14 +996,14 @@ class orm_template(object):
fields = {} fields = {}
childs = True childs = True
if node.nodeType == node.ELEMENT_NODE and node.localName == 'field': if node.tag == 'field':
if node.hasAttribute('name'): if node.get('name'):
attrs = {} attrs = {}
try: try:
if node.getAttribute('name') in self._columns: if node.get('name') in self._columns:
column = self._columns[node.getAttribute('name')] column = self._columns[node.get('name')]
else: else:
column = self._inherit_fields[node.getAttribute('name')][2] column = self._inherit_fields[node.get('name')][2]
except: except:
column = False column = False
@ -1012,65 +1011,63 @@ class orm_template(object):
relation = column._obj relation = column._obj
childs = False childs = False
views = {} views = {}
for f in node.childNodes: for f in node:
if f.nodeType == f.ELEMENT_NODE and f.localName in ('form', 'tree', 'graph'): if f.tag in ('form', 'tree', 'graph'):
node.removeChild(f) node.remove(f)
ctx = context.copy() ctx = context.copy()
ctx['base_model_name'] = self._name ctx['base_model_name'] = self._name
xarch, xfields = self.pool.get(relation).__view_look_dom_arch(cr, user, f, view_id, ctx) xarch, xfields = self.pool.get(relation).__view_look_dom_arch(cr, user, f, view_id, ctx)
views[str(f.localName)] = { views[str(f.tag)] = {
'arch': xarch, 'arch': xarch,
'fields': xfields 'fields': xfields
} }
attrs = {'views': views} attrs = {'views': views}
if node.hasAttribute('widget') and node.getAttribute('widget')=='selection': if node.get('widget') and node.get('widget') == 'selection':
# We can not use the 'string' domain has it is defined according to the record ! # We can not use the 'string' domain has it is defined according to the record !
dom = [] dom = None
if column._domain and not isinstance(column._domain, (str, unicode)): if column._domain and not isinstance(column._domain, (str, unicode)):
dom = column._domain dom = column._domain
attrs['selection'] = self.pool.get(relation).name_search(cr, user, '', dom, context=context) attrs['selection'] = self.pool.get(relation).name_search(cr, user, '', dom, context=context)
if (node.hasAttribute('required') and not int(node.getAttribute('required'))) or not column.required: if (node.get('required') and not int(node.get('required'))) or not column.required:
attrs['selection'].append((False,'')) attrs['selection'].append((False,''))
fields[node.getAttribute('name')] = attrs fields[node.get('name')] = attrs
elif node.nodeType==node.ELEMENT_NODE and node.localName in ('form', 'tree'): elif node.tag in ('form', 'tree'):
result = self.view_header_get(cr, user, False, node.localName, context) result = self.view_header_get(cr, user, False, node.tag, context)
if result: if result:
node.setAttribute('string', result) node.set('string', result)
elif node.nodeType==node.ELEMENT_NODE and node.localName == 'calendar': elif node.tag == 'calendar':
for additional_field in ('date_start', 'date_delay', 'date_stop', 'color'): for additional_field in ('date_start', 'date_delay', 'date_stop', 'color'):
if node.hasAttribute(additional_field) and node.getAttribute(additional_field): if node.get(additional_field):
fields[node.getAttribute(additional_field)] = {} fields[node.get(additional_field)] = {}
if node.nodeType == node.ELEMENT_NODE and node.hasAttribute('groups'): if 'groups' in node.attrib:
if node.getAttribute('groups'): if node.get('groups'):
groups = node.getAttribute('groups').split(',') groups = node.get('groups').split(',')
readonly = False readonly = False
access_pool = self.pool.get('ir.model.access') access_pool = self.pool.get('ir.model.access')
for group in groups: for group in groups:
readonly = readonly or access_pool.check_groups(cr, user, group) readonly = readonly or access_pool.check_groups(cr, user, group)
if not readonly: if not readonly:
node.setAttribute('invisible', '1') node.set('invisible', '1')
node.removeAttribute('groups') del(node.attrib['groups'])
if node.nodeType == node.ELEMENT_NODE: # translate view
# translate view if ('lang' in context) and not result:
if ('lang' in context) and not result: if node.get('string'):
if node.hasAttribute('string') and node.getAttribute('string'): trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('string').encode('utf8'))
trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.getAttribute('string').encode('utf8')) if not trans and ('base_model_name' in context):
if not trans and ('base_model_name' in context): trans = self.pool.get('ir.translation')._get_source(cr, user, context['base_model_name'], 'view', context['lang'], node.get('string').encode('utf8'))
trans = self.pool.get('ir.translation')._get_source(cr, user, context['base_model_name'], 'view', context['lang'], node.getAttribute('string').encode('utf8')) if trans:
if trans: node.set('string', trans)
node.setAttribute('string', trans) if node.get('sum'):
if node.hasAttribute('sum') and node.getAttribute('sum'): trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('sum').encode('utf8'))
trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.getAttribute('sum').encode('utf8')) if trans:
if trans: node.set('sum', trans)
node.setAttribute('sum', trans)
if childs: if childs:
for f in node.childNodes: for f in node:
fields.update(self.__view_look_dom(cr, user, f, view_id, context)) fields.update(self.__view_look_dom(cr, user, f, view_id, context))
return fields return fields
@ -1081,7 +1078,7 @@ class orm_template(object):
rolesobj = self.pool.get('res.roles') rolesobj = self.pool.get('res.roles')
usersobj = self.pool.get('res.users') usersobj = self.pool.get('res.users')
buttons = (n for n in node.getElementsByTagName('button') if n.getAttribute('type') != 'object') buttons = (n for n in node.getiterator('button') if n.get('type') != 'object')
for button in buttons: for button in buttons:
can_click = True can_click = True
if user != 1: # admin user has all roles if user != 1: # admin user has all roles
@ -1104,8 +1101,6 @@ class orm_template(object):
# #
# running -> done = signal_next (role Z) # running -> done = signal_next (role Z)
# running -> cancel = signal_cancel (role Z) # running -> cancel = signal_cancel (role Z)
# As we don't know the object state, in this scenario, # As we don't know the object state, in this scenario,
# the button "signal_cancel" will be always shown as there is no restriction to cancel in draft # the button "signal_cancel" will be always shown as there is no restriction to cancel in draft
# the button "signal_next" will be show if the user has any of the roles (X Y or Z) # the button "signal_next" will be show if the user has any of the roles (X Y or Z)
@ -1113,9 +1108,9 @@ class orm_template(object):
if roles: if roles:
can_click = any((not role) or rolesobj.check(cr, user, user_roles, role) for (role,) in roles) can_click = any((not role) or rolesobj.check(cr, user, user_roles, role) for (role,) in roles)
button.setAttribute('readonly', str(int(not can_click))) button.set('readonly', str(int(not can_click)))
arch = node.toxml(encoding="utf-8").replace('\t', '') arch = etree.tostring(node, encoding="utf-8").replace('\t', '')
fields = self.fields_get(cr, user, fields_def.keys(), context) fields = self.fields_get(cr, user, fields_def.keys(), context)
for field in fields_def: for field in fields_def:
if field == 'id': if field == 'id':
@ -1180,70 +1175,64 @@ class orm_template(object):
def _inherit_apply(src, inherit): def _inherit_apply(src, inherit):
def _find(node, node2): def _find(node, node2):
if node2.nodeType == node2.ELEMENT_NODE and node2.localName == 'xpath': if node2.tag == 'xpath':
res = xpath.Evaluate(node2.getAttribute('expr'), node) res = node.xpath(node2.get('expr'))
return res and res[0] return res and res[0]
else: else:
if node.nodeType == node.ELEMENT_NODE and node.localName == node2.localName: for n in node.getiterator(node2.tag):
res = True res = True
for attr in node2.attributes.keys(): for attr in node2.attrib:
if attr == 'position': if attr == 'position':
continue continue
if node.hasAttribute(attr): if n.get(attr):
if node.getAttribute(attr)==node2.getAttribute(attr): if n.get(attr) == node2.get(attr):
continue continue
res = False res = False
if res: if res:
return node return n
for child in node.childNodes:
res = _find(child, node2)
if res:
return res
return None return None
# End: _find(node, node2)
doc_dest = etree.fromstring(encode(inherit))
doc_src = dom.minidom.parseString(encode(src)) toparse = [ doc_dest ]
doc_dest = dom.minidom.parseString(encode(inherit))
toparse = doc_dest.childNodes
while len(toparse): while len(toparse):
node2 = toparse.pop(0) node2 = toparse.pop(0)
if not node2.nodeType == node2.ELEMENT_NODE: if node2.tag == 'data':
toparse += [ c for c in doc_dest ]
continue continue
if node2.localName == 'data': node = _find(src, node2)
toparse += node2.childNodes if node is not None:
continue
node = _find(doc_src, node2)
if node:
pos = 'inside' pos = 'inside'
if node2.hasAttribute('position'): if node2.get('position'):
pos = node2.getAttribute('position') pos = node2.get('position')
if pos == 'replace': if pos == 'replace':
parent = node.parentNode for child in node2:
for child in node2.childNodes: node.addprevious(child)
if child.nodeType == child.ELEMENT_NODE: node.getparent().remove(node)
parent.insertBefore(child, node)
parent.removeChild(node)
else: else:
sib = node.nextSibling sib = node.getnext()
for child in node2.childNodes: for child in node2:
if child.nodeType == child.ELEMENT_NODE: if pos == 'inside':
if pos == 'inside': node.append(child)
node.appendChild(child) elif pos == 'after':
elif pos == 'after': if sib is None:
node.parentNode.insertBefore(child, sib) node.addnext(child)
elif pos=='before':
node.parentNode.insertBefore(child, node)
else: else:
raise AttributeError(_('Unknown position in inherited view %s !') % pos) sib.addprevious(child)
elif pos == 'before':
node.addprevious(child)
else:
raise AttributeError(_('Unknown position in inherited view %s !') % pos)
else: else:
attrs = ''.join([ attrs = ''.join([
' %s="%s"' % (attr, node2.getAttribute(attr)) ' %s="%s"' % (attr, node2.get(attr))
for attr in node2.attributes.keys() for attr in node2.attrib
if attr != 'position' if attr != 'position'
]) ])
tag = "<%s%s>" % (node2.localName, attrs) tag = "<%s%s>" % (node2.tag, attrs)
raise AttributeError(_("Couldn't find tag '%s' in parent view !") % tag) raise AttributeError(_("Couldn't find tag '%s' in parent view !") % tag)
return doc_src.toxml(encoding="utf-8").replace('\t', '') return src
# End: _inherit_apply(src, inherit)
result = {'type': view_type, 'model': self._name} result = {'type': view_type, 'model': self._name}
@ -1295,7 +1284,8 @@ class orm_template(object):
result = _inherit_apply_rec(result, id) result = _inherit_apply_rec(result, id)
return result return result
result['arch'] = _inherit_apply_rec(result['arch'], sql_res[3]) inherit_result = etree.fromstring(encode(result['arch']))
result['arch'] = _inherit_apply_rec(inherit_result, sql_res[3])
result['name'] = sql_res[1] result['name'] = sql_res[1]
result['field_parent'] = sql_res[2] or False result['field_parent'] = sql_res[2] or False
@ -1322,13 +1312,12 @@ class orm_template(object):
xml = self.__get_default_calendar_view() xml = self.__get_default_calendar_view()
else: else:
xml = '' xml = ''
result['arch'] = xml result['arch'] = etree.fromstring(xml)
result['name'] = 'default' result['name'] = 'default'
result['field_parent'] = False result['field_parent'] = False
result['view_id'] = 0 result['view_id'] = 0
doc = dom.minidom.parseString(encode(result['arch'])) xarch, xfields = self.__view_look_dom_arch(cr, user, result['arch'], view_id, context=context)
xarch, xfields = self.__view_look_dom_arch(cr, user, doc, view_id, context=context)
result['arch'] = xarch result['arch'] = xarch
result['fields'] = xfields result['fields'] = xfields
if toolbar: if toolbar:
@ -3044,7 +3033,3 @@ class orm(orm_template):
if i in ids: if i in ids:
return False return False
return True return True
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -21,7 +21,7 @@
############################################################################## ##############################################################################
import re import re
import cStringIO import cStringIO
import xml.dom.minidom from lxml import etree
import osv import osv
import ir import ir
import pooler import pooler
@ -62,16 +62,13 @@ def _obj(pool, cr, uid, model_str, context=None):
def _eval_xml(self,node, pool, cr, uid, idref, context=None): def _eval_xml(self,node, pool, cr, uid, idref, context=None):
if context is None: if context is None:
context = {} context = {}
if node.nodeType == node.TEXT_NODE: if node.tag in ('field','value'):
return node.data.encode("utf8") t = node.get('type','') or 'char'
elif node.nodeType == node.ELEMENT_NODE: f_model = node.get("model", '').encode('ascii')
if node.nodeName in ('field','value'): if len(node.get('search','')):
t = node.getAttribute('type') or 'char' f_search = node.get("search",'').encode('utf-8')
f_model = node.getAttribute("model").encode('ascii') f_use = node.get("use",'').encode('ascii')
if len(node.getAttribute('search')): f_name = node.get("name",'').encode('utf-8')
f_search = node.getAttribute("search").encode('utf-8')
f_use = node.getAttribute("use").encode('ascii')
f_name = node.getAttribute("name").encode('utf-8')
if len(f_use)==0: if len(f_use)==0:
f_use = "id" f_use = "id"
q = eval(f_search, idref) q = eval(f_search, idref)
@ -87,7 +84,7 @@ def _eval_xml(self,node, pool, cr, uid, idref, context=None):
if isinstance(f_val, tuple): if isinstance(f_val, tuple):
f_val = f_val[0] f_val = f_val[0]
return f_val return f_val
a_eval = node.getAttribute('eval') a_eval = node.get('eval','')
if len(a_eval): if len(a_eval):
import time import time
from mx import DateTime from mx import DateTime
@ -116,14 +113,11 @@ def _eval_xml(self,node, pool, cr, uid, idref, context=None):
if not id in idref: if not id in idref:
idref[id]=self.id_get(cr, False, id) idref[id]=self.id_get(cr, False, id)
return s % idref return s % idref
txt = '<?xml version="1.0"?>\n'+_process("".join([i.toxml().encode("utf8") for i in node.childNodes]), idref) txt = '<?xml version="1.0"?>\n'+_process("".join([etree.tostring(i).encode("utf8") for i in node.getchildren()]), idref)
# txt = '<?xml version="1.0"?>\n'+"".join([i.toxml().encode("utf8") for i in node.childNodes]) % idref
return txt return txt
if t in ('char', 'int', 'float'): if t in ('char', 'int', 'float'):
d = "" d = ""
for n in [i for i in node.childNodes]: d = node.text
d+=str(_eval_xml(self,n,pool,cr,uid,idref))
if t == 'int': if t == 'int':
d = d.strip() d = d.strip()
if d=='None': if d=='None':
@ -135,37 +129,37 @@ def _eval_xml(self,node, pool, cr, uid, idref, context=None):
return d return d
elif t in ('list','tuple'): elif t in ('list','tuple'):
res=[] res=[]
for n in [i for i in node.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=='value')]: for n in [i for i in node.getchildren() if (i.tag=='value')]:
res.append(_eval_xml(self,n,pool,cr,uid,idref)) res.append(_eval_xml(self,n,pool,cr,uid,idref))
if t=='tuple': if t=='tuple':
return tuple(res) return tuple(res)
return res return res
elif node.nodeName=="getitem": elif node.tag == "getitem":
for n in [i for i in node.childNodes if (i.nodeType == i.ELEMENT_NODE)]: for n in [i for i in node.getchildren()]:
res=_eval_xml(self,n,pool,cr,uid,idref) res=_eval_xml(self,n,pool,cr,uid,idref)
if not res: if not res:
raise LookupError raise LookupError
elif node.getAttribute('type') in ("int", "list"): elif node.get('type','') in ("int", "list"):
return res[int(node.getAttribute('index'))] return res[int(node.get('index',''))]
else: else:
return res[node.getAttribute('index').encode("utf8")] return res[node.get('index','').encode("utf8")]
elif node.nodeName=="function": elif node.tag == "function":
args = [] args = []
a_eval = node.getAttribute('eval') a_eval = node.get('eval','')
if len(a_eval): if len(a_eval):
idref['ref'] = lambda x: self.id_get(cr, False, x) idref['ref'] = lambda x: self.id_get(cr, False, x)
args = eval(a_eval, idref) args = eval(a_eval, idref)
for n in [i for i in node.childNodes if (i.nodeType == i.ELEMENT_NODE)]: for n in [i for i in node.getchildren()]:
args.append(_eval_xml(self,n, pool, cr, uid, idref, context)) return_val = _eval_xml(self,n, pool, cr, uid, idref, context)
model = pool.get(node.getAttribute('model')) if return_val != None:
method = node.getAttribute('name') args.append(return_val)
res = getattr(model, method)(cr, uid, *args) model = pool.get(node.get('model',''))
return res method = node.get('name','')
elif node.nodeName=="test": res = getattr(model, method)(cr, uid, *args)
d = "" return res
for n in [i for i in node.childNodes]: elif node.tag == "test":
d+=str(_eval_xml(self,n,pool,cr,uid,idref, context=context)) d = node.text
return d return d
escape_re = re.compile(r'(?<!\\)/') escape_re = re.compile(r'(?<!\\)/')
@ -205,9 +199,9 @@ class xml_import(object):
@staticmethod @staticmethod
def nodeattr2bool(node, attr, default=False): def nodeattr2bool(node, attr, default=False):
if not node.hasAttribute(attr): if not node.get(attr):
return default return default
val = node.getAttribute(attr).strip() val = node.get(attr).strip()
if not val: if not val:
return default return default
return val.lower() not in ('0', 'false', 'off') return val.lower() not in ('0', 'false', 'off')
@ -216,20 +210,20 @@ class xml_import(object):
return self.noupdate or (data_node and self.nodeattr2bool(data_node, 'noupdate', False)) return self.noupdate or (data_node and self.nodeattr2bool(data_node, 'noupdate', False))
def get_context(self, data_node, node, eval_dict): def get_context(self, data_node, node, eval_dict):
data_node_context = (data_node and data_node.getAttribute('context').encode('utf8')) data_node_context = (data_node and data_node.get('context','').encode('utf8'))
if data_node_context: if data_node_context:
context = eval(data_node_context, eval_dict) context = eval(data_node_context, eval_dict)
else: else:
context = {} context = {}
node_context = node.getAttribute("context").encode('utf8') node_context = node.get("context",'').encode('utf8')
if len(node_context): if len(node_context):
context.update(eval(node_context, eval_dict)) context.update(eval(node_context, eval_dict))
return context return context
def get_uid(self, cr, uid, data_node, node): def get_uid(self, cr, uid, data_node, node):
node_uid = node.getAttribute('uid') or (data_node and data_node.getAttribute('uid')) node_uid = node.get('uid','') or (data_node and data_node.get('uid',''))
if len(node_uid): if len(node_uid):
return self.id_get(cr, None, node_uid) return self.id_get(cr, None, node_uid)
return uid return uid
@ -249,9 +243,9 @@ form: module.record_id""" % (xml_id,)
self.logger.notifyChannel('init', netsvc.LOG_ERROR, 'id: %s is to long (max: 64)'% (id,)) self.logger.notifyChannel('init', netsvc.LOG_ERROR, 'id: %s is to long (max: 64)'% (id,))
def _tag_delete(self, cr, rec, data_node=None): def _tag_delete(self, cr, rec, data_node=None):
d_model = rec.getAttribute("model") d_model = rec.get("model",'')
d_search = rec.getAttribute("search") d_search = rec.get("search",'')
d_id = rec.getAttribute("id") d_id = rec.get("id",'')
ids = [] ids = []
if len(d_search): if len(d_search):
ids = self.pool.get(d_model).search(cr,self.uid,eval(d_search)) ids = self.pool.get(d_model).search(cr,self.uid,eval(d_search))
@ -269,24 +263,24 @@ form: module.record_id""" % (xml_id,)
def _tag_report(self, cr, rec, data_node=None): def _tag_report(self, cr, rec, data_node=None):
res = {} res = {}
for dest,f in (('name','string'),('model','model'),('report_name','name')): for dest,f in (('name','string'),('model','model'),('report_name','name')):
res[dest] = rec.getAttribute(f).encode('utf8') res[dest] = rec.get(f,'').encode('utf8')
assert res[dest], "Attribute %s of report is empty !" % (f,) assert res[dest], "Attribute %s of report is empty !" % (f,)
for field,dest in (('rml','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')): for field,dest in (('rml','report_rml'),('xml','report_xml'),('xsl','report_xsl'),('attachment','attachment'),('attachment_use','attachment_use')):
if rec.hasAttribute(field): if rec.get(field):
res[dest] = rec.getAttribute(field).encode('utf8') res[dest] = rec.get(field,'').encode('utf8')
if rec.hasAttribute('auto'): if rec.get('auto'):
res['auto'] = eval(rec.getAttribute('auto')) res['auto'] = eval(rec.get('auto',''))
if rec.hasAttribute('sxw'): if rec.get('sxw'):
sxw_content = misc.file_open(rec.getAttribute('sxw')).read() sxw_content = misc.file_open(rec.get('sxw','')).read()
res['report_sxw_content'] = sxw_content res['report_sxw_content'] = sxw_content
if rec.hasAttribute('header'): if rec.get('header'):
res['header'] = eval(rec.getAttribute('header')) res['header'] = eval(rec.get('header',''))
res['multi'] = rec.hasAttribute('multi') and eval(rec.getAttribute('multi')) res['multi'] = rec.get('multi','') and eval(rec.get('multi',''))
xml_id = rec.getAttribute('id').encode('utf8') xml_id = rec.get('id','').encode('utf8')
self._test_xml_id(xml_id) self._test_xml_id(xml_id)
if rec.hasAttribute('groups'): if rec.get('groups'):
g_names = rec.getAttribute('groups').split(',') g_names = rec.get('groups','').split(',')
groups_value = [] groups_value = []
groups_obj = self.pool.get('res.groups') groups_obj = self.pool.get('res.groups')
for group in g_names: for group in g_names:
@ -302,11 +296,11 @@ form: module.record_id""" % (xml_id,)
self.idref[xml_id] = int(id) self.idref[xml_id] = int(id)
if not rec.hasAttribute('menu') or eval(rec.getAttribute('menu')): if not rec.get('menu') or eval(rec.get('menu','')):
keyword = str(rec.getAttribute('keyword') or 'client_print_multi') keyword = str(rec.get('keyword','') or 'client_print_multi')
keys = [('action',keyword),('res_model',res['model'])] keys = [('action',keyword),('res_model',res['model'])]
value = 'ir.actions.report.xml,'+str(id) value = 'ir.actions.report.xml,'+str(id)
replace = rec.hasAttribute('replace') and rec.getAttribute("replace") or True replace = rec.get("replace",'') or True
self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, res['name'], [res['model']], value, replace=replace, isobject=True, xml_id=xml_id) self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, res['name'], [res['model']], value, replace=replace, isobject=True, xml_id=xml_id)
return False return False
@ -319,16 +313,16 @@ form: module.record_id""" % (xml_id,)
return False return False
def _tag_wizard(self, cr, rec, data_node=None): def _tag_wizard(self, cr, rec, data_node=None):
string = rec.getAttribute("string").encode('utf8') string = rec.get("string",'').encode('utf8')
model = rec.getAttribute("model").encode('utf8') model = rec.get("model",'').encode('utf8')
name = rec.getAttribute("name").encode('utf8') name = rec.get("name",'').encode('utf8')
xml_id = rec.getAttribute('id').encode('utf8') xml_id = rec.get('id','').encode('utf8')
self._test_xml_id(xml_id) self._test_xml_id(xml_id)
multi = rec.hasAttribute('multi') and eval(rec.getAttribute('multi')) multi = rec.get('multi','') and eval(rec.get('multi',''))
res = {'name': string, 'wiz_name': name, 'multi': multi, 'model': model} res = {'name': string, 'wiz_name': name, 'multi': multi, 'model': model}
if rec.hasAttribute('groups'): if rec.get('groups'):
g_names = rec.getAttribute('groups').split(',') g_names = rec.get('groups','').split(',')
groups_value = [] groups_value = []
groups_obj = self.pool.get('res.groups') groups_obj = self.pool.get('res.groups')
for group in g_names: for group in g_names:
@ -343,20 +337,19 @@ form: module.record_id""" % (xml_id,)
id = self.pool.get('ir.model.data')._update(cr, self.uid, "ir.actions.wizard", self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode) id = self.pool.get('ir.model.data')._update(cr, self.uid, "ir.actions.wizard", self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode)
self.idref[xml_id] = int(id) self.idref[xml_id] = int(id)
# ir_set # ir_set
if (not rec.hasAttribute('menu') or eval(rec.getAttribute('menu'))) and id: if (not rec.get('menu') or eval(rec.get('menu',''))) and id:
keyword = str(rec.getAttribute('keyword') or 'client_action_multi') keyword = str(rec.get('keyword','') or 'client_action_multi')
keys = [('action',keyword),('res_model',model)] keys = [('action',keyword),('res_model',model)]
value = 'ir.actions.wizard,'+str(id) value = 'ir.actions.wizard,'+str(id)
replace = rec.hasAttribute('replace') and \ replace = rec.get("replace",'') or True
rec.getAttribute("replace") or True
self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, string, [model], value, replace=replace, isobject=True, xml_id=xml_id) self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, string, [model], value, replace=replace, isobject=True, xml_id=xml_id)
return False return False
def _tag_url(self, cr, rec, data_node=None): def _tag_url(self, cr, rec, data_node=None):
url = rec.getAttribute("string").encode('utf8') url = rec.get("string",'').encode('utf8')
target = rec.getAttribute("target").encode('utf8') target = rec.get("target",'').encode('utf8')
name = rec.getAttribute("name").encode('utf8') name = rec.get("name",'').encode('utf8')
xml_id = rec.getAttribute('id').encode('utf8') xml_id = rec.get('id','').encode('utf8')
self._test_xml_id(xml_id) self._test_xml_id(xml_id)
res = {'name': name, 'url': url, 'target':target} res = {'name': name, 'url': url, 'target':target}
@ -364,34 +357,31 @@ form: module.record_id""" % (xml_id,)
id = self.pool.get('ir.model.data')._update(cr, self.uid, "ir.actions.url", self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode) id = self.pool.get('ir.model.data')._update(cr, self.uid, "ir.actions.url", self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode)
self.idref[xml_id] = int(id) self.idref[xml_id] = int(id)
# ir_set # ir_set
if (not rec.hasAttribute('menu') or eval(rec.getAttribute('menu'))) and id: if (not rec.get('menu') or eval(rec.get('menu',''))) and id:
keyword = str(rec.getAttribute('keyword') or 'client_action_multi') keyword = str(rec.get('keyword','') or 'client_action_multi')
keys = [('action',keyword)] keys = [('action',keyword)]
value = 'ir.actions.url,'+str(id) value = 'ir.actions.url,'+str(id)
replace = rec.hasAttribute('replace') and \ replace = rec.get("replace",'') or True
rec.getAttribute("replace") or True
self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, url, ["ir.actions.url"], value, replace=replace, isobject=True, xml_id=xml_id) self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, url, ["ir.actions.url"], value, replace=replace, isobject=True, xml_id=xml_id)
return False return False
def _tag_act_window(self, cr, rec, data_node=None): def _tag_act_window(self, cr, rec, data_node=None):
name = rec.hasAttribute('name') and rec.getAttribute('name').encode('utf-8') name = rec.get('name','').encode('utf-8')
xml_id = rec.getAttribute('id').encode('utf8') xml_id = rec.get('id','').encode('utf8')
self._test_xml_id(xml_id) self._test_xml_id(xml_id)
type = rec.hasAttribute('type') and rec.getAttribute('type').encode('utf-8') or 'ir.actions.act_window' type = rec.get('type','').encode('utf-8') or 'ir.actions.act_window'
view_id = False view_id = False
if rec.hasAttribute('view'): if rec.get('view'):
view_id = self.id_get(cr, 'ir.actions.act_window', rec.getAttribute('view').encode('utf-8')) view_id = self.id_get(cr, 'ir.actions.act_window', rec.get('view','').encode('utf-8'))
domain = rec.hasAttribute('domain') and rec.getAttribute('domain').encode('utf-8') domain = rec.get('domain','').encode('utf-8')
context = rec.hasAttribute('context') and rec.getAttribute('context').encode('utf-8') or '{}' context = rec.get('context','').encode('utf-8') or '{}'
res_model = rec.getAttribute('res_model').encode('utf-8') res_model = rec.get('res_model','').encode('utf-8')
src_model = rec.hasAttribute('src_model') and rec.getAttribute('src_model').encode('utf-8') src_model = rec.get('src_model','').encode('utf-8')
view_type = rec.hasAttribute('view_type') and rec.getAttribute('view_type').encode('utf-8') or 'form' view_type = rec.get('view_type','').encode('utf-8') or 'form'
view_mode = rec.hasAttribute('view_mode') and rec.getAttribute('view_mode').encode('utf-8') or 'tree,form' view_mode = rec.get('view_mode','').encode('utf-8') or 'tree,form'
usage = rec.hasAttribute('usage') and rec.getAttribute('usage').encode('utf-8') usage = rec.get('usage','').encode('utf-8')
limit = rec.hasAttribute('limit') and rec.getAttribute('limit').encode('utf-8') limit = rec.get('limit','').encode('utf-8')
auto_refresh = rec.hasAttribute('auto_refresh') \ auto_refresh = rec.get('auto_refresh','').encode('utf-8')
and rec.getAttribute('auto_refresh').encode('utf-8')
# groups_id = rec.hasAttribute('groups') and rec.getAttribute('groups').encode('utf-8')
# def ref() added because , if context has ref('id') eval wil use this ref # def ref() added because , if context has ref('id') eval wil use this ref
@ -417,8 +407,8 @@ form: module.record_id""" % (xml_id,)
# 'groups_id':groups_id, # 'groups_id':groups_id,
} }
if rec.hasAttribute('groups'): if rec.get('groups'):
g_names = rec.getAttribute('groups').split(',') g_names = rec.get('groups','').split(',')
groups_value = [] groups_value = []
groups_obj = self.pool.get('res.groups') groups_obj = self.pool.get('res.groups')
for group in g_names: for group in g_names:
@ -430,8 +420,8 @@ form: module.record_id""" % (xml_id,)
groups_value.append((4, group_id)) groups_value.append((4, group_id))
res['groups_id'] = groups_value res['groups_id'] = groups_value
if rec.hasAttribute('target'): if rec.get('target'):
res['target'] = rec.getAttribute('target') res['target'] = rec.get('target','')
id = self.pool.get('ir.model.data')._update(cr, self.uid, 'ir.actions.act_window', self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode) id = self.pool.get('ir.model.data')._update(cr, self.uid, 'ir.actions.act_window', self.module, res, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode)
self.idref[xml_id] = int(id) self.idref[xml_id] = int(id)
@ -439,7 +429,7 @@ form: module.record_id""" % (xml_id,)
keyword = 'client_action_relate' keyword = 'client_action_relate'
keys = [('action', keyword), ('res_model', res_model)] keys = [('action', keyword), ('res_model', res_model)]
value = 'ir.actions.act_window,'+str(id) value = 'ir.actions.act_window,'+str(id)
replace = rec.hasAttribute('replace') and rec.getAttribute('replace') or True replace = rec.get('replace','') or True
self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, xml_id, [src_model], value, replace=replace, isobject=True, xml_id=xml_id) self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', keyword, xml_id, [src_model], value, replace=replace, isobject=True, xml_id=xml_id)
# TODO add remove ir.model.data # TODO add remove ir.model.data
return False return False
@ -448,8 +438,8 @@ form: module.record_id""" % (xml_id,)
if not self.mode=='init': if not self.mode=='init':
return False return False
res = {} res = {}
for field in [i for i in rec.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=="field")]: for field in [i for i in rec.getchildren() if (i.tag=="field")]:
f_name = field.getAttribute("name").encode('utf-8') f_name = field.get("name",'').encode('utf-8')
f_val = _eval_xml(self,field,self.pool, cr, self.uid, self.idref) f_val = _eval_xml(self,field,self.pool, cr, self.uid, self.idref)
res[f_name] = f_val res[f_name] = f_val
self.pool.get('ir.model.data').ir_set(cr, self.uid, res['key'], res['key2'], res['name'], res['models'], res['value'], replace=res.get('replace',True), isobject=res.get('isobject', False), meta=res.get('meta',None)) self.pool.get('ir.model.data').ir_set(cr, self.uid, res['key'], res['key2'], res['name'], res['models'], res['value'], replace=res.get('replace',True), isobject=res.get('isobject', False), meta=res.get('meta',None))
@ -458,21 +448,21 @@ form: module.record_id""" % (xml_id,)
def _tag_workflow(self, cr, rec, data_node=None): def _tag_workflow(self, cr, rec, data_node=None):
if self.isnoupdate(data_node) and self.mode != 'init': if self.isnoupdate(data_node) and self.mode != 'init':
return return
model = str(rec.getAttribute('model')) model = str(rec.get('model',''))
w_ref = rec.getAttribute('ref') w_ref = rec.get('ref','')
if len(w_ref): if len(w_ref):
id = self.id_get(cr, model, w_ref) id = self.id_get(cr, model, w_ref)
else: else:
assert rec.childNodes, 'You must define a child node if you dont give a ref' assert rec.getchildren(), 'You must define a child node if you dont give a ref'
element_childs = [i for i in rec.childNodes if i.nodeType == i.ELEMENT_NODE] element_childs = [i for i in rec.getchildren()]
assert len(element_childs) == 1, 'Only one child node is accepted (%d given)' % len(rec.childNodes) assert len(element_childs) == 1, 'Only one child node is accepted (%d given)' % len(rec.getchildren())
id = _eval_xml(self, element_childs[0], self.pool, cr, self.uid, self.idref) id = _eval_xml(self, element_childs[0], self.pool, cr, self.uid, self.idref)
uid = self.get_uid(cr, self.uid, data_node, rec) uid = self.get_uid(cr, self.uid, data_node, rec)
wf_service = netsvc.LocalService("workflow") wf_service = netsvc.LocalService("workflow")
wf_service.trg_validate(uid, model, wf_service.trg_validate(uid, model,
id, id,
str(rec.getAttribute('action')), cr) str(rec.get('action','')), cr)
return False return False
# #
@ -483,12 +473,12 @@ form: module.record_id""" % (xml_id,)
# parent="parent_id" # parent="parent_id"
# #
def _tag_menuitem(self, cr, rec, data_node=None): def _tag_menuitem(self, cr, rec, data_node=None):
rec_id = rec.getAttribute("id").encode('ascii') rec_id = rec.get("id",'').encode('ascii')
self._test_xml_id(rec_id) self._test_xml_id(rec_id)
m_l = map(escape, escape_re.split(rec.getAttribute("name").encode('utf8'))) m_l = map(escape, escape_re.split(rec.get("name",'').encode('utf8')))
values = {'parent_id': False} values = {'parent_id': False}
if not rec.hasAttribute('parent'): if not rec.get('parent'):
pid = False pid = False
for idx, menu_elem in enumerate(m_l): for idx, menu_elem in enumerate(m_l):
if pid: if pid:
@ -500,7 +490,7 @@ form: module.record_id""" % (xml_id,)
values = {'parent_id': pid,'name':menu_elem} values = {'parent_id': pid,'name':menu_elem}
elif res: elif res:
pid = res[0] pid = res[0]
xml_id = idx==len(m_l)-1 and rec.getAttribute('id').encode('utf8') xml_id = idx==len(m_l)-1 and rec.get('id','').encode('utf8')
try: try:
npid = self.pool.get('ir.model.data')._update_dummy(cr, self.uid, 'ir.ui.menu', self.module, xml_id, idx==len(m_l)-1) npid = self.pool.get('ir.model.data')._update_dummy(cr, self.uid, 'ir.ui.menu', self.module, xml_id, idx==len(m_l)-1)
except: except:
@ -510,18 +500,18 @@ form: module.record_id""" % (xml_id,)
self.logger.notifyChannel("init", netsvc.LOG_WARNING, 'Warning no ID for submenu %s of menu %s !' % (menu_elem, str(m_l))) self.logger.notifyChannel("init", netsvc.LOG_WARNING, 'Warning no ID for submenu %s of menu %s !' % (menu_elem, str(m_l)))
pid = self.pool.get('ir.ui.menu').create(cr, self.uid, {'parent_id' : pid, 'name' : menu_elem}) pid = self.pool.get('ir.ui.menu').create(cr, self.uid, {'parent_id' : pid, 'name' : menu_elem})
else: else:
menu_parent_id = self.id_get(cr, 'ir.ui.menu', rec.getAttribute('parent')) menu_parent_id = self.id_get(cr, 'ir.ui.menu', rec.get('parent',''))
values = {'parent_id': menu_parent_id} values = {'parent_id': menu_parent_id}
if rec.hasAttribute('name'): if rec.get('name'):
values['name'] = rec.getAttribute('name') values['name'] = rec.get('name','')
try: try:
res = [ self.id_get(cr, 'ir.ui.menu', rec.getAttribute('id')) ] res = [ self.id_get(cr, 'ir.ui.menu', rec.get('id','')) ]
except: except:
res = None res = None
if rec.hasAttribute('action'): if rec.get('action'):
a_action = rec.getAttribute('action').encode('utf8') a_action = rec.get('action','').encode('utf8')
a_type = rec.getAttribute('type').encode('utf8') or 'act_window' a_type = rec.get('type','').encode('utf8') or 'act_window'
icons = { icons = {
"act_window": 'STOCK_NEW', "act_window": 'STOCK_NEW',
"report.xml": 'STOCK_PASTE', "report.xml": 'STOCK_PASTE',
@ -560,13 +550,13 @@ form: module.record_id""" % (xml_id,)
resw = cr.fetchone() resw = cr.fetchone()
if (not values.get('name', False)) and resw: if (not values.get('name', False)) and resw:
values['name'] = resw[0] values['name'] = resw[0]
if rec.hasAttribute('sequence'): if rec.get('sequence'):
values['sequence'] = int(rec.getAttribute('sequence')) values['sequence'] = int(rec.get('sequence',''))
if rec.hasAttribute('icon'): if rec.get('icon'):
values['icon'] = str(rec.getAttribute('icon')) values['icon'] = str(rec.get('icon',''))
if rec.hasAttribute('groups'): if rec.get('groups'):
g_names = rec.getAttribute('groups').split(',') g_names = rec.get('groups','').split(',')
groups_value = [] groups_value = []
groups_obj = self.pool.get('res.groups') groups_obj = self.pool.get('res.groups')
for group in g_names: for group in g_names:
@ -578,16 +568,16 @@ form: module.record_id""" % (xml_id,)
groups_value.append((4, group_id)) groups_value.append((4, group_id))
values['groups_id'] = groups_value values['groups_id'] = groups_value
xml_id = rec.getAttribute('id').encode('utf8') xml_id = rec.get('id','').encode('utf8')
self._test_xml_id(xml_id) self._test_xml_id(xml_id)
pid = self.pool.get('ir.model.data')._update(cr, self.uid, 'ir.ui.menu', self.module, values, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode, res_id=res and res[0] or False) pid = self.pool.get('ir.model.data')._update(cr, self.uid, 'ir.ui.menu', self.module, values, xml_id, noupdate=self.isnoupdate(data_node), mode=self.mode, res_id=res and res[0] or False)
if rec_id and pid: if rec_id and pid:
self.idref[rec_id] = int(pid) self.idref[rec_id] = int(pid)
if rec.hasAttribute('action') and pid: if rec.get('action') and pid:
a_action = rec.getAttribute('action').encode('utf8') a_action = rec.get('action','').encode('utf8')
a_type = rec.getAttribute('type').encode('utf8') or 'act_window' a_type = rec.get('type','').encode('utf8') or 'act_window'
a_id = self.id_get(cr, 'ir.actions.%s' % a_type, a_action) a_id = self.id_get(cr, 'ir.actions.%s' % a_type, a_action)
action = "ir.actions.%s,%d" % (a_type, a_id) action = "ir.actions.%s,%d" % (a_type, a_id)
self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', 'tree_but_open', 'Menuitem', [('ir.ui.menu', int(pid))], action, True, True, xml_id=rec_id) self.pool.get('ir.model.data').ir_set(cr, self.uid, 'action', 'tree_but_open', 'Menuitem', [('ir.ui.menu', int(pid))], action, True, True, xml_id=rec_id)
@ -600,17 +590,17 @@ form: module.record_id""" % (xml_id,)
if self.isnoupdate(data_node) and self.mode != 'init': if self.isnoupdate(data_node) and self.mode != 'init':
return return
rec_model = rec.getAttribute("model").encode('ascii') rec_model = rec.get("model",'').encode('ascii')
model = self.pool.get(rec_model) model = self.pool.get(rec_model)
assert model, "The model %s does not exist !" % (rec_model,) assert model, "The model %s does not exist !" % (rec_model,)
rec_id = rec.getAttribute("id").encode('ascii') rec_id = rec.get("id",'').encode('ascii')
self._test_xml_id(rec_id) self._test_xml_id(rec_id)
rec_src = rec.getAttribute("search").encode('utf8') rec_src = rec.get("search",'').encode('utf8')
rec_src_count = rec.getAttribute("count") rec_src_count = rec.get("count",'')
severity = rec.getAttribute("severity").encode('ascii') or netsvc.LOG_ERROR severity = rec.get("severity",'').encode('ascii') or netsvc.LOG_ERROR
rec_string = rec.getAttribute("string").encode('utf8') or 'unknown' rec_string = rec.get("string",'').encode('utf8') or 'unknown'
ids = None ids = None
eval_dict = {'ref': _ref(self, cr)} eval_dict = {'ref': _ref(self, cr)}
@ -651,8 +641,8 @@ form: module.record_id""" % (xml_id,)
globals['floatEqual'] = self._assert_equals globals['floatEqual'] = self._assert_equals
globals['ref'] = ref globals['ref'] = ref
globals['_ref'] = ref globals['_ref'] = ref
for test in [i for i in rec.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=="test")]: for test in [i for i in rec.getchildren() if (i.tag=="test")]:
f_expr = test.getAttribute("expr").encode('utf-8') f_expr = test.get("expr",'').encode('utf-8')
expected_value = _eval_xml(self, test, self.pool, cr, uid, self.idref, context=context) or True expected_value = _eval_xml(self, test, self.pool, cr, uid, self.idref, context=context) or True
expression_value = eval(f_expr, globals) expression_value = eval(f_expr, globals)
if expression_value != expected_value: # assertion failed if expression_value != expected_value: # assertion failed
@ -661,7 +651,7 @@ form: module.record_id""" % (xml_id,)
' xmltag: %s\n' \ ' xmltag: %s\n' \
' expected value: %r\n' \ ' expected value: %r\n' \
' obtained value: %r\n' \ ' obtained value: %r\n' \
% (rec_string, test.toxml(), expected_value, expression_value) % (rec_string, etree.tostring(test), expected_value, expression_value)
self.logger.notifyChannel('init', severity, msg) self.logger.notifyChannel('init', severity, msg)
sevval = getattr(logging, severity.upper()) sevval = getattr(logging, severity.upper())
if sevval >= config['assert_exit_level']: if sevval >= config['assert_exit_level']:
@ -672,12 +662,11 @@ form: module.record_id""" % (xml_id,)
self.assert_report.record_assertion(True, severity) self.assert_report.record_assertion(True, severity)
def _tag_record(self, cr, rec, data_node=None): def _tag_record(self, cr, rec, data_node=None):
rec_model = rec.getAttribute("model").encode('ascii') rec_model = rec.get("model").encode('ascii')
model = self.pool.get(rec_model) model = self.pool.get(rec_model)
assert model, "The model %s does not exist !" % (rec_model,) assert model, "The model %s does not exist !" % (rec_model,)
rec_id = rec.getAttribute("id").encode('ascii') rec_id = rec.get("id",'').encode('ascii')
self._test_xml_id(rec_id) self._test_xml_id(rec_id)
if self.isnoupdate(data_node) and self.mode != 'init': if self.isnoupdate(data_node) and self.mode != 'init':
# check if the xml record has an id string # check if the xml record has an id string
if rec_id: if rec_id:
@ -703,17 +692,16 @@ form: module.record_id""" % (xml_id,)
else: else:
# otherwise it is skipped # otherwise it is skipped
return None return None
res = {} res = {}
for field in [i for i in rec.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=="field")]: for field in [i for i in rec.getchildren() if (i.tag == "field")]:
#TODO: most of this code is duplicated above (in _eval_xml)... #TODO: most of this code is duplicated above (in _eval_xml)...
f_name = field.getAttribute("name").encode('utf-8') f_name = field.get("name",'').encode('utf-8')
f_ref = field.getAttribute("ref").encode('ascii') f_ref = field.get("ref",'').encode('ascii')
f_search = field.getAttribute("search").encode('utf-8') f_search = field.get("search",'').encode('utf-8')
f_model = field.getAttribute("model").encode('ascii') f_model = field.get("model",'').encode('ascii')
if not f_model and model._columns.get(f_name,False): if not f_model and model._columns.get(f_name,False):
f_model = model._columns[f_name]._obj f_model = model._columns[f_name]._obj
f_use = field.getAttribute("use").encode('ascii') or 'id' f_use = field.get("use",'').encode('ascii') or 'id'
f_val = False f_val = False
if len(f_search): if len(f_search):
@ -761,24 +749,22 @@ form: module.record_id""" % (xml_id,)
return int(self.pool.get('ir.model.data').read(cr, self.uid, [result], ['res_id'])[0]['res_id']) return int(self.pool.get('ir.model.data').read(cr, self.uid, [result], ['res_id'])[0]['res_id'])
def parse(self, xmlstr): def parse(self, xmlstr):
d = xml.dom.minidom.parseString(xmlstr) de = etree.XML(xmlstr)
de = d.documentElement
if not de.nodeName in ['terp', 'openerp']: if not de.tag in ['terp', 'openerp']:
self.logger.notifyChannel("init", netsvc.LOG_ERROR, "Mismatch xml format" ) self.logger.notifyChannel("init", netsvc.LOG_ERROR, "Mismatch xml format" )
raise Exception( "Mismatch xml format: only terp or openerp as root tag" ) raise Exception( "Mismatch xml format: only terp or openerp as root tag" )
if de.nodeName == 'terp': if de.tag == 'terp':
self.logger.notifyChannel("init", netsvc.LOG_WARNING, "The tag <terp/> is deprecated, use <openerp/>") self.logger.notifyChannel("init", netsvc.LOG_WARNING, "The tag <terp/> is deprecated, use <openerp/>")
for n in [i for i in de.childNodes if (i.nodeType == i.ELEMENT_NODE and i.nodeName=="data")]: for n in [i for i in de.getchildren() if (i.tag=="data")]:
for rec in n.childNodes: for rec in n.getchildren():
if rec.nodeType == rec.ELEMENT_NODE: if rec.tag in self._tags:
if rec.nodeName in self._tags:
try: try:
self._tags[rec.nodeName](self.cr, rec, n) self._tags[rec.tag](self.cr, rec, n)
except: except:
self.logger.notifyChannel("init", netsvc.LOG_ERROR, '\n'+rec.toxml()) self.logger.notifyChannel("init", netsvc.LOG_ERROR, '\n'+etree.tostring(rec))
self.cr.rollback() self.cr.rollback()
raise raise
return True return True
@ -891,11 +877,13 @@ def convert_xml_export(res):
pool=pooler.get_pool(cr.dbname) pool=pooler.get_pool(cr.dbname)
cr=pooler.db.cursor() cr=pooler.db.cursor()
idref = {} idref = {}
d = xml.dom.minidom.getDOMImplementation().createDocument(None, "terp", None)
de = d.documentElement page = etree.Element ( 'terp' )
data=d.createElement("data") doc = etree.ElementTree ( page )
de.appendChild(data) data = etree.SubElement ( page, 'data' )
de.appendChild(d.createTextNode('Some textual content.')) text_node = etree.SubElement ( page, 'text' )
text_node.text = 'Some textual content.'
cr.commit() cr.commit()
cr.close() cr.close()

View File

@ -23,9 +23,9 @@
import os import os
from os.path import join from os.path import join
import fnmatch import fnmatch
import csv, xml.dom, re import csv, re
from lxml import etree
import tools, pooler import tools, pooler
from osv.orm import BrowseRecordError
import ir import ir
import netsvc import netsvc
from tools.misc import UpdateableStr from tools.misc import UpdateableStr
@ -335,9 +335,9 @@ def trans_export(lang, modules, buffer, format, dbname=None):
def trans_parse_xsl(de): def trans_parse_xsl(de):
res = [] res = []
for n in [i for i in de.childNodes if (i.nodeType == i.ELEMENT_NODE)]: for n in [i for i in de.getchildren()]:
if n.hasAttribute("t"): if n.get("t"):
for m in [j for j in n.childNodes if (j.nodeType == j.TEXT_NODE)]: for m in [j for j in n.getchildren()]:
l = m.data.strip().replace('\n',' ') l = m.data.strip().replace('\n',' ')
if len(l): if len(l):
res.append(l.encode("utf8")) res.append(l.encode("utf8"))
@ -346,8 +346,8 @@ def trans_parse_xsl(de):
def trans_parse_rml(de): def trans_parse_rml(de):
res = [] res = []
for n in [i for i in de.childNodes if (i.nodeType == i.ELEMENT_NODE)]: for n in [i for i in de.getchildren()]:
for m in [j for j in n.childNodes if (j.nodeType == j.TEXT_NODE)]: for m in [j for j in n.getchildren()]:
string_list = [s.replace('\n', ' ').strip() for s in re.split('\[\[.+?\]\]', m.data)] string_list = [s.replace('\n', ' ').strip() for s in re.split('\[\[.+?\]\]', m.data)]
for s in string_list: for s in string_list:
if s: if s:
@ -357,15 +357,15 @@ def trans_parse_rml(de):
def trans_parse_view(de): def trans_parse_view(de):
res = [] res = []
if de.hasAttribute("string"): if de.get("string"):
s = de.getAttribute('string') s = de.get('string')
if s: if s:
res.append(s.encode("utf8")) res.append(s.encode("utf8"))
if de.hasAttribute("sum"): if de.get("sum"):
s = de.getAttribute('sum') s = de.get('sum')
if s: if s:
res.append(s.encode("utf8")) res.append(s.encode("utf8"))
for n in [i for i in de.childNodes if (i.nodeType == i.ELEMENT_NODE)]: for n in [i for i in de.getchildren()]:
res.extend(trans_parse_view(n)) res.extend(trans_parse_view(n))
return res return res
@ -434,8 +434,8 @@ def trans_generate(lang, modules, dbname=None):
obj = pool.get(model).browse(cr, uid, res_id) obj = pool.get(model).browse(cr, uid, res_id)
if model=='ir.ui.view': if model=='ir.ui.view':
d = xml.dom.minidom.parseString(encode(obj.arch)) d = etree.XML(encode(obj.arch))
for t in trans_parse_view(d.documentElement): for t in trans_parse_view(d):
push_translation(module, 'view', encode(obj.model), 0, t) push_translation(module, 'view', encode(obj.model), 0, t)
elif model=='ir.actions.wizard': elif model=='ir.actions.wizard':
service_name = 'wizard.'+encode(obj.wiz_name) service_name = 'wizard.'+encode(obj.wiz_name)
@ -522,10 +522,10 @@ def trans_generate(lang, modules, dbname=None):
report_type = "xsl" report_type = "xsl"
try: try:
xmlstr = tools.file_open(fname).read() xmlstr = tools.file_open(fname).read()
d = xml.dom.minidom.parseString(xmlstr) d = etree.XML()(xmlstr)
for t in parse_func(d.documentElement): for t in parse_func(d.getroot()):
push_translation(module, report_type, name, 0, t) push_translation(module, report_type, name, 0, t)
except IOError, xml.dom.expatbuilder.expat.ExpatError: except IOError, etree.expatbuilder.expat.ExpatError:
if fname: if fname:
logger.notifyChannel("i18n", netsvc.LOG_ERROR, "couldn't export translation for report %s %s %s" % (name, report_type, fname)) logger.notifyChannel("i18n", netsvc.LOG_ERROR, "couldn't export translation for report %s %s %s" % (name, report_type, fname))

View File

@ -24,7 +24,7 @@ import netsvc
from tools import copy from tools import copy
from tools.misc import UpdateableStr, UpdateableDict from tools.misc import UpdateableStr, UpdateableDict
from tools.translate import translate from tools.translate import translate
from xml import dom from lxml import etree
import ir import ir
import pooler import pooler
@ -50,13 +50,12 @@ class interface(netsvc.Service):
self.wiz_name = name self.wiz_name = name
def translate_view(self, cr, node, state, lang): def translate_view(self, cr, node, state, lang):
if node.nodeType == node.ELEMENT_NODE: if node.get('string'):
if node.hasAttribute('string') and node.getAttribute('string'): trans = translate(cr, self.wiz_name+','+state, 'wizard_view', lang, node.get('string').encode('utf8'))
trans = translate(cr, self.wiz_name+','+state, 'wizard_view', lang, node.getAttribute('string').encode('utf8'))
if trans: if trans:
node.setAttribute('string', trans) node.set('string', trans)
for n in node.childNodes: for n in node.getchildren():
self.translate_view(cr, n, state, lang) self.translate_view(cr, n, state, lang)
def execute_cr(self, cr, uid, data, state='init', context=None): def execute_cr(self, cr, uid, data, state='init', context=None):
if not context: if not context:
@ -132,9 +131,9 @@ class interface(netsvc.Service):
# translate arch # translate arch
if not isinstance(arch, UpdateableStr): if not isinstance(arch, UpdateableStr):
doc = dom.minidom.parseString(arch.encode('utf8')) doc = etree.XML(arch)
self.translate_view(cr, doc, state, lang) self.translate_view(cr, doc, state, lang)
arch = doc.toxml() arch = etree.tostring(doc)
# translate buttons # translate buttons
button_list = list(button_list) button_list = list(button_list)