-
Notifications
You must be signed in to change notification settings - Fork 4
feat: add complexity analyzer tool #53
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
nnennandukwe
wants to merge
1
commit into
feature/41-core-module
Choose a base branch
from
feature/44-complexity-analysis
base: feature/41-core-module
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| """Complexity analysis tools for measuring Python code complexity metrics.""" | ||
|
|
||
| __version__ = "0.1.0" | ||
|
|
||
| from .calculator import CognitiveCalculator, CyclomaticCalculator | ||
| from .metrics import ClassMetrics, FileMetrics, FunctionMetrics, analyze_complexity | ||
| from .patterns import ComplexityCategory | ||
|
|
||
| __all__ = [ | ||
| "CyclomaticCalculator", | ||
| "CognitiveCalculator", | ||
| "FunctionMetrics", | ||
| "ClassMetrics", | ||
| "FileMetrics", | ||
| "ComplexityCategory", | ||
| "analyze_complexity", | ||
| ] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| """Cyclomatic and cognitive complexity calculators using Astroid.""" | ||
|
|
||
| import astroid | ||
|
|
||
|
|
||
| class CyclomaticCalculator: | ||
| """Calculates cyclomatic complexity for Python functions. | ||
|
|
||
| Cyclomatic complexity counts the number of linearly independent paths | ||
| through a function. Higher values indicate more complex branching logic. | ||
| """ | ||
|
|
||
| def calculate(self, node: astroid.FunctionDef | astroid.AsyncFunctionDef) -> int: | ||
| """Calculate cyclomatic complexity for a function node. | ||
|
|
||
| Args: | ||
| node: An Astroid FunctionDef or AsyncFunctionDef node. | ||
|
|
||
| Returns: | ||
| Cyclomatic complexity score (minimum 1). | ||
| """ | ||
| complexity = 1 # Base complexity | ||
| complexity += self._count_branches(node) | ||
| return complexity | ||
|
|
||
| def _count_branches(self, node: astroid.NodeNG) -> int: | ||
| """Recursively count branching constructs.""" | ||
| count = 0 | ||
| for _child in node.nodes_of_class( | ||
| ( | ||
| astroid.If, | ||
| astroid.For, | ||
| astroid.While, | ||
| astroid.ExceptHandler, | ||
| astroid.With, | ||
| astroid.Assert, | ||
| astroid.IfExp, | ||
| astroid.Comprehension, | ||
| ) | ||
| ): | ||
| count += 1 | ||
|
|
||
| # Count boolean operators in conditions | ||
| for bool_op in node.nodes_of_class(astroid.BoolOp): | ||
| # Each 'and'/'or' adds a new path | ||
| count += len(bool_op.values) - 1 | ||
|
|
||
| return count | ||
|
|
||
|
|
||
| class CognitiveCalculator: | ||
| """Calculates cognitive complexity (Sonar's metric) for Python functions. | ||
|
|
||
| Cognitive complexity measures how difficult code is to understand, | ||
| applying nesting penalties for structures inside other structures. | ||
| """ | ||
|
|
||
| def calculate(self, node: astroid.FunctionDef | astroid.AsyncFunctionDef) -> int: | ||
| """Calculate cognitive complexity for a function node. | ||
|
|
||
| Args: | ||
| node: An Astroid FunctionDef or AsyncFunctionDef node. | ||
|
|
||
| Returns: | ||
| Cognitive complexity score (minimum 0). | ||
| """ | ||
| return self._walk(node, nesting=0, func_name=node.name) | ||
|
|
||
| def _walk(self, node: astroid.NodeNG, nesting: int, func_name: str) -> int: | ||
| """Recursively walk the AST accumulating cognitive complexity.""" | ||
| total = 0 | ||
|
|
||
| for child in node.get_children(): | ||
| if isinstance(child, (astroid.FunctionDef, astroid.AsyncFunctionDef)): | ||
| # Nested function definitions increase nesting | ||
| total += self._walk(child, nesting + 1, func_name) | ||
| continue | ||
|
|
||
| # Increment for breaks in linear flow + nesting penalty | ||
| if isinstance(child, astroid.If): | ||
| total += 1 + nesting # +1 for if + nesting penalty | ||
| total += self._walk(child, nesting + 1, func_name) | ||
| continue | ||
| elif isinstance(child, (astroid.For, astroid.While)): | ||
| total += 1 + nesting | ||
| total += self._walk(child, nesting + 1, func_name) | ||
| continue | ||
| elif isinstance(child, astroid.ExceptHandler): | ||
| total += 1 + nesting | ||
| total += self._walk(child, nesting + 1, func_name) | ||
| continue | ||
| elif isinstance(child, astroid.With): | ||
| total += 1 + nesting | ||
| total += self._walk(child, nesting + 1, func_name) | ||
| continue | ||
| elif isinstance(child, astroid.IfExp): | ||
| total += 1 + nesting | ||
| total += self._walk(child, nesting, func_name) | ||
| continue | ||
|
|
||
| # Boolean operators: +1 for each sequence | ||
| if isinstance(child, astroid.BoolOp): | ||
| total += 1 | ||
|
|
||
| # Recursion: +1 when function calls itself | ||
| if isinstance(child, astroid.Call): | ||
| call_name = self._get_call_name(child) | ||
| if call_name == func_name: | ||
| total += 1 | ||
|
|
||
| total += self._walk(child, nesting, func_name) | ||
|
|
||
| return total | ||
|
|
||
| @staticmethod | ||
| def _get_call_name(node: astroid.Call) -> str | None: | ||
| """Get the simple name of a function call.""" | ||
| if isinstance(node.func, astroid.Name): | ||
| return node.func.name | ||
| return None |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
1. Module not under tools/
📎 Requirement gap✓ CorrectnessAgent Prompt
ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools