forked from OCA/server-tools
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpatch_xml_import.py
1556 lines (1346 loc) · 56.1 KB
/
patch_xml_import.py
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
import logging
import re
from lxml import etree
from odoo.exceptions import ValidationError
from odoo.tools import mute_logger
from odoo.tools.misc import file_open
from odoo.tools.template_inheritance import locate_node
_logger = logging.getLogger(__name__)
from odoo.tools.convert import xml_import
original_tag_record = xml_import._tag_record
def new_tag_record(self, rec, extra_vals=None):
rec_model = rec.get("model")
if rec_model == "ir.ui.view":
_convert_ir_ui_view_modifiers(self, rec, extra_vals=extra_vals)
return original_tag_record(self, rec, extra_vals=extra_vals)
xml_import._tag_record = new_tag_record
def _convert_ir_ui_view_modifiers(self, record_node, extra_vals=None):
rec_id = record_node.get("id", "")
f_model = record_node.find('field[@name="model"]')
f_type = record_node.find('field[@name="type"]')
f_inherit = record_node.find('field[@name="inherit_id"]')
f_arch = record_node.find('field[@name="arch"]')
root = f_arch if f_arch is not None else record_node
ref = f"{rec_id} ({self.xml_filename})"
try:
data_id = f_inherit is not None and f_inherit.get("ref")
inherit = None
if data_id:
if "." not in data_id:
data_id = f"{self.module}.{data_id}"
inherit = self.env.ref(data_id)
model_name = f_model is not None and f_model.text
if not model_name and inherit:
model_name = inherit.model
if not model_name:
return
view_type = f_type is not None and f_type.text or root[0].tag
if inherit:
view_type = inherit.type
if view_type not in ("kanban", "tree", "form", "calendar", "setting", "search"):
return
# load previous arch
arch = None
previous_xml = file_open(self.xml_filename, "r").read()
match = re.search(
rf"""(<record [^>]*id=['"]{rec_id}['"][^>]*>(?:[^<]|<(?!/record>))+</record>)""",
previous_xml,
)
if not match:
_logger.error(f"Can not found {rec_id!r} from {self.xml_filename}")
return
record_xml = match.group(1)
match = re.search(
r"""(<field [^>]*name=["']arch["'][^>]*>((.|\n)+)</field>)""", record_xml
)
if not match:
_logger.error(f"Can not found arch of {rec_id!r} from {self.xml_filename}")
return
arch = match.group(2).strip()
# load inherited arch
inherited_root = inherit and etree.fromstring(inherit.get_combined_arch())
head = False
added_data = False
arch_clean = arch
if arch_clean.startswith("<?"):
head, arch_clean = arch_clean.split("\n", 1)
if not arch_clean.startswith("<data>"):
added_data = True
arch_clean = f"<data>{arch_clean}</data>"
root_content = etree.fromstring(arch_clean)
model = self.env[model_name]
try:
arch_result = convert_template_modifiers(
self.env,
arch_clean,
root_content,
model,
view_type,
ref,
inherited_root=inherited_root,
)
except Exception as e:
_logger.error(f"Can not convert: {rec_id!r} from {self.xml_filename}\n{e}")
return
if re.sub(rf"(\n| )*{reg_comment}(\n| )*", "", arch_result) == "<data></data>":
_logger.error(
f"No uncommented element found: {rec_id!r} from {self.xml_filename}"
)
arch_result = (
arch_result[:6]
+ '<field position="attributes" help="add to avoid error when convert"/>'
+ arch_result[6:]
)
if added_data:
arch_result = arch_result[6:-7]
if head:
arch_result = head + arch_result
if arch_result != arch:
if added_data:
while len(f_arch):
f_arch.remove(f_arch[0])
for n in root_content:
f_arch.append(n)
f_arch.text = root_content.text
new_xml = previous_xml.replace(arch, arch_result)
with file_open(self.xml_filename, "w") as file:
file.write(new_xml)
try:
# test file before save
etree.fromstring(new_xml.encode())
except Exception as e:
_logger.error(
f"Wrong view conversion in {rec_id!r} from {self.xml_filename}\n\n{arch}\n\n{e}"
)
return
except Exception as e:
_logger.error("FAIL ! %s\n%s", ref, e)
import itertools
from odoo.osv.expression import (
AND_OPERATOR,
DOMAIN_OPERATORS,
FALSE_LEAF,
NOT_OPERATOR,
OR_OPERATOR,
TERM_OPERATORS,
TRUE_LEAF,
distribute_not,
normalize_domain,
)
from odoo.tools import apply_inheritance_specs, locate_node, mute_logger
# from odoo import tools
from odoo.tools.misc import str2bool, unique
from odoo.tools.safe_eval import _BUILTINS
from odoo.tools.view_validation import (
_get_expression_contextual_values,
get_domain_value_names,
get_expression_field_names,
)
VALID_TERM_OPERATORS = TERM_OPERATORS + ("<>", "==")
AST_OP_TO_STR = {
ast.Eq: "==",
ast.NotEq: "!=",
ast.Lt: "<",
ast.LtE: "<=",
ast.Gt: ">",
ast.GtE: ">=",
ast.Is: "is",
ast.IsNot: "is not",
ast.In: "in",
ast.NotIn: "not in",
ast.Add: "+",
ast.Sub: "-",
ast.Mult: "*",
ast.Div: "/",
ast.FloorDiv: "//",
ast.Mod: "%",
ast.Pow: "^",
}
class InvalidDomainError(ValueError):
"""Domain can contain only '!', '&', '|', tuples or expression whose returns boolean"""
#######################################################################
def convert_template_modifiers(
env, arch, root, rec_model, view_type, ref, inherited_root=None
):
"""Convert old syntax (attrs, states...) into new modifiers syntax"""
result = arch
if not arch.startswith("<data>"):
raise ValueError(
f"Wrong formating for view conversion. Arch must be wrapped with <data>: {ref!r}\n{arch}"
)
if inherited_root is None: # this is why it must be False
result = convert_basic_view(arch, root, env, rec_model, view_type, ref)
else:
result = convert_inherit_view(
arch, root, env, rec_model, view_type, ref, inherited_root
)
if not result.startswith("<data>"):
raise ValueError(
f"View conversion failed. Result should had been wrapped with <data>: {ref!r}\n{result}"
)
root_result = etree.fromstring(result.encode())
# Check for incomplete conversion, those attributes should had been removed by
# convert_basic_view and convert_inherit_view. In case there are some left
# just log an error but keep the converted view in the database/file.
for item in root_result.findall('.//attribute[@name="states"]'):
xml = etree.tostring(item, encoding="unicode")
_logger.error('Incomplete view conversion ("states"): %r\n%s', ref, xml)
for item in root_result.findall('.//attribute[@name="attrs"]'):
xml = etree.tostring(item, encoding="unicode")
_logger.error('Incomplete view conversion ("attrs"): %r\n%s', ref, xml)
for item in root_result.findall(".//*[@attrs]"):
xml = etree.tostring(item, encoding="unicode")
_logger.error('Incomplete view conversion ("attrs"): %r\n%s', ref, xml)
for item in root_result.findall(".//*[@states]"):
xml = etree.tostring(item, encoding="unicode")
_logger.error('Incomplete view conversion ("states"): %r\n%s', ref, xml)
return result
def convert_basic_view(arch, root, env, model, view_type, ref):
updated_nodes, _analysed_nodes = convert_node_modifiers_inplace(
root, env, model, view_type, ref
)
if not updated_nodes:
return arch
return replace_and_keep_indent(root, arch, ref)
def convert_inherit_view(arch, root, env, model, view_type, ref, inherited_root):
updated = False
result = arch
def get_target(spec):
target_node = None
try:
with mute_logger("odoo.tools.template_inheritance"):
target_node = locate_node(inherited_root, spec)
# target can be None without error
except Exception:
pass
if target_node is None:
clone = etree.tostring(
etree.Element(spec.tag, spec.attrib), encoding="unicode"
)
_logger.info("Target not found for %s with xpath: %s", ref, clone)
return None, view_type, model
parent_view_type = view_type
target_model = model
parent_f_names = []
for p in target_node.iterancestors():
if (
p.tag == "field" or p.tag == "groupby"
): # subview and groupby in tree view
parent_f_names.append(p.get("name"))
for p in target_node.iterancestors():
if p.tag in ("groupby", "header"):
# in tree view
parent_view_type = "form"
break
elif p.tag in ("tree", "form", "setting"):
parent_view_type = p.tag
break
for name in reversed(parent_f_names):
try:
field = target_model._fields[name]
target_model = env[field.comodel_name]
except KeyError:
# Model is custom or had been removed. Can convert view without using field python states
if name in target_model._fields:
_logger.warning(
"Unknown model %s. The <field> modifiers may be incompletely converted. %s",
target_model._fields[name].comodel_name,
ref,
)
else:
_logger.warning(
"Unknown field %s on model %s. The <field> modifiers may be incompletely converted. %s",
name,
target_model,
ref,
)
target_model = None
break
return target_node, parent_view_type, target_model
specs = []
for spec in root:
if isinstance(spec.tag, str):
if spec.tag == "data":
specs.extend(c for c in spec)
else:
specs.append(spec)
for spec in specs:
spec_xml = get_targeted_xml_content(spec, result)
if spec.get("position") == "attributes":
target_node, parent_view_type, target_model = get_target(spec)
updated = convert_inherit_attributes_inplace(
spec, target_node, parent_view_type
)
xml = (
etree.tostring(spec, pretty_print=True, encoding="unicode")
.replace(""", "'")
.strip()
)
else:
_target_node, parent_view_type, target_model = get_target(spec)
updated = (
convert_node_modifiers_inplace(
spec, env, target_model, parent_view_type, ref
)[0]
or updated
)
xml = replace_and_keep_indent(spec, spec_xml, ref)
try:
with mute_logger("odoo.tools.template_inheritance"):
inherited_root = apply_inheritance_specs(
inherited_root, etree.fromstring(xml)
)
except (ValueError, etree.XPathSyntaxError, ValidationError):
clone = xml.split(">", 1)[0] + ">"
if "%(" in clone:
_logger.info("Can not apply inheritance: %s\nPath: %r", ref, clone)
else:
_logger.error("Can not apply inheritance: %s\nPath: %r", ref, clone)
# updated = True
# xml = xml.replace('--', '- -').replace('--', '- -')
# comment = etree.Comment(f' {xml} ')
# spec.getparent().replace(spec, comment)
# xml = f'<!-- {xml} -->'
except Exception:
_logger.error(
"Can not apply inheritance: %s\nPath: %r",
ref,
xml.split(">", 1)[0] + ">",
)
# updated = True
# xml = xml.replace('--', '- -').replace('--', '- -')
# comment = etree.Comment(f' {xml} ')
# spec.getparent().replace(spec, comment)
# xml = f'<!-- {xml} -->'
if updated:
if spec_xml not in result:
_logger.error(
"Can not apply inheritance: %s\nPath: %r",
ref,
xml.split(">", 1)[0] + ">",
)
else:
result = result.replace(spec_xml, xml, 1)
return result
def convert_inherit_attributes_inplace(spec, target_node, view_type):
"""
convert inherit with <attribute name="attrs"> + <attribute name="invisible">
The conversion is different if attrs and invisible/readonly/required are modified.
(can replace attributes, or use separator " or " to combine with previous)
migration is idempotent, this eg stay unchanged:
<attribute name="invisible">(aaa)</invisible>
<attribute name="invisible">0</attribute>
<attribute name="invisible">1</attribute>
<attribute name="invisible" add="context.get('aaa')" separator=" or "/>
"""
migrated = False
has_change = False
items = {}
to_remove = set()
node = None
for attr in ("attrs", "column_invisible", "invisible", "readonly", "required"):
nnode = spec.find(f'.//attribute[@name="{attr}"]')
if nnode is None:
continue
to_remove.add(nnode)
value = nnode.text and nnode.text.strip()
if value not in ("True", "False", "0", "1"):
node = nnode
if nnode.get("separator") or (value and value[0] == "("):
# previously migrate
migrated = True
break
if attr == "attrs":
try:
value = (
value
and ast.literal_eval(value)
or {"invisible": "", "readonly": "", "required": ""}
)
except Exception as error:
raise ValueError(f'Can not convert "attrs": {value!r}') from error
elif (
attr == "invisible"
and view_type == "tree"
and (
value in ("0", "1", "True", "False")
or (
value.startswith("context")
and " or " not in value
and " and " not in value
)
)
):
attr = "column_invisible"
items[attr] = value
if node is None or not items or migrated:
return has_change
index = spec.index(node)
is_last = spec[-1] == node
domain_attrs = items.pop("attrs", {})
all_attrs = list(set(items) | set(domain_attrs))
all_attrs.sort()
i = len(all_attrs)
next_xml = ""
for attr in all_attrs:
value = items.get(attr)
domain = domain_attrs.get(attr, "")
attr_value = (
domain_to_expression(domain) if isinstance(domain, list) else str(domain)
)
i -= 1
elem = etree.Element("attribute", {"name": attr})
if i or not is_last:
elem.tail = spec.text
else:
elem.tail = spec[-1].tail
spec[-1].tail = spec.text
if value and attr_value:
has_change = True
# replace whole expression
if value in ("False", "0"):
elem.text = attr_value
elif value in ("True", "1"):
elem.text = value
else:
elem.text = f"({value}) or ({attr_value})"
else:
inherited_value = target_node.get(attr) if target_node is not None else None
inherited_context = (
_get_expression_contextual_values(
ast.parse(inherited_value.strip(), mode="eval").body
)
if inherited_value
else set()
)
res_value = value or attr_value or "False"
if inherited_context:
# replace whole expression if replace record value by record value, or context/parent by context/parent
# <field invisible="context.get('a')"/>
# is replaced
#
# <field attrs="{'invisible': [('b', '=', 1)]}"/> => <field invisible="b == 1"/>
# will be combined
#
# <field invisible="context.get('a')" attrs="{'invisible': [('b', '=', 1)]}"/> => <field invisible="context.get('a') or b == 1"/>
# logged because human control is necessary
context = _get_expression_contextual_values(
ast.parse(res_value.strip(), mode="eval").body
)
has_record = any(True for v in context if not v.startswith("context."))
has_context = any(True for v in context if v.startswith("context."))
inherited_has_record = any(
True for v in inherited_context if not v.startswith("context.")
)
inherited_has_context = any(
True for v in inherited_context if v.startswith("context.")
)
if (
has_record == inherited_has_record
and has_context == inherited_has_context
):
elem.text = res_value
if attr_value:
has_change = True
elif has_context and not has_record:
elem.set("add", res_value)
elem.set("separator", " or ")
has_change = True
elif not inherited_has_record:
elem.set("add", res_value)
elem.set("separator", " or ")
has_change = True
elif not value and not attr_value:
has_change = True
elif res_value in ("0", "False", "1", "True"):
elem.text = res_value
has_change = True
else:
elem.set("add", res_value)
elem.set("separator", " or ")
has_change = True
_logger.info(
"The migration of attributes inheritance might not be exact: %s",
etree.tostring(elem, encoding="unicode"),
)
elif not value and not attr_value:
continue
else:
elem.text = res_value
if attr_value:
has_change = True
spec.insert(index, elem)
index += 1
# remove previous node and xml
for node in to_remove:
spec.remove(node)
return has_change
def convert_node_modifiers_inplace(root, env, model, view_type, ref):
"""Convert inplace old syntax (attrs, states...) into new modifiers syntax"""
updated_nodes = set()
analysed_nodes = set()
def expr_to_attr(item, py_field_modifiers=None, field=None):
if item in analysed_nodes:
return
analysed_nodes.add(item)
try:
modifiers = extract_node_modifiers(item, view_type, py_field_modifiers)
except ValueError as error:
if (
"country_id != %(base." in error.args[0]
or "%(base.lu)d not in account_enabled_tax_country_ids" in error.args[0]
):
# Odoo xml file can use %(...)s ref/xmlid, this part is
# replaced later by the record id. This code cannot be
# parsed into a domain and convert into a expression.
# Just skip it.
return
xml = etree.tostring(item, encoding="unicode")
_logger.error(
"Invalid modifiers syntax: %s\nError: %s\n%s", ref, error, xml
)
return
# apply new modifiers on item only when modified...
for attr in ("column_invisible", "invisible", "readonly", "required"):
new_py_expr = modifiers.pop(attr, None)
old_expr = item.attrib.get(attr)
if (
old_expr == new_py_expr
or (old_expr in ("1", "True") and new_py_expr == "True")
or (old_expr in ("0", "False") and new_py_expr in ("False", None))
):
continue
if new_py_expr and (
new_py_expr != "False"
or (attr == "readonly" and field and field.readonly)
or (attr == "required" and field and field.required)
):
item.attrib[attr] = new_py_expr
else:
item.attrib.pop(attr, None)
updated_nodes.add(item)
# ... and remove old attributes
if item.attrib.pop("states", None):
updated_nodes.add(item)
if item.attrib.pop("attrs", None):
updated_nodes.add(item)
# they are some modifiers left, some templates are badly storing
# options in attrs, then they must be left as is (e.g.: studio
# widget, name, ...)
if modifiers:
item.attrib["attrs"] = repr(modifiers)
def in_subview(item):
for p in item.iterancestors():
if p == root:
return False
if p.tag in ("field", "groupby"):
return True
if model is not None:
if view_type == "tree":
# groupby from tree target the field as a subview (inside groupby is treated as form)
for item in root.findall(".//groupby[@name]"):
f_name = item.get("name")
field = model._fields[f_name]
updated, fnodes = convert_node_modifiers_inplace(
item, env, env[field.comodel_name], "form", ref
)
analysed_nodes.update(fnodes)
updated_nodes.update(updated)
for item in root.findall(".//field[@name]"):
if in_subview(item):
continue
if item in analysed_nodes:
continue
# in kanban view, field outside the template should not have modifiers
if view_type == "kanban" and item.getparent().tag == "kanban":
for attr in (
"states",
"attrs",
"column_invisible",
"invisible",
"readonly",
"required",
):
item.attrib.pop(attr, None)
continue
# shortcut for views that do not use information from the python field
if view_type not in ("kanban", "tree", "form", "setting"):
expr_to_attr(item)
continue
f_name = item.get("name")
if f_name not in model._fields:
_logger.warning(
"Unknown field %r from %r, can not migrate 'states' python field attribute in view %s",
f_name,
model._name,
ref,
)
continue
field = model._fields[f_name]
# get subviews
if field.comodel_name:
for subview in item.getchildren():
subview_type = subview.tag if subview.tag != "groupby" else "form"
updated, fnodes = convert_node_modifiers_inplace(
subview, env, env[field.comodel_name], subview_type, ref
)
analysed_nodes.update(fnodes)
updated_nodes.update(updated)
# use python field to convert view <field>
if item.get("readonly"):
expr_to_attr(item, field=field)
elif field.states:
readonly = bool(field.readonly)
fnames = [k for k, v in field.states.items() if v[0][1] != readonly]
if fnames:
fnames.sort()
dom = [("state", "not in" if readonly else "in", fnames)]
expr_to_attr(
item,
py_field_modifiers={"readonly": domain_to_expression(dom)},
field=field,
)
else:
expr_to_attr(item)
elif field.readonly not in (True, False):
try:
readonly_expr = domain_to_expression(str(field.readonly))
except ValueError:
_logger.warning("Can not convert readonly: %r", field.readonly)
continue
if readonly_expr in ("0", "1"):
readonly_expr = str(readonly_expr == "1")
expr_to_attr(
item, py_field_modifiers={"readonly": readonly_expr}, field=field
)
else:
expr_to_attr(item, field=field)
# processes all elements that have not been converted
for item in unique(
itertools.chain(
root.findall(".//*[@attrs]"),
root.findall(".//*[@states]"),
root.findall(".//tree/*[@invisible]"),
)
):
expr_to_attr(item)
return updated_nodes, analysed_nodes
reg_comment = r"<!--(?:-(?!-)|\n|[^-])+-->"
reg_att1 = r'[a-zA-Z0-9._-]+\s*=\s*"(?:\n|[^"])*"'
reg_att2 = r"[a-zA-Z0-9._-]+\s*=\s*'(?:\n|[^'])*'"
reg_open_tag = rf"""<[a-zA-Z0-9]+(?:\s*\n|\s+{reg_att1}|\s+{reg_att2})*\s*/?>"""
reg_close_tag = r"</[a-zA-Z0-9]+\s*>"
reg_split = (
rf"((?:\n|[^<])*)({reg_comment}|{reg_open_tag}|{reg_close_tag})((?:\n|[^<])*)"
)
reg_attrs = r""" (attrs|states|invisible|column_invisible|readonly|required)=("(?:\n|[^"])*"|'(?:\n|[^'])*')"""
close_placeholder = "</XXXYXXX>"
def split_xml(arch):
"""split xml in tags, add a close tag for each void."""
split = list(re.findall(reg_split, arch.replace("/>", f"/>{close_placeholder}")))
return split
def get_targeted_xml_content(spec, field_arch_content):
spec_xml = etree.tostring(spec, encoding="unicode").strip()
if spec_xml in field_arch_content:
return spec_xml
for ancestor in spec.iterancestors():
if ancestor.tag in ("field", "data"):
break
spec_index = ancestor.index(spec)
xml = ""
level = 0
index = 0
for before, tag, after in split_xml(field_arch_content):
if index - 1 == spec_index:
xml += before + tag + after
if tag[1] == "/":
level -= 1
elif tag[1] != "!":
level += 1
if level == 1:
index += 1
if not xml:
ValueError("Source inheritance spec not found for %s: %s", ref, spec_xml)
return xml.replace(close_placeholder, "").strip()
def replace_and_keep_indent(element, arch, ref):
"""Generate micro-diff from updated attributes"""
next_record = (
etree.tostring(element, encoding="unicode").replace(""", "'").strip()
)
n_split = split_xml(next_record)
arch = arch.strip()
p_split = split_xml(arch)
control = ""
level = 0
for i in range(max(len(p_split), len(n_split))):
p_node = p_split[i][1]
n_node = n_split[i][1]
control += "".join(p_split[i])
if p_node[1] != "/" and p_node[1] != "!":
level += 1
replace_by = p_node
if p_node != n_node:
if p_node == close_placeholder and not n_node.startswith("</"):
raise ValueError(
"Wrong split for convertion in %s\n\n---------\nSource node: None\nCurrent node: %s\nSource arch: %s\nCurrent arch: %s"
% (ref, n_node, arch, next_record)
)
if n_node == close_placeholder and not p_node.startswith("</"):
raise ValueError(
"Wrong split for convertion in %s\n\n---------\nSource node: %s\nCurrent node: None\nSource arch: %s\nCurrent arch: %s"
% (ref, p_node, arch, next_record)
)
p_tag = re.split(r"[<>\n /]+", p_node, 2)[1]
n_tag = re.split(r"[<>\n /]+", n_node, 2)[1]
if (
p_node != close_placeholder
and n_node != close_placeholder
and p_tag != n_tag
):
raise ValueError(
"Wrong split for convertion in %s\n\n---------\nSource node: %s\nCurrent node: %s\nSource arch: %s\nCurrent arch: %s"
% (ref, p_node, n_node, arch, next_record)
)
p_attrs = {k: v[1:-1] for k, v in re.findall(reg_attrs, p_node)}
n_attrs = {k: v[1:-1] for k, v in re.findall(reg_attrs, n_node)}
if p_attrs != n_attrs:
if p_attrs:
key, value = p_attrs.popitem()
for j in p_attrs:
replace_by = replace_by.replace(f' {j}="{p_attrs[j]}"', "")
rep = ""
if n_attrs:
space = re.search(rf"(\n? +){key}=", replace_by).group(1)
rep = " " + space.join(f'{k}="{v}"' for k, v in n_attrs.items())
replace_by = re.sub(
r""" %s=["']%s["']""" % (re.escape(key), re.escape(value)),
rep,
replace_by,
)
replace_by = re.sub("(?: *\n +)+(\n +)", r"\1", replace_by)
replace_by = re.sub("(?: *\n +)(/?>)", r"\1", replace_by)
else:
rep = ""
if n_attrs:
rep = " " + " ".join(f'{k}="{v}"' for k, v in n_attrs.items())
if p_node.endswith("/>"):
replace_by = replace_by[0:-2] + rep + "/>"
else:
replace_by = replace_by[0:-1] + rep + ">"
if p_node[1] == "/":
level -= 1
p_split[i] = (p_split[i][0], replace_by, p_split[i][2])
xml = "".join("".join(s) for s in p_split).replace(f"/>{close_placeholder}", "/>")
control = control.replace(f"/>{close_placeholder}", "/>")
if not control or level != 0:
_logger.error("Wrong convertion in %s\n\n%s", ref, control)
raise ValueError("Missing update: \n{control}")
return xml
def extract_node_modifiers(node, view_type, py_field_modifiers=None):
"""extract the node modifiers and concat attributes (attrs, states...)"""
modifiers = {}
# modifiers from deprecated attrs
# <field attrs="{'invisible': "[['user_id', '=', uid]]", 'readonly': [('name', '=', 'toto')]}" .../>
# =>
# modfiers['invisible'] = 'user_id == uid'
# modfiers['readonly'] = 'name == "toto"'
attrs = ast.literal_eval(node.attrib.get("attrs", "{}")) or {}
for modifier, val in attrs.items():
try:
domain = modifier_to_domain(val)
py_expression = domain_to_expression(domain)
except Exception as error:
raise ValueError(
f"Invalid modifier {modifier!r}: {val!r}\n{error}"
) from error
modifiers[modifier] = py_expression
# invisible modifier from deprecated states
# <field states="draft,done" .../>
# =>
# modifiers['invisible'] = "state not in ('draft', 'done')"
states = node.attrib.get("states")
if states:
value = tuple(states.split(","))
if len(value) == 1:
py_expression = f"state != {value[0]!r}"
else:
py_expression = f"state not in {value!r}"
invisible = modifiers.get("invisible") or "False"
if invisible == "False":
modifiers["invisible"] = py_expression
else:
# only add parenthesis if necessary
if " and " in py_expression or " or " in py_expression:
py_expression = f"({py_expression})"
if " and " in invisible or " or " in invisible:
invisible = f"({invisible})"
modifiers["invisible"] = f"{invisible} and {py_expression}"
# extract remaining modifiers
# <field invisible="context.get('hide')" .../>
for modifier in ("column_invisible", "invisible", "readonly", "required"):
py_expression = node.attrib.get(modifier, "").strip()
if not py_expression:
if (
modifier not in modifiers
and py_field_modifiers
and py_field_modifiers.get(modifier)
):
modifiers[modifier] = py_field_modifiers[modifier]
continue
try:
# most (~95%) elements are 1/True/0/False
py_expression = repr(str2bool(py_expression))
except ValueError:
# otherwise, make sure it is a valid expression
try:
modifier_ast = ast.parse(f"({py_expression})", mode="eval").body
py_expression = repr(_modifier_to_domain_ast_leaf(modifier_ast))
except Exception as error:
raise ValueError(
f"Invalid modifier {modifier!r}: {error}: {py_expression!r}"
) from None
# Special case, must rename "invisible" to "column_invisible"
if (
modifier == "invisible"
and py_expression != "False"
and not get_expression_field_names(py_expression)
):
parent_view_type = view_type
for parent in node.iterancestors():
if parent.tag in (
"tree",
"form",
"setting",
"kanban",
"calendar",
"search",
):
parent_view_type = parent.tag
break
if parent.tag in (
"groupby",
"header",
): # tree view element with form view behavior
parent_view_type = "form"
break
if parent_view_type == "tree":
modifier = "column_invisible"
# previous_py_expr and py_expression must be OR-ed
# first 3 cases are short circuits
previous_py_expr = modifiers.get(modifier, "False")
if (
previous_py_expr == "True" or py_expression == "True" # True or ... => True
): # ... or True => True
modifiers[modifier] = "True"
elif previous_py_expr == "False": # False or ... => ...
modifiers[modifier] = py_expression
elif py_expression == "False": # ... or False => ...
modifiers[modifier] = previous_py_expr
else:
# only add parenthesis if necessary
if " and " in previous_py_expr or " or " in previous_py_expr:
previous_py_expr = f"({previous_py_expr})"
modifiers[modifier] = f"{py_expression} or {previous_py_expr}"
return modifiers
def domain_to_expression(domain):
"""Convert the given domain into a python expression"""
domain = normalize_domain(domain)
domain = distribute_not(domain)
operators = []
expression = []
for leaf in reversed(domain):
if leaf == AND_OPERATOR:
right = expression.pop()
if operators.pop() == OR_OPERATOR:
right = f"({right})"
left = expression.pop()
if operators.pop() == OR_OPERATOR:
left = f"({left})"
expression.append(f"{right} and {left}")
operators.append(leaf)
elif leaf == OR_OPERATOR: