desc
stringlengths 3
26.7k
| decl
stringlengths 11
7.89k
| bodies
stringlengths 8
553k
|
---|---|---|
'set option on the correct option provider'
| def global_set_option(self, opt, value):
| self._all_options[opt].set_option(opt, value)
|
'write a configuration file according to the current configuration
into the given stream or stdout'
| def generate_config(self, stream=None, skipsections=(), encoding=None):
| options_by_section = {}
sections = []
for provider in self.options_providers:
for (section, options) in provider.options_by_section():
if (section is None):
section = provider.name
if (section in skipsections):
continue
options = [(n, d, v) for (n, d, v) in options if ((d.get('type') is not None) and (not d.get('deprecated')))]
if (not options):
continue
if (section not in sections):
sections.append(section)
alloptions = options_by_section.setdefault(section, [])
alloptions += options
stream = (stream or sys.stdout)
encoding = utils._get_encoding(encoding, stream)
printed = False
for section in sections:
if printed:
print('\n', file=stream)
utils.format_section(stream, section.upper(), sorted(options_by_section[section]), encoding)
printed = True
|
'initialize configuration using default values'
| def load_provider_defaults(self):
| for provider in self.options_providers:
provider.load_defaults()
|
'read the configuration file but do not load it (i.e. dispatching
values to each options provider)'
| def read_config_file(self, config_file=None):
| helplevel = 1
while (helplevel <= self._maxlevel):
opt = ('-'.join((['long'] * helplevel)) + '-help')
if (opt in self._all_options):
break
def helpfunc(option, opt, val, p, level=helplevel):
print(self.help(level))
sys.exit(0)
helpmsg = ('%s verbose help.' % ' '.join((['more'] * helplevel)))
optdict = {'action': 'callback', 'callback': helpfunc, 'help': helpmsg}
provider = self.options_providers[0]
self.add_optik_option(provider, self.cmdline_parser, opt, optdict)
provider.options += ((opt, optdict),)
helplevel += 1
if (config_file is None):
config_file = self.config_file
if (config_file is not None):
config_file = os.path.expanduser(config_file)
if (config_file and os.path.exists(config_file)):
parser = self.cfgfile_parser
with io.open(config_file, 'r', encoding='utf_8_sig') as fp:
parser.readfp(fp)
for (sect, values) in list(parser._sections.items()):
if ((not sect.isupper()) and values):
parser._sections[sect.upper()] = values
elif (not self.quiet):
msg = 'No config file found, using default configuration'
print(msg, file=sys.stderr)
return
|
'dispatch values previously read from a configuration file to each
options provider)'
| def load_config_file(self):
| parser = self.cfgfile_parser
for section in parser.sections():
for (option, value) in parser.items(section):
try:
self.global_set_option(option, value)
except (KeyError, optparse.OptionError):
continue
|
'override configuration according to given parameters'
| def load_configuration(self, **kwargs):
| return self.load_configuration_from_config(kwargs)
|
'Override configuration according to command line parameters
return additional arguments'
| def load_command_line_configuration(self, args=None):
| with _patch_optparse():
if (args is None):
args = sys.argv[1:]
else:
args = list(args)
(options, args) = self.cmdline_parser.parse_args(args=args)
for provider in self._nocallback_options:
config = provider.config
for attr in config.__dict__.keys():
value = getattr(options, attr, None)
if (value is None):
continue
setattr(config, attr, value)
return args
|
'add a dummy option section for help purpose'
| def add_help_section(self, title, description, level=0):
| group = optparse.OptionGroup(self.cmdline_parser, title=title.capitalize(), description=description)
group.level = level
self._maxlevel = max(self._maxlevel, level)
self.cmdline_parser.add_option_group(group)
|
'return the usage string for available options'
| def help(self, level=0):
| self.cmdline_parser.formatter.output_level = level
with _patch_optparse():
return self.cmdline_parser.format_help()
|
'initialize the provider using default values'
| def load_defaults(self):
| for (opt, optdict) in self.options:
action = optdict.get('action')
if (action != 'callback'):
if (optdict is None):
optdict = self.get_option_def(opt)
default = optdict.get('default')
self.set_option(opt, default, action, optdict)
|
'get the config attribute corresponding to opt'
| def option_attrname(self, opt, optdict=None):
| if (optdict is None):
optdict = self.get_option_def(opt)
return optdict.get('dest', opt.replace('-', '_'))
|
'get the current value for the given option'
| def option_value(self, opt):
| return getattr(self.config, self.option_attrname(opt), None)
|
'method called to set an option (registered in the options list)'
| def set_option(self, optname, value, action=None, optdict=None):
| if (optdict is None):
optdict = self.get_option_def(optname)
if (value is not None):
value = _validate(value, optdict, optname)
if (action is None):
action = optdict.get('action', 'store')
if (action == 'store'):
setattr(self.config, self.option_attrname(optname, optdict), value)
elif (action in ('store_true', 'count')):
setattr(self.config, self.option_attrname(optname, optdict), 0)
elif (action == 'store_false'):
setattr(self.config, self.option_attrname(optname, optdict), 1)
elif (action == 'append'):
optname = self.option_attrname(optname, optdict)
_list = getattr(self.config, optname, None)
if (_list is None):
if isinstance(value, (list, tuple)):
_list = value
elif (value is not None):
_list = []
_list.append(value)
setattr(self.config, optname, _list)
elif isinstance(_list, tuple):
setattr(self.config, optname, (_list + (value,)))
else:
_list.append(value)
elif (action == 'callback'):
optdict['callback'](None, optname, value, None)
else:
raise UnsupportedAction(action)
|
'return the dictionary defining an option given its name'
| def get_option_def(self, opt):
| assert self.options
for option in self.options:
if (option[0] == opt):
return option[1]
raise optparse.OptionError(('no such option %s in section %r' % (opt, self.name)), opt)
|
'return an iterator on options grouped by section
(section, [list of (optname, optdict, optvalue)])'
| def options_by_section(self):
| sections = {}
for (optname, optdict) in self.options:
sections.setdefault(optdict.get('group'), []).append((optname, optdict, self.option_value(optname)))
if (None in sections):
(yield (None, sections.pop(None)))
for (section, options) in sorted(sections.items()):
(yield (section.upper(), options))
|
'Format the message according to the given template.
The template format is the one of the format method :
cf. http://docs.python.org/2/library/string.html#formatstrings'
| def format(self, template):
| return template.format(**dict(zip(self._fields, self)))
|
'return True if message may be emitted using the current interpreter'
| def may_be_emitted(self):
| if ((self.minversion is not None) and (self.minversion > sys.version_info)):
return False
if ((self.maxversion is not None) and (self.maxversion <= sys.version_info)):
return False
return True
|
'return the help string for the given message id'
| def format_help(self, checkerref=False):
| desc = self.descr
if checkerref:
desc += (' This message belongs to the %s checker.' % self.checker.name)
title = self.msg
if self.symbol:
msgid = ('%s (%s)' % (self.symbol, self.msgid))
else:
msgid = self.msgid
if (self.minversion or self.maxversion):
restr = []
if self.minversion:
restr.append(('< %s' % '.'.join([str(n) for n in self.minversion])))
if self.maxversion:
restr.append(('>= %s' % '.'.join([str(n) for n in self.maxversion])))
restr = ' or '.join(restr)
if checkerref:
desc += (" It can't be emitted when using Python %s." % restr)
else:
desc += (" This message can't be emitted when using Python %s." % restr)
desc = _normalize_text(' '.join(desc.split()), indent=' ')
if (title != '%s'):
title = title.splitlines()[0]
return (':%s: *%s*\n%s' % (msgid, title, desc))
return (':%s:\n%s' % (msgid, desc))
|
'don\'t output message of the given id'
| def disable(self, msgid, scope='package', line=None, ignore_unknown=False):
| self._set_msg_status(msgid, enable=False, scope=scope, line=line, ignore_unknown=ignore_unknown)
|
'reenable message of the given id'
| def enable(self, msgid, scope='package', line=None, ignore_unknown=False):
| self._set_msg_status(msgid, enable=True, scope=scope, line=line, ignore_unknown=ignore_unknown)
|
'Get the message symbol of the given message id
Return the original message id if the message does not
exist.'
| def _message_symbol(self, msgid):
| try:
return self.msgs_store.check_message_id(msgid).symbol
except UnknownMessageError:
return msgid
|
'Returns the scope at which a message was enabled/disabled.'
| def get_message_state_scope(self, msgid, line=None, confidence=UNDEFINED):
| if (self.config.confidence and (confidence.name not in self.config.confidence)):
return MSG_STATE_CONFIDENCE
try:
if (line in self.file_state._module_msgs_state[msgid]):
return MSG_STATE_SCOPE_MODULE
except (KeyError, TypeError):
return MSG_STATE_SCOPE_CONFIG
|
'return true if the message associated to the given message id is
enabled
msgid may be either a numeric or symbolic message id.'
| def is_message_enabled(self, msg_descr, line=None, confidence=None):
| if (self.config.confidence and confidence):
if (confidence.name not in self.config.confidence):
return False
try:
msgid = self.msgs_store.check_message_id(msg_descr).msgid
except UnknownMessageError:
msgid = msg_descr
if (line is None):
return self._msgs_state.get(msgid, True)
try:
return self.file_state._module_msgs_state[msgid][line]
except KeyError:
return self._msgs_state.get(msgid, True)
|
'Adds a message given by ID or name.
If provided, the message string is expanded using args
AST checkers should must the node argument (but may optionally
provide line if the line number is different), raw and token checkers
must provide the line argument.'
| def add_message(self, msg_descr, line=None, node=None, args=None, confidence=UNDEFINED):
| msg_info = self.msgs_store.check_message_id(msg_descr)
msgid = msg_info.msgid
symbol = (msg_info.symbol or msgid)
if (msgid[0] not in _SCOPE_EXEMPT):
if (msg_info.scope == WarningScope.LINE):
if (line is None):
raise InvalidMessageError(('Message %s must provide line, got None' % msgid))
if (node is not None):
raise InvalidMessageError(('Message %s must only provide line, got line=%s, node=%s' % (msgid, line, node)))
elif (msg_info.scope == WarningScope.NODE):
if (node is None):
raise InvalidMessageError(('Message %s must provide Node, got None' % msgid))
if ((line is None) and (node is not None)):
line = node.fromlineno
if hasattr(node, 'col_offset'):
col_offset = node.col_offset
else:
col_offset = None
if (not self.is_message_enabled(msgid, line, confidence)):
self.file_state.handle_ignored_message(self.get_message_state_scope(msgid, line, confidence), msgid, line, node, args, confidence)
return
msg_cat = MSG_TYPES[msgid[0]]
self.msg_status |= MSG_TYPES_STATUS[msgid[0]]
self.stats[msg_cat] += 1
self.stats['by_module'][self.current_name][msg_cat] += 1
try:
self.stats['by_msg'][symbol] += 1
except KeyError:
self.stats['by_msg'][symbol] = 1
msg = msg_info.msg
if args:
msg %= args
if (node is None):
(module, obj) = (self.current_name, '')
abspath = self.current_file
else:
(module, obj) = get_module_and_frameid(node)
abspath = node.root().file
path = abspath.replace(self.reporter.path_strip_prefix, '')
self.reporter.handle_message(Message(msgid, symbol, (abspath, path, module, obj, (line or 1), (col_offset or 0)), msg, confidence))
|
'output a full documentation in ReST format'
| def print_full_documentation(self, stream=None):
| if (not stream):
stream = sys.stdout
print('Pylint global options and switches', file=stream)
print('----------------------------------', file=stream)
print('', file=stream)
print('Pylint provides global options and switches.', file=stream)
print('', file=stream)
by_checker = {}
for checker in self.get_checkers():
if (checker.name == 'master'):
if checker.options:
for (section, options) in checker.options_by_section():
if (section is None):
title = 'General options'
else:
title = ('%s options' % section.capitalize())
print(title, file=stream)
print(('~' * len(title)), file=stream)
_rest_format_section(stream, None, options)
print('', file=stream)
else:
name = checker.name
try:
by_checker[name]['options'] += checker.options_and_values()
by_checker[name]['msgs'].update(checker.msgs)
by_checker[name]['reports'] += checker.reports
except KeyError:
by_checker[name] = {'options': list(checker.options_and_values()), 'msgs': dict(checker.msgs), 'reports': list(checker.reports)}
print("Pylint checkers' options and switches", file=stream)
print('-------------------------------------', file=stream)
print('', file=stream)
print('Pylint checkers can provide three set of features:', file=stream)
print('', file=stream)
print('* options that control their execution,', file=stream)
print('* messages that they can raise,', file=stream)
print('* reports that they can generate.', file=stream)
print('', file=stream)
print('Below is a list of all checkers and their features.', file=stream)
print('', file=stream)
for (checker, info) in six.iteritems(by_checker):
self._print_checker_doc(checker, info, stream=stream)
|
'Helper method for print_full_documentation.
Also used by doc/exts/pylint_extensions.py.'
| @staticmethod
def _print_checker_doc(checker_name, info, stream=None):
| if (not stream):
stream = sys.stdout
doc = info.get('doc')
module = info.get('module')
msgs = info.get('msgs')
options = info.get('options')
reports = info.get('reports')
title = ('%s checker' % checker_name.replace('_', ' ').title())
if module:
print(('.. _%s:\n' % module), file=stream)
print(title, file=stream)
print(('~' * len(title)), file=stream)
print('', file=stream)
if module:
print(('This checker is provided by ``%s``.' % module), file=stream)
print(('Verbatim name of the checker is ``%s``.' % checker_name), file=stream)
print('', file=stream)
if doc:
title = 'Documentation'
print(title, file=stream)
print(('^' * len(title)), file=stream)
print(cleandoc(doc), file=stream)
print('', file=stream)
if options:
title = 'Options'
print(title, file=stream)
print(('^' * len(title)), file=stream)
_rest_format_section(stream, None, options)
print('', file=stream)
if msgs:
title = 'Messages'
print(title, file=stream)
print(('^' * len(title)), file=stream)
for (msgid, msg) in sorted(six.iteritems(msgs), key=(lambda kv: (_MSG_ORDER.index(kv[0][0]), kv[1]))):
msg = build_message_def(checker_name, msgid, msg)
print(msg.format_help(checkerref=False), file=stream)
print('', file=stream)
if reports:
title = 'Reports'
print(title, file=stream)
print(('^' * len(title)), file=stream)
for report in reports:
print((':%s: %s' % report[:2]), file=stream)
print('', file=stream)
print('', file=stream)
|
'Walk the AST to collect block level options line numbers.'
| def collect_block_lines(self, msgs_store, module_node):
| for (msg, lines) in six.iteritems(self._module_msgs_state):
self._raw_module_msgs_state[msg] = lines.copy()
orig_state = self._module_msgs_state.copy()
self._module_msgs_state = {}
self._suppression_mapping = {}
self._collect_block_lines(msgs_store, module_node, orig_state)
|
'Recursively walk (depth first) AST to collect block level options
line numbers.'
| def _collect_block_lines(self, msgs_store, node, msg_state):
| for child in node.get_children():
self._collect_block_lines(msgs_store, child, msg_state)
first = node.fromlineno
last = node.tolineno
if (isinstance(node, (nodes.Module, nodes.ClassDef, nodes.FunctionDef)) and node.body):
firstchildlineno = node.body[0].fromlineno
else:
firstchildlineno = last
for (msgid, lines) in six.iteritems(msg_state):
for (lineno, state) in list(lines.items()):
original_lineno = lineno
if ((first > lineno) or (last < lineno)):
continue
if (msgs_store.check_message_id(msgid).scope == WarningScope.NODE):
if (lineno > firstchildlineno):
state = True
(first_, last_) = node.block_range(lineno)
else:
first_ = lineno
last_ = last
for line in range(first_, (last_ + 1)):
if (line in self._module_msgs_state.get(msgid, ())):
continue
if (line in lines):
state = lines[line]
original_lineno = line
if (not state):
self._suppression_mapping[(msgid, line)] = original_lineno
try:
self._module_msgs_state[msgid][line] = state
except KeyError:
self._module_msgs_state[msgid] = {line: state}
del lines[lineno]
|
'Set status (enabled/disable) for a given message at a given line'
| def set_msg_status(self, msg, line, status):
| assert (line > 0)
try:
self._module_msgs_state[msg.msgid][line] = status
except KeyError:
self._module_msgs_state[msg.msgid] = {line: status}
|
'Report an ignored message.
state_scope is either MSG_STATE_SCOPE_MODULE or MSG_STATE_SCOPE_CONFIG,
depending on whether the message was disabled locally in the module,
or globally. The other arguments are the same as for add_message.'
| def handle_ignored_message(self, state_scope, msgid, line, node, args, confidence):
| if (state_scope == MSG_STATE_SCOPE_MODULE):
try:
orig_line = self._suppression_mapping[(msgid, line)]
self._ignored_msgs[(msgid, orig_line)].add(line)
except KeyError:
pass
|
'The list of all active messages.'
| @property
def messages(self):
| return six.itervalues(self._messages)
|
'Register the old ID and symbol for a warning that was renamed.
This allows users to keep using the old ID/symbol in suppressions.'
| def add_renamed_message(self, old_id, old_symbol, new_symbol):
| msg = self.check_message_id(new_symbol)
msg.old_names.append((old_id, old_symbol))
self._register_alternative_name(msg, old_id)
self._register_alternative_name(msg, old_symbol)
|
'register a dictionary of messages
Keys are message ids, values are a 2-uple with the message type and the
message itself
message ids should be a string of len 4, where the two first characters
are the checker id and the two last the message id in this checker'
| def register_messages(self, checker):
| chkid = None
for (msgid, msg_tuple) in sorted(six.iteritems(checker.msgs)):
msg = build_message_def(checker, msgid, msg_tuple)
if ((msg.symbol in self._messages) or (msg.symbol in self._alternative_names)):
raise InvalidMessageError(('Message symbol %r is already defined' % msg.symbol))
if ((chkid is not None) and (chkid != msg.msgid[1:3])):
raise InvalidMessageError(("Inconsistent checker part in message id %r (expected 'x%sxx')" % (msgid, chkid)))
chkid = msg.msgid[1:3]
self._messages[msg.symbol] = msg
self._register_alternative_name(msg, msg.msgid)
for (old_id, old_symbol) in msg.old_names:
self._register_alternative_name(msg, old_id)
self._register_alternative_name(msg, old_symbol)
self._msgs_by_category[msg.msgid[0]].append(msg.msgid)
|
'helper for register_message()'
| def _register_alternative_name(self, msg, name):
| if ((name in self._messages) and (self._messages[name] != msg)):
raise InvalidMessageError(('Message symbol %r is already defined' % name))
if ((name in self._alternative_names) and (self._alternative_names[name] != msg)):
raise InvalidMessageError(('Message %s %r is already defined' % (('id' if ((len(name) == 5) and (name[0] in MSG_TYPES)) else 'alternate name'), name)))
self._alternative_names[name] = msg
|
'returns the Message object for this message.
msgid may be either a numeric or symbolic id.
Raises UnknownMessageError if the message id is not defined.'
| def check_message_id(self, msgid):
| if msgid[1:].isdigit():
msgid = msgid.upper()
for source in (self._alternative_names, self._messages):
try:
return source[msgid]
except KeyError:
pass
raise UnknownMessageError(('No such message id %s' % msgid))
|
'Generates a user-consumable representation of a message.
Can be just the message ID or the ID and the symbol.'
| def get_msg_display_string(self, msgid):
| return repr(self.check_message_id(msgid).symbol)
|
'display help messages for the given message identifiers'
| def help_message(self, msgids):
| for msgid in msgids:
try:
print(self.check_message_id(msgid).format_help(checkerref=True))
print('')
except UnknownMessageError as ex:
print(ex)
print('')
continue
|
'output full messages list documentation in ReST format'
| def list_messages(self):
| msgs = sorted(six.itervalues(self._messages), key=(lambda msg: msg.msgid))
for msg in msgs:
if (not msg.may_be_emitted()):
continue
print(msg.format_help(checkerref=False))
print('')
|
'Return a list of reports, sorted in the order
in which they must be called.'
| def report_order(self):
| return list(self._reports)
|
'register a report
reportid is the unique identifier for the report
r_title the report\'s title
r_cb the method to call to make the report
checker is the checker defining the report'
| def register_report(self, reportid, r_title, r_cb, checker):
| reportid = reportid.upper()
self._reports[checker].append((reportid, r_title, r_cb))
|
'disable the report of the given id'
| def enable_report(self, reportid):
| reportid = reportid.upper()
self._reports_state[reportid] = True
|
'disable the report of the given id'
| def disable_report(self, reportid):
| reportid = reportid.upper()
self._reports_state[reportid] = False
|
'return true if the report associated to the given identifier is
enabled'
| def report_is_enabled(self, reportid):
| return self._reports_state.get(reportid, True)
|
'render registered reports'
| def make_reports(self, stats, old_stats):
| sect = Section('Report', ('%s statements analysed.' % self.stats['statement']))
for checker in self.report_order():
for (reportid, r_title, r_cb) in self._reports[checker]:
if (not self.report_is_enabled(reportid)):
continue
report_sect = Section(r_title)
try:
r_cb(report_sect, stats, old_stats)
except EmptyReportError:
continue
report_sect.report_id = reportid
sect.append(report_sect)
return sect
|
'add some stats entries to the statistic dictionary
raise an AssertionError if there is a key conflict'
| def add_stats(self, **kwargs):
| for (key, value) in six.iteritems(kwargs):
if (key[(-1)] == '_'):
key = key[:(-1)]
assert (key not in self.stats)
self.stats[key] = value
return self.stats
|
'walk to the checker\'s dir and collect visit and leave methods'
| def add_checker(self, checker):
| vcids = set()
lcids = set()
visits = self.visit_events
leaves = self.leave_events
for member in dir(checker):
cid = member[6:]
if (cid == 'default'):
continue
if member.startswith('visit_'):
v_meth = getattr(checker, member)
if self._is_method_enabled(v_meth):
visits[cid].append(v_meth)
vcids.add(cid)
elif member.startswith('leave_'):
l_meth = getattr(checker, member)
if self._is_method_enabled(l_meth):
leaves[cid].append(l_meth)
lcids.add(cid)
visit_default = getattr(checker, 'visit_default', None)
if visit_default:
for cls in nodes.ALL_NODE_CLASSES:
cid = cls.__name__.lower()
if (cid not in vcids):
visits[cid].append(visit_default)
|
'call visit events of astroid checkers for the given node, recurse on
its children, then leave events.'
| def walk(self, astroid):
| cid = astroid.__class__.__name__.lower()
visit_events = ()
leave_events = ()
visit_events = self.visit_events.get(cid, ())
leave_events = self.leave_events.get(cid, ())
if astroid.is_statement:
self.nbstatements += 1
for cb in (visit_events or ()):
cb(astroid)
for child in astroid.get_children():
self.walk(child)
for cb in (leave_events or ()):
cb(astroid)
|
'init filter modes'
| def __init__(self, mode):
| __mode = 0
for nummod in mode.split('+'):
try:
__mode += MODES[nummod]
except KeyError as ex:
print(('Unknown filter mode %s' % ex), file=sys.stderr)
self.__mode = __mode
|
'return true if the node should be treated'
| def show_attr(self, node):
| visibility = get_visibility(getattr(node, 'name', node))
return (not (self.__mode & VIS_MOD[visibility]))
|
'walk on the tree from <node>, getting callbacks from handler'
| def walk(self, node, _done=None):
| if (_done is None):
_done = set()
if (node in _done):
raise AssertionError((id(node), node, node.parent))
_done.add(node)
self.visit(node)
for child_node in node.get_children():
assert (child_node is not node)
self.walk(child_node, _done)
self.leave(node)
assert (node.parent is not node)
|
'get callbacks from handler for the visited node'
| def get_callbacks(self, node):
| klass = node.__class__
methods = self._cache.get(klass)
if (methods is None):
handler = self.handler
kid = klass.__name__.lower()
e_method = getattr(handler, ('visit_%s' % kid), getattr(handler, 'visit_default', None))
l_method = getattr(handler, ('leave_%s' % kid), getattr(handler, 'leave_default', None))
self._cache[klass] = (e_method, l_method)
else:
(e_method, l_method) = methods
return (e_method, l_method)
|
'walk on the tree from <node>, getting callbacks from handler'
| def visit(self, node):
| method = self.get_callbacks(node)[0]
if (method is not None):
method(node)
|
'walk on the tree from <node>, getting callbacks from handler'
| def leave(self, node):
| method = self.get_callbacks(node)[1]
if (method is not None):
method(node)
|
'launch the visit starting from the given node'
| def visit(self, node):
| if (node in self._visited):
return
self._visited[node] = 1
methods = self.get_callbacks(node)
if (methods[0] is not None):
methods[0](node)
if hasattr(node, 'locals'):
for local_node in node.values():
self.visit(local_node)
if (methods[1] is not None):
return methods[1](node)
|
'common Diagram Handler initialization'
| def __init__(self, linker, handler):
| self.config = handler.config
self._set_default_options()
self.linker = linker
self.classdiagram = None
|
'get title for objects'
| def get_title(self, node):
| title = node.name
if self.module_names:
title = ('%s.%s' % (node.root().name, title))
return title
|
'activate some options if not explicitly deactivated'
| def _set_option(self, option):
| if (option is None):
return bool(self.config.classes)
return option
|
'set different default options with _default dictionary'
| def _set_default_options(self):
| self.module_names = self._set_option(self.config.module_names)
all_ancestors = self._set_option(self.config.all_ancestors)
all_associated = self._set_option(self.config.all_associated)
(anc_level, ass_level) = (0, 0)
if all_ancestors:
anc_level = (-1)
if all_associated:
ass_level = (-1)
if (self.config.show_ancestors is not None):
anc_level = self.config.show_ancestors
if (self.config.show_associated is not None):
ass_level = self.config.show_associated
(self.anc_level, self.ass_level) = (anc_level, ass_level)
|
'help function for search levels'
| def _get_levels(self):
| return (self.anc_level, self.ass_level)
|
'true if builtins and not show_builtins'
| def show_node(self, node):
| if self.config.show_builtin:
return True
return (node.root().name != BUILTINS_NAME)
|
'visit one class and add it to diagram'
| def add_class(self, node):
| self.linker.visit(node)
self.classdiagram.add_object(self.get_title(node), node)
|
'return ancestor nodes of a class node'
| def get_ancestors(self, node, level):
| if (level == 0):
return
for ancestor in node.ancestors(recurs=False):
if (not self.show_node(ancestor)):
continue
(yield ancestor)
|
'return associated nodes of a class node'
| def get_associated(self, klass_node, level):
| if (level == 0):
return
for ass_nodes in (list(klass_node.instance_attrs_type.values()) + list(klass_node.locals_type.values())):
for ass_node in ass_nodes:
if isinstance(ass_node, astroid.Instance):
ass_node = ass_node._proxied
if (not (isinstance(ass_node, astroid.ClassDef) and self.show_node(ass_node))):
continue
(yield ass_node)
|
'extract recursively classes related to klass_node'
| def extract_classes(self, klass_node, anc_level, ass_level):
| if (self.classdiagram.has_node(klass_node) or (not self.show_node(klass_node))):
return
self.add_class(klass_node)
for ancestor in self.get_ancestors(klass_node, anc_level):
self.extract_classes(ancestor, (anc_level - 1), ass_level)
for ass_node in self.get_associated(klass_node, ass_level):
self.extract_classes(ass_node, anc_level, (ass_level - 1))
|
'visit an pyreverse.utils.Project node
create a diagram definition for packages'
| def visit_project(self, node):
| mode = self.config.mode
if (len(node.modules) > 1):
self.pkgdiagram = PackageDiagram(('packages %s' % node.name), mode)
else:
self.pkgdiagram = None
self.classdiagram = ClassDiagram(('classes %s' % node.name), mode)
|
'leave the pyreverse.utils.Project node
return the generated diagram definition'
| def leave_project(self, node):
| if self.pkgdiagram:
return (self.pkgdiagram, self.classdiagram)
return (self.classdiagram,)
|
'visit an astroid.Module node
add this class to the package diagram definition'
| def visit_module(self, node):
| if self.pkgdiagram:
self.linker.visit(node)
self.pkgdiagram.add_object(node.name, node)
|
'visit an astroid.Class node
add this class to the class diagram definition'
| def visit_classdef(self, node):
| (anc_level, ass_level) = self._get_levels()
self.extract_classes(node, anc_level, ass_level)
|
'visit astroid.From and catch modules for package diagram'
| def visit_importfrom(self, node):
| if self.pkgdiagram:
self.pkgdiagram.add_from_depend(node, node.modname)
|
'return a class diagram definition for the given klass and its
related klasses'
| def class_diagram(self, project, klass):
| self.classdiagram = ClassDiagram(klass, self.config.mode)
if (len(project.modules) > 1):
(module, klass) = klass.rsplit('.', 1)
module = project.get_module(module)
else:
module = project.modules[0]
klass = klass.split('.')[(-1)]
klass = next(module.ilookup(klass))
(anc_level, ass_level) = self._get_levels()
self.extract_classes(klass, anc_level, ass_level)
return self.classdiagram
|
'Get the diagrams configuration data
:param project:The pyreverse project
:type project: pyreverse.utils.Project
:param linker: The linker
:type linker: pyreverse.inspector.Linker(IdGeneratorMixIn, LocalsVisitor)
:returns: The list of diagram definitions
:rtype: list(:class:`pylint.pyreverse.diagrams.ClassDiagram`)'
| def get_diadefs(self, project, linker):
| diagrams = []
generator = ClassDiadefGenerator(linker, self)
for klass in self.config.classes:
diagrams.append(generator.class_diagram(project, klass))
if (not diagrams):
diagrams = DefaultDiadefGenerator(linker, self).visit(project)
for diagram in diagrams:
diagram.extract_relationships()
return diagrams
|
'checking arguments and run project'
| def run(self, args):
| if (not args):
print(self.help())
return 1
sys.path.insert(0, os.getcwd())
try:
project = project_from_files(args, project_name=self.config.project, black_list=self.config.black_list)
linker = Linker(project, tag=True)
handler = DiadefsHandler(self.config)
diadefs = handler.get_diadefs(project, linker)
finally:
sys.path.pop(0)
if (self.config.output_format == 'vcg'):
writer.VCGWriter(self.config).write(diadefs)
else:
writer.DotWriter(self.config).write(diadefs)
return 0
|
'init the id counter'
| def init_counter(self, start_value=0):
| self.id_count = start_value
|
'generate a new identifier'
| def generate_id(self):
| self.id_count += 1
return self.id_count
|
'visit an pyreverse.utils.Project node
* optionally tag the node with a unique id'
| def visit_project(self, node):
| if self.tag:
node.uid = self.generate_id()
for module in node.modules:
self.visit(module)
|
'visit an astroid.Package node
* optionally tag the node with a unique id'
| def visit_package(self, node):
| if self.tag:
node.uid = self.generate_id()
for subelmt in node.values():
self.visit(subelmt)
|
'visit an astroid.Module node
* set the locals_type mapping
* set the depends mapping
* optionally tag the node with a unique id'
| def visit_module(self, node):
| if hasattr(node, 'locals_type'):
return
node.locals_type = collections.defaultdict(list)
node.depends = []
if self.tag:
node.uid = self.generate_id()
|
'visit an astroid.Class node
* set the locals_type and instance_attrs_type mappings
* set the implements list and build it
* optionally tag the node with a unique id'
| def visit_classdef(self, node):
| if hasattr(node, 'locals_type'):
return
node.locals_type = collections.defaultdict(list)
if self.tag:
node.uid = self.generate_id()
for baseobj in node.ancestors(recurs=False):
specializations = getattr(baseobj, 'specializations', [])
specializations.append(node)
baseobj.specializations = specializations
node.instance_attrs_type = collections.defaultdict(list)
for assattrs in node.instance_attrs.values():
for assattr in assattrs:
self.handle_assattr_type(assattr, node)
try:
node.implements = list(interfaces(node, self.inherited_interfaces))
except astroid.InferenceError:
node.implements = ()
|
'visit an astroid.Function node
* set the locals_type mapping
* optionally tag the node with a unique id'
| def visit_functiondef(self, node):
| if hasattr(node, 'locals_type'):
return
node.locals_type = collections.defaultdict(list)
if self.tag:
node.uid = self.generate_id()
|
'visit an astroid.AssName node
handle locals_type'
| def visit_assignname(self, node):
| if hasattr(node, '_handled'):
return
node._handled = True
if (node.name in node.frame()):
frame = node.frame()
else:
frame = node.root()
try:
if (not hasattr(frame, 'locals_type')):
if isinstance(frame, astroid.ClassDef):
self.visit_classdef(frame)
elif isinstance(frame, astroid.FunctionDef):
self.visit_functiondef(frame)
else:
self.visit_module(frame)
current = frame.locals_type[node.name]
values = set(node.infer())
frame.locals_type[node.name] = list((set(current) | values))
except astroid.InferenceError:
pass
|
'handle an astroid.AssAttr node
handle instance_attrs_type'
| @staticmethod
def handle_assattr_type(node, parent):
| try:
values = set(node.infer())
current = set(parent.instance_attrs_type[node.attrname])
parent.instance_attrs_type[node.attrname] = list((current | values))
except astroid.InferenceError:
pass
|
'visit an astroid.Import node
resolve module dependencies'
| def visit_import(self, node):
| context_file = node.root().file
for name in node.names:
relative = modutils.is_relative(name[0], context_file)
self._imported_module(node, name[0], relative)
|
'visit an astroid.From node
resolve module dependencies'
| def visit_importfrom(self, node):
| basename = node.modname
context_file = node.root().file
if (context_file is not None):
relative = modutils.is_relative(basename, context_file)
else:
relative = False
for name in node.names:
if (name[0] == '*'):
continue
fullname = ('%s.%s' % (basename, name[0]))
if (fullname.find('.') > (-1)):
try:
fullname = modutils.get_module_part(fullname, context_file)
except ImportError:
continue
if (fullname != basename):
self._imported_module(node, fullname, relative)
|
'return true if the module should be added to dependencies'
| def compute_module(self, context_name, mod_path):
| package_dir = os.path.dirname(self.project.path)
if (context_name == mod_path):
return 0
elif modutils.is_standard_module(mod_path, (package_dir,)):
return 1
return 0
|
'Notify an imported module, used to analyze dependencies'
| def _imported_module(self, node, mod_path, relative):
| module = node.root()
context_name = module.name
if relative:
mod_path = ('%s.%s' % ('.'.join(context_name.split('.')[:(-1)]), mod_path))
if self.compute_module(context_name, mod_path):
if (not hasattr(module, 'depends')):
module.depends = []
mod_paths = module.depends
if (mod_path not in mod_paths):
mod_paths.append(mod_path)
|
'open a vcg graph'
| def open_graph(self, **args):
| self._stream.write(('%sgraph:{\n' % self._indent))
self._inc_indent()
self._write_attributes(GRAPH_ATTRS, **args)
|
'close a vcg graph'
| def close_graph(self):
| self._dec_indent()
self._stream.write(('%s}\n' % self._indent))
|
'draw a node'
| def node(self, title, **args):
| self._stream.write(('%snode: {title:"%s"' % (self._indent, title)))
self._write_attributes(NODE_ATTRS, **args)
self._stream.write('}\n')
|
'draw an edge from a node to another.'
| def edge(self, from_node, to_node, edge_type='', **args):
| self._stream.write(('%s%sedge: {sourcename:"%s" targetname:"%s"' % (self._indent, edge_type, from_node, to_node)))
self._write_attributes(EDGE_ATTRS, **args)
self._stream.write('}\n')
|
'write graph, node or edge attributes'
| def _write_attributes(self, attributes_dict, **args):
| for (key, value) in args.items():
try:
_type = attributes_dict[key]
except KeyError:
raise Exception(('no such attribute %s\npossible attributes are %s' % (key, attributes_dict.keys())))
if (not _type):
self._stream.write(('%s%s:"%s"\n' % (self._indent, key, value)))
elif (_type == 1):
self._stream.write(('%s%s:%s\n' % (self._indent, key, int(value))))
elif (value in _type):
self._stream.write(('%s%s:%s\n' % (self._indent, key, value)))
else:
raise Exception(("value %s isn't correct for attribute %s\ncorrect values are %s" % (value, key, _type)))
|
'increment indentation'
| def _inc_indent(self):
| self._indent = (' %s' % self._indent)
|
'decrement indentation'
| def _dec_indent(self):
| self._indent = self._indent[:(-2)]
|
'write files for <project> according to <diadefs>'
| def write(self, diadefs):
| for diagram in diadefs:
basename = diagram.title.strip().replace(' ', '_')
file_name = ('%s.%s' % (basename, self.config.output_format))
self.set_printer(file_name, basename)
if (diagram.TYPE == 'class'):
self.write_classes(diagram)
else:
self.write_packages(diagram)
self.close_graph()
|
'write a package diagram'
| def write_packages(self, diagram):
| for (i, obj) in enumerate(sorted(diagram.modules(), key=(lambda x: x.title))):
self.printer.emit_node(i, label=self.get_title(obj), shape='box')
obj.fig_id = i
for rel in diagram.get_relationships('depends'):
self.printer.emit_edge(rel.from_object.fig_id, rel.to_object.fig_id, **self.pkg_edges)
|
'write a class diagram'
| def write_classes(self, diagram):
| for (i, obj) in enumerate(sorted(diagram.objects, key=(lambda x: x.title))):
self.printer.emit_node(i, **self.get_values(obj))
obj.fig_id = i
for rel in diagram.get_relationships('specialization'):
self.printer.emit_edge(rel.from_object.fig_id, rel.to_object.fig_id, **self.inh_edges)
for rel in diagram.get_relationships('implements'):
self.printer.emit_edge(rel.from_object.fig_id, rel.to_object.fig_id, **self.imp_edges)
for rel in diagram.get_relationships('association'):
self.printer.emit_edge(rel.from_object.fig_id, rel.to_object.fig_id, label=rel.name, **self.ass_edges)
|
'set printer'
| def set_printer(self, file_name, basename):
| raise NotImplementedError
|
'get project title'
| def get_title(self, obj):
| raise NotImplementedError
|
'get label and shape for classes.'
| def get_values(self, obj):
| raise NotImplementedError
|
'finalize the graph'
| def close_graph(self):
| raise NotImplementedError
|
'initialize DotWriter and add options for layout.'
| def set_printer(self, file_name, basename):
| layout = dict(rankdir='BT')
self.printer = DotBackend(basename, additional_param=layout)
self.file_name = file_name
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.