def run(self): '''Run the ComplexityVisitor over the AST tree.''' if self.max_cc < 0: if not self.no_assert: return self.max_cc = 10 visitor = ComplexityVisitor.from_ast(self.tree, no_assert=self.no_assert) for block in visitor.blocks: if block.complexity > self.max_cc: text = self._error_tmpl % (block.name, block.complexity) yield block.lineno, block.col_offset, text, type(self)
def mi_parameters(code, count_multi=True): '''Given a source code snippet, compute the necessary parameters to compute the Maintainability Index metric. These include: * the Halstead Volume * the Cyclomatic Complexity * the number of LLOC (Logical Lines of Code) * the percent of lines of comment :param multi: If True, then count multiline strings as comment lines as well. This is not always safe because Python multiline strings are not always docstrings. ''' ast_node = ast.parse(code) raw = analyze(code) comments_lines = raw.comments + (raw.multi if count_multi else 0) comments = comments_lines / float(raw.sloc) * 100 if raw.sloc != 0 else 0 return (h_visit_ast(ast_node).volume, ComplexityVisitor.from_ast(ast_node).total_complexity, raw.lloc, comments)
def analyze_complexity(code, code_metrics, is_multi): ast = visitors.code2ast(code) # Cyclomatic complexity complexity_visitor = ComplexityVisitor.from_ast(ast) res = get_wavg_complexity(complexity_visitor.blocks) # Maintainability index and rank if code_metrics['sloc'] != 0: comments_lines = (code_metrics['comments'] + (code_metrics['multi'] if is_multi else 0)) comments = utils.divide_or_zero(comments_lines, code_metrics['sloc']) * 100 else: comments = 0 res['mi'] = metrics.mi_compute(calculate_halstead_volume(ast), complexity_visitor.total_complexity, code_metrics['lloc'], comments) return res
def cc_visit_ast(ast_node, **kwargs): '''Visit the AST node with :class:`~radon.visitors.ComplexityVisitor`. All the keyword arguments are directly passed to the visitor. ''' return ComplexityVisitor.from_ast(ast_node, **kwargs).blocks
def mi_parameters_without_comments(code): ast_node = ast.parse(code) raw = analyze(code) return (h_visit_ast(ast_node).total.volume, ComplexityVisitor.from_ast(ast_node).total_complexity, raw.lloc)
def cc_visit_ast(ast_node): '''Visit the AST node with :class:`~radon.visitors.ComplexityVisitor` and pass the resulting blocks to :func:`~radon.complexity.sorted_results`. ''' return sorted_results(ComplexityVisitor.from_ast(ast_node).blocks)