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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 OpenERP SA (<http://openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
"""
Experimental script for conversion between OpenERP's XML serialization format
and the new YAML serialization format introduced in OpenERP 6.0.
Intended to be used as a quick preprocessor for converting data/test files, then
to be fine-tuned manually.
"""
import yaml
import logging
from lxml import etree
__VERSION__ = '0.0.2'
def toString(value):
value='"' + value + '"'
return value
class XmlTag(etree.ElementBase):
def _to_yaml(self):
child_tags = []
for node in self:
if hasattr(node, '_to_yaml'):
child_tags.append(node._to_yaml())
return self.tag(attrib=self.attrib, child_tags=child_tags)
class YamlTag(object):
"""
Superclass for constructors of custom tags defined in yaml file.
"""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
self.attrib = self.__dict__.get('attrib', {})
self.child_tags = self.__dict__.get('child_tags', '')
def __getitem__(self, key):
return getattr(self, key)
def __getattr__(self, attr):
return None
def __repr__(self):
for k,v in self.attrib.iteritems():
if str(v) and str(v)[0] in ['[', '{', '#', '*', '(']:
self.attrib[k] = toString(self.attrib[k]).replace("'", '')
st = self.yaml_tag + ' ' + str(self.attrib)
return st
# attrib tags
class ref(YamlTag):
yaml_tag = u'!ref'
def __init__(self, expr="False"):
self.expr = expr
def __repr__(self):
return "'%s'"%str(self.expr)
class Eval(YamlTag):
yaml_tag = u'!eval'
def __init__(self, expr="False"):
self.expr = expr
def __repr__(self):
value=str(self.expr)
if value.find("6,") != -1:
value = eval(str(eval(value)))
value=value[0][2]
value = [[value]]
else:
try:
value=int(value)
except:
if value and value[0] in ['[', '{', '#', '*', '(']:
value = value.replace('"', r'\"')
value = toString(value)
else:
try:
value = eval(value)
except Exception:
pass
return value
class Search(YamlTag):
yaml_tag = u'!ref'
# test tag
class xml_test(XmlTag):
def _to_yaml(self):
expr = self.attrib.get('expr')
text = self.text
if text:
expr = expr + ' == ' + '"%s"'%text
return [[expr]]
class xml_data(etree.ElementBase):
def _to_yaml(self):
value = self.attrib.get('noupdate', "0")
return data(value)
# field tag:
class xml_field(etree.ElementBase):
def _to_yaml(self):
field = ' ' + self.attrib.pop('name','unknown')
if self.attrib.get('search', None):
value = Search(attrib=self.attrib, child_tags='').__repr__()
else:
attr = (self.attrib.get('ref', None) and 'ref') or (self.attrib.get('eval', None) and 'eval') or 'None'
value = Eval(self.attrib.get(attr, self.text)).__repr__() or ''
return {field: value}
# value tag
class xml_value(etree.ElementBase):
def _to_yaml(self):
if self.attrib.get('eval', None):
key, val = 'eval', '"'+self.attrib.get('eval')+'"'
elif self.attrib.get('model', None):
key, val = 'model', self.attrib.get('model')
val=val.replace("'",'""')
self.attrib.pop(key)
d={}
for k,v in self.attrib.iteritems():
if k == 'search':
v = '"' + v + '"'
k='--' + k
v=v.replace("'",'""')
d[k] = v
if d:
ls=[[{key:val},dict(d)]]
else:
ls=[[{key:val}]]
return ls
# data tag
class data(YamlTag):
yaml_tag = u'!context'
def __init__(self, noupdate="0"):
self.child_tags = {' noupdate':noupdate}
def __repr__(self):
return "!!context"
# Record tag
class Record(YamlTag):
yaml_tag = u'!record'
class xml_record(XmlTag):
tag=Record
def _to_yaml(self):
child_tags = {}
for node in self:
if hasattr(node, '_to_yaml'):
child_tags.update(node._to_yaml())
return Record(attrib=self.attrib, child_tags=child_tags)
# ir_set tag
class Ir_Set(YamlTag):
yaml_tag = u'!ir_set'
def __repr__(self):
st = self.yaml_tag
return st
class xml_ir_set(XmlTag):
tag=Ir_Set
def _to_yaml(self):
child_tags = {}
for node in self:
if hasattr(node, '_to_yaml'):
child_tags.update(node._to_yaml())
return Ir_Set(attrib=self.attrib, child_tags=child_tags)
# workflow tag
class Workflow(YamlTag):
yaml_tag = u'!workflow'
class xml_workflow(XmlTag):
tag=Workflow
# function tag
class Function(YamlTag):
yaml_tag = u'!function'
class xml_function(XmlTag):
tag=Function
# function tag
class Assert(YamlTag):
yaml_tag = u'!assert'
class xml_assert(XmlTag):
tag=Assert
# menuitem tagresult.append(yaml.safe_dump(obj, default_flow_style=False, allow_unicode=True).replace("'",''))
class MenuItem(YamlTag):
yaml_tag = u'!menuitem'
class xml_menuitem(XmlTag):
tag=MenuItem
# act_window tag
class ActWindow(YamlTag):
yaml_tag = u'!act_window'
class xml_act_window(XmlTag):
tag=ActWindow
# report tag
class Report(YamlTag):
yaml_tag = u'!report'
class xml_report(XmlTag):
tag=Report
# deletes tag
class Delete(YamlTag):
yaml_tag = u'!delete'
class xml_delete(XmlTag):
tag=Delete
# python tag
class Python(YamlTag):
yaml_tag = u'!python'
class xml_python(XmlTag):
tag=Python
# context tag
class Context(YamlTag):
yaml_tag = u'!context'
class xml_context(XmlTag):
tag=Context
# url tag
class Url(YamlTag):
yaml_tag = u'!url'
class xml_url(XmlTag):
tag=Url
# delete tag
class Delete(YamlTag):
yaml_tag = u'!delete'
class xml_delete(XmlTag):
tag=Delete
def represent_data(dumper, data):
return dumper.represent_mapping(u'tag:yaml.org,2002:map', [('!'+str(data), data.child_tags)])
yaml.SafeDumper.add_representer(Record, represent_data)
yaml.SafeDumper.add_representer(data, represent_data)
yaml.SafeDumper.add_representer(Workflow, represent_data)
yaml.SafeDumper.add_representer(Function, represent_data)
yaml.SafeDumper.add_representer(Assert, represent_data)
yaml.SafeDumper.add_representer(MenuItem, represent_data)
yaml.SafeDumper.add_representer(Ir_Set, represent_data)
yaml.SafeDumper.add_representer(Python, represent_data)
yaml.SafeDumper.add_representer(Context, represent_data)
class MyLookup(etree.CustomElementClassLookup):
def lookup(self, node_type, document, namespace, name):
if node_type=='element':
return {
'data': xml_data,
'record': xml_record,
'field': xml_field,
'workflow': xml_workflow,
'function': xml_function,
'value': xml_value,
'assert': xml_assert,
'test': xml_test,
'menuitem': xml_menuitem,
'act_window': xml_act_window,
'report': xml_report,
'delete': xml_delete,
'python': xml_python,
'context': xml_context,
'url': xml_url,
'ir_set': xml_ir_set,
}.get(name, None)
elif node_type=='comment':
return None#xml_comment
return None
class xml_parse(object):
def __init__(self):
self.context = {}
def parse(self, fname):
parser = etree.XMLParser()
parser.setElementClassLookup(MyLookup())
result = []
self.root = etree.XML(file(fname).read(), parser)
for data in self.root:
if hasattr(data, '_to_yaml'):
obj = data._to_yaml()
if obj.yaml_tag == '!context':
result.append(yaml.dump(str(obj)).replace("'",'').split('\n')[0])
result.append(yaml.dump(obj.child_tags, default_flow_style=False).replace("'",''))
else:
result.append(yaml.safe_dump(obj, default_flow_style=False, allow_unicode=True).replace("'",''))
self.context.update(data.attrib)
for tag in data:
if tag.tag == etree.Comment:
result.append(tag)
else:
if hasattr(tag, '_to_yaml'):
obj = tag._to_yaml()
if not obj.child_tags:
result.append(yaml.dump('!'+str(obj), default_flow_style=False, allow_unicode=True, width=999).replace("'",''))
else:
result.append(yaml.safe_dump(obj, default_flow_style=False, allow_unicode=True, width=999).replace('\n:', ':\n').replace("'",''))
print "# Experimental OpenERP xml-to-yml conversion! (v%s)"%__VERSION__
print "# Please use this as a first conversion/preprocessing step,"
print "# not as a production-ready tool!"
for record in result:
if type(record) != type(''):
record=str(record)
l= record.split("\n")
for line in l:
print '#' + str(line)
continue
record=str(record)
record = record.replace('- --',' ') #for value tag
record = record.replace('!!', '- \n !') #for all parent tags
record = record.replace('- - -', ' -') #for many2many fields
record = record.replace('? ', '') #for long expressions
record = record.replace('""', "'") #for string-value under value tag
print record
if __name__=='__main__':
import optparse
import sys
parser = optparse.OptionParser(
usage = '%s file.xml' % sys.argv[0])
(opt, args) = parser.parse_args()
if len(args) != 1:
parser.error("incorrect number of arguments")
fname = sys.argv[1]
p = xml_parse()
p.parse(fname)
|