|
1 | 1 | # SPDX-FileCopyrightText: Copyright (c) 2019-2025 Aibolit |
2 | 2 | # SPDX-License-Identifier: MIT |
3 | 3 |
|
4 | | -import os |
5 | | -import shutil |
6 | | -import subprocess |
7 | | -import tempfile |
8 | | -import uuid |
| 4 | +from aibolit.ast_framework import AST, ASTNode, ASTNodeType |
9 | 5 |
|
10 | | -from bs4 import BeautifulSoup |
11 | 6 |
|
| 7 | +class CCMetric: |
| 8 | + """ |
| 9 | + Calculates cyclomatic complexity by counting |
| 10 | + decision points in all methods and constructors: |
12 | 11 |
|
13 | | -class CCMetric(): |
14 | | - """Main Cyclical Complexity class.""" |
| 12 | + - Base complexity: 1 per method/constructor |
| 13 | + - Decision points: if, while, for, do-while, |
| 14 | + switch cases, catch, throw, |
| 15 | + ternary, break, continue |
| 16 | + - Boolean operators (&&, ||) add additional complexity paths |
| 17 | + """ |
15 | 18 |
|
16 | | - input = '' |
| 19 | + def value(self, ast: AST) -> int: |
| 20 | + return sum( |
| 21 | + self._method_complexity(ast, node) |
| 22 | + for node in ast.get_proxy_nodes( |
| 23 | + ASTNodeType.METHOD_DECLARATION, ASTNodeType.CONSTRUCTOR_DECLARATION |
| 24 | + ) |
| 25 | + ) |
17 | 26 |
|
18 | | - def __init__(self, input): |
19 | | - self.input = input |
| 27 | + def _method_complexity(self, ast: AST, method: ASTNode) -> int: |
| 28 | + method_ast = ast.get_subtree(method) |
| 29 | + return 1 + sum(self._node_complexity(ast, node) for node in method_ast.get_proxy_nodes()) |
20 | 30 |
|
21 | | - def value(self, showoutput=False): |
22 | | - """Run Cyclical Complexity analaysis""" |
| 31 | + def _node_complexity(self, ast: AST, node: ASTNode) -> int: |
| 32 | + if node.node_type in _SIMPLE_NODES: |
| 33 | + return 1 |
| 34 | + elif node.node_type in _CONDITION_NODES: |
| 35 | + return self._condition_complexity(ast, node) |
| 36 | + elif node.node_type == ASTNodeType.FOR_STATEMENT: |
| 37 | + return self._for_statement_complexity(ast, node) |
| 38 | + return 0 |
23 | 39 |
|
24 | | - if len(self.input) == 0: |
25 | | - raise ValueError('Empty file for analysis') |
26 | | - try: |
27 | | - root = os.path.join(tempfile.gettempdir(), uuid.uuid4().hex) |
28 | | - dirName = os.path.join(root, 'src/main/java') |
29 | | - os.makedirs(dirName) |
30 | | - if os.path.isdir(self.input): |
31 | | - shutil.copytree(self.input, os.path.join(dirName, self.input)) |
32 | | - elif os.path.isfile(self.input): |
33 | | - pos1 = self.input.rfind('/') |
34 | | - os.makedirs(dirName + '/' + self.input[0:pos1]) |
35 | | - shutil.copyfile(self.input, os.path.join(dirName, self.input)) |
36 | | - else: |
37 | | - raise Exception('File ' + self.input + ' does not exist') |
38 | | - tmppath = os.path.dirname(os.path.realpath(__file__)) |
39 | | - shutil.copyfile(os.path.join(tmppath, 'pom.xml'), root + '/pom.xml') |
40 | | - shutil.copyfile(os.path.join(tmppath, 'cyclical.xml'), root + '/cyclical.xml') |
41 | | - if showoutput: |
42 | | - subprocess.run(['mvn', 'pmd:pmd'], cwd=root, check=False) |
43 | | - else: |
44 | | - subprocess.run(['mvn', 'pmd:pmd'], cwd=root, |
45 | | - stdout=subprocess.DEVNULL, |
46 | | - stderr=subprocess.DEVNULL, check=False) |
47 | | - if os.path.isfile(root + '/target/pmd.xml'): |
48 | | - res = self.__parseFile(root) |
49 | | - return res |
50 | | - raise Exception('File ' + self.input + ' analyze failed') |
51 | | - finally: |
52 | | - shutil.rmtree(root) |
| 40 | + def _condition_complexity(self, ast: AST, node: ASTNode) -> int: |
| 41 | + return 1 + self._expression_complexity(ast, node.condition) |
53 | 42 |
|
54 | | - def __parseFile(self, root): |
55 | | - result = {'data': [], 'errors': []} |
56 | | - content = [] |
57 | | - with open(root + '/target/pmd.xml', 'r', encoding='utf-8') as file: |
58 | | - content = file.read() |
59 | | - soup = BeautifulSoup(content, 'lxml') |
60 | | - files = soup.find_all('file') |
61 | | - for file in files: |
62 | | - out = file.violation.string |
63 | | - name = file['name'] |
64 | | - pos1 = name.find(root + '/src/main/java/') |
65 | | - pos1 = pos1 + len(root + '/src/main/java/') |
66 | | - name = name[pos1:] |
67 | | - pos1 = out.find('has a total cyclomatic complexity') |
68 | | - pos1 = out.find('of ', pos1) |
69 | | - pos1 = pos1 + 3 |
70 | | - pos2 = out.find('(', pos1) |
71 | | - complexity = int(out[pos1:pos2 - 1]) |
72 | | - result['data'].append({'file': name, 'complexity': complexity}) |
73 | | - errors = soup.find_all('error') |
74 | | - for error in errors: |
75 | | - name = error['filename'] |
76 | | - pos1 = name.find(root + '/src/main/java/') |
77 | | - pos1 = pos1 + len(root + '/src/main/java/') |
78 | | - name = name[pos1:] |
79 | | - raise Exception(error['msg']) |
80 | | - return result |
| 43 | + def _for_statement_complexity(self, ast: AST, node: ASTNode) -> int: |
| 44 | + if hasattr(node.control, 'condition'): |
| 45 | + return self._condition_complexity(ast, node.control) |
| 46 | + return 1 |
| 47 | + |
| 48 | + def _expression_complexity(self, ast: AST, expression: ASTNode | None) -> int: |
| 49 | + if expression is None: |
| 50 | + return 0 |
| 51 | + expression_ast = ast.get_subtree(expression) |
| 52 | + return sum( |
| 53 | + 1 |
| 54 | + for node in expression_ast.get_proxy_nodes(ASTNodeType.BINARY_OPERATION) |
| 55 | + if node.operator in ('&&', '||') |
| 56 | + ) |
| 57 | + |
| 58 | + |
| 59 | +_SIMPLE_NODES = ( |
| 60 | + ASTNodeType.BREAK_STATEMENT, |
| 61 | + ASTNodeType.CATCH_CLAUSE, |
| 62 | + ASTNodeType.CONTINUE_STATEMENT, |
| 63 | + ASTNodeType.SWITCH_STATEMENT_CASE, |
| 64 | + ASTNodeType.THROW_STATEMENT, |
| 65 | +) |
| 66 | + |
| 67 | +_CONDITION_NODES = ( |
| 68 | + ASTNodeType.IF_STATEMENT, |
| 69 | + ASTNodeType.WHILE_STATEMENT, |
| 70 | + ASTNodeType.DO_STATEMENT, |
| 71 | + ASTNodeType.TERNARY_EXPRESSION, |
| 72 | +) |
0 commit comments