I'm trying to set up a CI/CD process that logs a warning when the code has too many nested if statements. I attempted to start with just two nested ifs to see if it registers correctly. Here's the setup I used:
```yaml
- id: python-too-many-nested-ifs
languages: [python]
severity: WARNING
message: |
Excessive nesting of if statements.
patterns:
- pattern-inside: |
if $A:
...
- pattern-inside: |
if $B:
...
- pattern: |
if $C:
...
```
Unfortunately, it seems to trigger even for a single if statement. Is there a way to accurately detect excessive nesting with Semgrep?
3 Answers
It's worth considering that enforcing strict rules about nested ifs might lead to more complicated single if statements, potentially making your code harder to read. Sometimes simpler code is better than overly strict rules.
Many static analysis tools offer configurable complexity warnings, which can help with detecting nesting issues. You might want to explore those options alongside Semgrep.
Though I'm not an expert on Semgrep, the term you're looking for is "cyclomatic complexity." It's a way to measure how complex your logic is based on the nested conditions. That might guide how you set your patterns.

Totally agree! Cyclomatic complexity is crucial to keep in check from a testing standpoint. It can get pretty wild with all the conditions, and restructuring with case statements might be a more readable alternative.