/
misc.py
470 lines (425 loc) · 18.5 KB
/
misc.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
import ast
import csv
import os
import re
import subprocess
import inspect
from distutils.version import LooseVersion
from lxml import etree
from pylint.checkers import BaseChecker, BaseTokenChecker
from pylint.interfaces import UNDEFINED
from pylint.interfaces import IAstroidChecker, ITokenChecker
from pylint.utils import _basename_in_blacklist_re
from restructuredtext_lint import lint_file as rst_lint
from six import string_types
from . import settings
try:
from shutil import which # python3.x
except ImportError:
from whichcraft import which
DFTL_VALID_ODOO_VERSIONS = [
'4.2', '5.0', '6.0', '6.1', '7.0', '8.0', '9.0', '10.0', '11.0', '12.0',
]
DFTL_MANIFEST_VERSION_FORMAT = r"({valid_odoo_versions})\.\d+\.\d+\.\d+$"
def get_plugin_msgs(pylint_run_res):
"""Get all message of this pylint plugin.
:param pylint_run_res: Object returned by pylint.run method.
:return: List of strings with message name.
"""
all_plugin_msgs = [
key
for key in pylint_run_res.linter.msgs_store._messages
if pylint_run_res.linter.msgs_store._messages[key].checker.name ==
settings.CFG_SECTION
]
return all_plugin_msgs
def join_node_args_kwargs(node):
"""Method to join args and keywords
:param node: node to get args and keywords
:return: List of args
"""
args = (getattr(node, 'args', None) or []) + \
(getattr(node, 'keywords', None) or [])
return args
class PylintOdooChecker(BaseChecker):
# Auto call to `process_tokens` method
__implements__ = IAstroidChecker
odoo_node = None
odoo_module_name = None
manifest_file = None
manifest_dict = None
def formatversion(self, string):
valid_odoo_versions = self.linter._all_options[
'valid_odoo_versions'].config.valid_odoo_versions
valid_odoo_versions = '|'.join(
map(re.escape, DFTL_VALID_ODOO_VERSIONS))
self.config.manifest_version_format_parsed = (
DFTL_MANIFEST_VERSION_FORMAT.format(
valid_odoo_versions=valid_odoo_versions))
return re.match(self.config.manifest_version_format_parsed, string)
def get_manifest_file(self, node_file):
"""Get manifest file path
:param node_file: String with full path of a python module file.
:return: Full path of manifest file if exists else return None"""
if os.path.basename(node_file) == '__init__.py':
for manifest_basename in settings.MANIFEST_FILES:
manifest_file = os.path.join(
os.path.dirname(node_file), manifest_basename)
if os.path.isfile(manifest_file):
return manifest_file
def set_ext_files(self):
"""Create `self.ext_files` dictionary with {extension_file: [files]}
and exclude files using --ignore and --ignore-patterns parameters
"""
self.ext_files = {}
for root, _, filenames in os.walk(self.module_path, followlinks=True):
for filename in filenames:
fext = os.path.splitext(filename)[1].lower()
fname = os.path.join(root, filename)
# If the file is within black_list_re is ignored
if _basename_in_blacklist_re(fname,
self.linter.config.black_list_re):
continue
# If the file is within ignores is ignored
find = False
for ignore in self.linter.config.black_list:
if ignore in fname:
find = True
break
if not find:
fname_rel = os.path.relpath(fname, self.module_path)
self.ext_files.setdefault(fext, []).append(fname_rel)
def set_caches(self):
if self.odoo_node:
self.set_ext_files()
def clear_caches(self):
self.ext_files = None
def leave_module(self, node):
"""Clear caches"""
self.clear_caches()
def wrapper_visit_module(self, node):
"""Call methods named with name-key from self.msgs
Method should be named with next standard:
def _check_{NAME_KEY}(self, module_path)
by example: def _check_missing_icon(self, module_path)
to check missing-icon message name key
And should return True if all fine else False.
if a False is returned then add message of name-key.
Assign object variables to use in methods.
:param node: A astroid.scoped_nodes.Module
:return: None
"""
manifest_file = self.get_manifest_file(node.file)
if manifest_file:
self.manifest_file = manifest_file
self.odoo_node = node
self.odoo_module_name = os.path.basename(
os.path.dirname(self.odoo_node.file))
with open(self.manifest_file) as f_manifest:
self.manifest_dict = ast.literal_eval(f_manifest.read())
elif self.odoo_node and not os.path.dirname(self.odoo_node.file) in \
os.path.dirname(node.file):
# It's not a sub-module python of a odoo module and
# it's not a odoo module
self.odoo_node = None
self.odoo_module_name = None
self.manifest_dict = None
self.manifest_file = None
self.is_main_odoo_module = False
if self.odoo_node and self.odoo_node.file == node.file:
self.is_main_odoo_module = True
self.node = node
self.module_path = os.path.dirname(node.file)
self.module = os.path.basename(self.module_path)
self.set_caches()
for msg_code, (title, name_key, description) in \
sorted(self.msgs.items()):
self.msg_code = msg_code
self.msg_name_key = name_key
self.msg_args = None
if not self.linter.is_message_enabled(msg_code):
continue
check_method = getattr(
self, '_check_' + name_key.replace('-', '_'),
None)
is_odoo_check = self.is_main_odoo_module and \
msg_code[1:3] == str(settings.BASE_OMODULE_ID)
is_py_check = msg_code[1:3] == str(settings.BASE_PYMODULE_ID)
if callable(check_method) and (is_odoo_check or is_py_check):
if not check_method():
if not isinstance(self.msg_args, list):
self.msg_args = [self.msg_args]
for msg_args in self.msg_args:
node_file_original = node.file
node_lineno_original = node.lineno
msg_args_extra = self.set_extra_file(node, msg_args,
msg_code)
self.add_message(name_key, line=node.lineno, node=node,
args=msg_args_extra)
node.file = node_file_original
node.lineno = node_lineno_original
def visit_module(self, node):
self.wrapper_visit_module(node)
def add_message(self, msg_id, line=None, node=None, args=None,
confidence=UNDEFINED):
version = (self.manifest_dict.get('version')
if isinstance(self.manifest_dict, dict) else '')
match = self.formatversion(version)
short_version = match.group(1) if match else ''
if not short_version:
valid_odoo_versions = self.linter._all_options[
'valid_odoo_versions'].config.valid_odoo_versions
short_version = (valid_odoo_versions[0] if
len(valid_odoo_versions) == 1 else '')
if not self._is_version_supported(short_version, msg_id):
return
return super(PylintOdooChecker, self).add_message(
msg_id, line, node, args, confidence)
def _is_version_supported(self, version, name_check):
if not version or not hasattr(self, 'odoo_check_versions'):
return True
odoo_check_versions = self.odoo_check_versions.get(name_check, {})
if not odoo_check_versions:
return True
version = LooseVersion(version)
min_odoo_version = LooseVersion(odoo_check_versions.get(
'min_odoo_version', DFTL_VALID_ODOO_VERSIONS[0]))
max_odoo_version = LooseVersion(odoo_check_versions.get(
'max_odoo_version', DFTL_VALID_ODOO_VERSIONS[-1]))
return (min_odoo_version <= version <= max_odoo_version)
class PylintOdooTokenChecker(BaseTokenChecker, PylintOdooChecker):
# Auto call to `process_tokens` method
__implements__ = (ITokenChecker, IAstroidChecker)
# TODO: Change all methods here
class WrapperModuleChecker(PylintOdooChecker):
node = None
module_path = None
msg_args = None
msg_code = None
msg_name_key = None
module = None
is_main_odoo_module = None
def open(self):
self.odoo_node = None
def set_extra_file(self, node, msg_args, msg_code):
if isinstance(msg_args, string_types):
msg_args = (msg_args,)
first_arg = msg_args and msg_args[0] or ""
fregex_str = \
r"(?P<file>^[\w|\-|\.|/ \\]+):?(?P<lineno>\d+)?:?(?P<colno>\d+)?"
fregex = re.compile(fregex_str)
fmatch = fregex.match(first_arg)
msg = self.linter.msgs_store.check_message_id(msg_code).msg.\
strip('"\' ')
if not fmatch or not msg.startswith(r"%s"):
return msg_args
module_path = os.path.dirname(self.odoo_node.file)
fname = fmatch.group('file')
fpath = os.path.join(module_path, fname)
node.file = fpath if os.path.isfile(fpath) else module_path
node.lineno = int(fmatch.group('lineno') or 0)
msg_strip = re.sub(fregex_str, '', first_arg, 1).strip(': ')
return (msg_strip,) + msg_args[1:]
def filter_files_ext(self, fext, relpath=True, skip_examples=True):
"""Filter files of odoo modules with a file extension.
:param fext: Extension name of files to filter.
:param relpath: Boolean to choose absolute path or relative path
If relpath is True then return relative paths
else return absolute paths
:param skip_examples: Boolean to skip "examples" folder
:return: List of paths of files matched
with extension fext.
"""
dirnames_to_skip = []
if skip_examples:
dirnames_to_skip.extend([
'example', 'examples', 'sample', 'samples', 'lib', 'libs',
'doc', 'docs', 'template', 'templates',
])
if not fext.startswith('.'):
fext = '.' + fext
fext = fext.lower()
fnames = self._skip_files_ext(fext, self.ext_files.get(fext, []))
for fname in list(fnames):
dirnames = os.path.dirname(fname).split(os.sep)
for dirname_to_skip in dirnames_to_skip:
if dirname_to_skip in dirnames:
fnames.remove(fname)
break
if not relpath:
# Unused section is not delete it for compatibility
fnames = [ # pragma: no cover
os.path.join(self.module_path, fname)
for fname in fnames]
return fnames
def _skip_files_ext(self, fext, fnames):
"""Detected inside the resource the skip message
Eg: '<!-- pylint-odoo:disable=deprecated-data-xml-node -->'
inside the xml resource"""
if fext != '.xml':
return fnames
info_called = [item[3] for item in inspect.stack() if
'modules_odoo' in item[1] and
item[3].startswith('_check_')]
method_called = (info_called[0].replace(
'_check_', '').replace('_', '-') if info_called else False)
if method_called:
for fname in list(fnames):
full_name = os.path.join(self.module_path, fname)
if not os.path.isfile(full_name):
continue
class PylintCommentTarget(object):
def __init__(self):
self.comments = []
def comment(self, text):
match = re.search(
r'(pylint:disable=|pylint: disable=|'
'pylint : disable=)', text)
if match:
text = match.re.split(text)[-1].replace(
'_', '-').strip()
self.comments.extend([item.strip() for item in
text.split(',')])
def close(self):
return self.comments
parser = etree.XMLParser(target=PylintCommentTarget())
try:
with open(full_name, 'rb') as xml_file:
skips = etree.parse(xml_file, parser)
except etree.XMLSyntaxError:
skips = []
pass
if method_called in skips and fname in fnames:
fnames.remove(fname)
return fnames
def check_rst_syntax(self, fname):
"""Check syntax in rst files.
:param fname: String with file name path to check
:return: Return list of errors.
"""
return rst_lint(fname)
def npm_which_module(self, module):
module_bin = which(module)
npm_bin = which('npm')
if not module_bin and npm_bin:
npm_bin_paths = []
for cmd in ([npm_bin, 'bin'], [npm_bin, 'bin', '-g']):
process = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, err = process.communicate()
output = output.decode('UTF-8')
err = err.decode('UTF-8')
npm_bin_path = output.strip('\n ')
if os.path.isdir(npm_bin_path) and not err:
npm_bin_paths.append(npm_bin_path)
if npm_bin_paths:
module_bin = which(module, path=os.pathsep.join(npm_bin_paths))
return module_bin
def check_js_lint(self, fname, frc=None):
"""Check javascript lint in fname.
:param fname: String with full path of file to check
:param frc: String with full path of configuration file for
the javascript-lint tool
:return: Return list of errors.
"""
lint_bin = self.npm_which_module('eslint')
if not lint_bin:
return []
cmd = [lint_bin, '--format=unix', fname]
if frc:
cmd.append('--config=' + frc)
process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
output, err = process.communicate()
output = output.decode('UTF-8')
err = err.decode('UTF-8')
if process.returncode != 0 and err:
return []
# Strip multi-line output https://github.com/eslint/eslint/issues/6810
for old in re.findall(r"`(.*)` instead.", output, re.DOTALL):
new = old.split('\n')[0][:20] + '...'
output = output.replace(old, new)
output = output.replace(fname, '')
output_spplited = []
if output:
output_spplited.extend(
output.strip('\n').split('\n')[:-2])
return output_spplited
def get_duplicated_items(self, items):
"""Get duplicated items
:param items: Iterable items
:return: List with tiems duplicated
"""
unique_items = set()
duplicated_items = set()
for item in items:
if item in unique_items:
duplicated_items.add(item)
else:
unique_items.add(item)
return list(duplicated_items)
def parse_xml(self, xml_file):
"""Get xml parsed.
:param xml_file: Path of file xml
:return: Doc parsed (lxml.etree object)
if there is syntax error return string error message
"""
if not os.path.isfile(xml_file):
return etree.Element("__empty__")
try:
with open(xml_file, "rb") as f:
doc = etree.parse(f)
except etree.XMLSyntaxError as xmlsyntax_error_exception:
return str(xmlsyntax_error_exception)
return doc
def get_xml_records(self, xml_file, model=None, more=None):
"""Get tag `record` of a openerp xml file.
:param xml_file: Path of file xml
:param model: String with record model to filter.
if model is None then get all.
Default None.
:return: List of lxml `record` nodes
If there is syntax error return []
"""
xml_file = self._skip_files_ext('.xml', [xml_file])
if not xml_file:
return []
xml_file = xml_file[0]
if model is None:
model_filter = ''
else:
model_filter = "[@model='{model}']".format(model=model)
if more is None:
more_filter = ''
else:
more_filter = more
doc = self.parse_xml(xml_file)
return doc.xpath("/openerp//record" + model_filter + more_filter) + \
doc.xpath("/odoo//record" + model_filter + more_filter) \
if not isinstance(doc, string_types) else []
def get_field_csv(self, csv_file, field='id'):
"""Get xml ids from csv file
:param csv_file: Path of file csv
:param field: Field to search
:return: List of string with field rows
"""
with open(csv_file, 'r') as csvfile:
lines = csv.DictReader(csvfile)
return [line[field] for line in lines if field in line]
def get_xml_redundant_module_name(self, xml_file, module=None):
"""Get xml redundant name module in xml_id of a openerp xml file
:param xml_file: Path of file xml
:param module: String with record model to filter.
If model is None then return a empty list.
Default None.
:return: List of tuples with (string, integer) with
(module.xml_id, lineno) found
"""
xml_ids = []
for record in self.get_xml_records(xml_file):
ref = record.get('id', '')
xml_module, xml_id = ref.split('.') if '.' in ref else ['', ref]
if module and xml_module == module:
xml_ids.append((xml_id, record.sourceline))
return xml_ids