Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(health): stop counting a try block as a nesting level (#3648)
Swati Ahujac9d0c7d56c8e
diff --git a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.pyindex ebb2c1c1f..f7adba95f 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/cyclomatic.py@@ -438,8 +438,10 @@ def _walk_function_body())elif node.is_named and node.type in lmap.try_kinds:- # TRY opens a nesting level but does not branch on its own.- nesting_increment = 1+ # TRY neither branches nor nests: each catch opens the level for+ # its own body, and the guarded and finally bodies stay at the+ # try's depth (Sonar's cognitive complexity spec).+ passelif node.is_named and node.type in lmap.switch_kinds:# Detect flat match: all arms are simple single-expression arms.if _is_flat_match(node, lmap):diff --git a/packages/core/src/repowise/core/analysis/health/complexity/languages.py b/packages/core/src/repowise/core/analysis/health/complexity/languages.pyindex 444e34971..49bac5d91 100644--- a/packages/core/src/repowise/core/analysis/health/complexity/languages.py+++ b/packages/core/src/repowise/core/analysis/health/complexity/languages.py@@ -7,7 +7,7 @@ names to the walker's abstract categories:- ``BRANCH`` — adds 1 to CCN, 1 to nesting, 1 + nesting to cognitive.- ``LOOP`` — same as BRANCH.- ``TRY`` — adds 1 to CCN per ``catch``/``except`` clause; the- ``TRY`` block itself only opens a nesting level.+ ``TRY`` block itself adds no CCN and no nesting.- ``CATCH`` — adds 1 to CCN, 1 to nesting; the catch clause.- ``SWITCH`` — case dispatch root; counts each case as a branch.- ``CASE`` — adds 1 to CCN, 1 to nesting per case.@@ -1288,7 +1288,7 @@ _OBJC = LanguageNodeMap(# ``for_in_statement`` node in this grammar.loop_kinds=frozenset({"for_statement", "while_statement", "do_statement"}),try_kinds=frozenset({"try_statement"}),- # TRY only opens a nesting level; CATCH is what adds to CCN.+ # CATCH, not TRY, adds to CCN and nesting.catch_kinds=frozenset({"catch_clause"}),switch_kinds=frozenset({"switch_statement"}),case_kinds=frozenset({"case_statement"}),diff --git a/tests/unit/health/test_complexity_walker.py b/tests/unit/health/test_complexity_walker.pyindex 50f6b0fe0..430013b46 100644--- a/tests/unit/health/test_complexity_walker.py+++ b/tests/unit/health/test_complexity_walker.py@@ -987,3 +987,83 @@ def test_php_assertion_blocks():assert many.assertion_blocks[0][2] == 5few = _find(results, "testFewAsserts")assert few is not None and few.assertion_blocks == []+++def _walk_source(source: str, language: str, filename: str):+ _require_language(language)+ results = walk_file_complexity(filename, language, source.encode())+ if not results:+ pytest.skip(f"tree-sitter language pack missing for {language}")+ return {r.name: r for r in results}+++# A try neither branches nor nests: each catch opens one level for its own+# body, and the guarded and finally bodies stay at the try's depth.+ ("language", "filename", "source", "ccn", "nesting", "cognitive"),+ [+ (+ "python",+ "f.py",+ "def f(a):\n try:\n g()\n except ValueError:\n if a:\n return 2\n return 3\n",+ 3,+ 2,+ 3,+ ),+ (+ "python",+ "f.py",+ "def f(a):\n try:\n if a:\n g()\n finally:\n if a:\n h()\n",+ 3,+ 1,+ 2,+ ),+ (+ "python",+ "f.py",+ "def f():\n try:\n try:\n g()\n except KeyError:\n h()\n except ValueError:\n k()\n",+ 3,+ 1,+ 2,+ ),+ (+ "java",+ "F.java",+ "class F {\n int f(boolean a) {\n try (Reader r = open()) {\n g();\n"+ " } catch (IOException e) {\n if (a) { return 2; }\n }\n return 3;\n }\n}\n",+ 3,+ 2,+ 3,+ ),+ (+ "kotlin",+ "f.kt",+ "fun f(a: Boolean): Int {\n val x = try {\n g()\n } catch (e: Exception) {\n"+ " if (a) 2 else 3\n }\n return x\n}\n",+ 3,+ 2,+ 3,+ ),+ ],+ ids=["try-except-if", "try-finally", "nested-try", "java-try-with-resources", "kotlin-try-expression"],+)+def test_try_does_not_nest(language, filename, source, ccn, nesting, cognitive):+ fn = _walk_source(source, language, filename)["f"]+ assert (fn.ccn, fn.max_nesting, fn.cognitive) == (ccn, nesting, cognitive)+++def test_catch_still_nests_its_body():+ source = (+ "def f(a):\n"+ " try:\n"+ " g()\n"+ " except ValueError:\n"+ " log()\n"+ " log()\n"+ " log()\n"+ " return 3\n"+ )+ fn = _walk_source(source, "python", "f.py")["f"]+ assert fn.max_nesting == 1+ # The nesting locator names the except clause, not the try around it.+ assert fn.deepest_block == (4, 7)diff --git a/tests/unit/health/test_jsx_ternary_nesting.py b/tests/unit/health/test_jsx_ternary_nesting.pyindex 5b0c098bb..533bf5929 100644--- a/tests/unit/health/test_jsx_ternary_nesting.py+++ b/tests/unit/health/test_jsx_ternary_nesting.py@@ -133,10 +133,11 @@ def test_conditional_rendering_inside_markup_is_flat():def test_real_pyramid_inside_a_jsx_handler_still_flagged():fn = _fn(HANDLER_PYRAMID, "Panel")- # for > if > try > if > while: the arrow handler rolls into Panel.- assert fn.max_nesting == 5+ # for > if > if > while (the try adds no level): the arrow handler rolls+ # into Panel.+ assert fn.max_nesting == 4[finding] = BIOMARKER.detect(_ctx(fn))- assert finding.severity.value == "high"+ assert finding.severity.value == "medium"def test_value_ternary_chain_is_flat_in_plain_typescript():diff --git a/tests/unit/health/test_swift_complexity.py b/tests/unit/health/test_swift_complexity.pyindex 994d11a7f..8df5a4195 100644--- a/tests/unit/health/test_swift_complexity.py+++ b/tests/unit/health/test_swift_complexity.py@@ -210,7 +210,7 @@ def test_a_case_where_guard_is_not_counted():# -- errors ------------------------------------------------------------------------def test_do_catch_counts_each_catch_and_do_opens_a_level():+def test_do_catch_counts_each_catch_and_only_the_catch_nests():source = ("func f() -> Int {\n do {\n try g()\n } catch let e as NSError {\n return 1\n"" } catch {\n return 2\n }\n return 0\n}\n"@@ -220,8 +220,8 @@ def test_do_catch_counts_each_catch_and_do_opens_a_level():" } catch (e: Exception) {\n return 2\n }\n return 0\n}\n")- assert _shape(source) == {"f": (3, 2)}- assert _shape(kotlin, "kotlin") == {"f": (3, 2)}+ assert _shape(source) == {"f": (3, 1)}+ assert _shape(kotlin, "kotlin") == {"f": (3, 1)}def test_a_catch_where_filter_is_one_more_decision():@@ -240,8 +240,8 @@ def test_try_marks_and_defer_are_not_decisions():assert _shape(source) == {"f": (1, 0)}-def test_a_do_block_with_no_catch_opens_a_level_and_adds_no_path():- assert _f(" do { if a > 0 { return 1 } }") == (2, 2)+def test_a_do_block_with_no_catch_adds_no_path_and_no_level():+ assert _f(" do { if a > 0 { return 1 } }") == (2, 1)# -- what is a function -------------------------------------------------------------