From bf4fdfc8319f23485c0f78a37ade8f52d4b63c80 Mon Sep 17 00:00:00 2001 From: dodoshell <326978213+dodoshell@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:44:01 +0100 Subject: [PATCH] fix(srp): count sibling modules as one concern concernLabel returned the first segment that differs from the module's own path, so for a module importing a sibling in its own package that segment was the sibling's file name. A facade composing a few private helpers (_actor importing _errors, _ref, _registry, _messages) was reported as mixing one concern per file, while the same edges raised the package's cohesion. A direct sibling module now maps to one label named after the shared package, so siblings count as at most one concern and flat-layout packages are still checked instead of having the rule switched off. A generic package name such as utils is skipped, as it is elsewhere. Sibling subpackages and modules elsewhere in the project are labelled as before. Closes #846 --- service/responsibility_analysis.go | 6 ++++ service/responsibility_analysis_test.go | 34 +++++++++++++++++++ .../docs/fr/rules/single-responsibility.md | 2 +- .../docs/ja/rules/single-responsibility.md | 2 +- website/docs/rules/single-responsibility.md | 2 +- .../docs/zh/rules/single-responsibility.md | 2 +- 6 files changed, 44 insertions(+), 4 deletions(-) diff --git a/service/responsibility_analysis.go b/service/responsibility_analysis.go index 95a98536..d03b4890 100644 --- a/service/responsibility_analysis.go +++ b/service/responsibility_analysis.go @@ -268,6 +268,12 @@ func concernLabel(module, neighbor string) string { for i < limit && moduleParts[i] == neighborParts[i] { i++ } + // Sibling modules in the module's own package share one concern named + // after that package, so a facade over private helpers is not counted as + // mixing one concern per file (#846). + if i > 0 && i == len(moduleParts)-1 && len(neighborParts) == len(moduleParts) { + return firstMeaningfulSegment(moduleParts[i-1 : i]) + } if i < len(neighborParts) { return firstMeaningfulSegment(neighborParts[i:]) } diff --git a/service/responsibility_analysis_test.go b/service/responsibility_analysis_test.go index efe2f66b..5d5170e1 100644 --- a/service/responsibility_analysis_test.go +++ b/service/responsibility_analysis_test.go @@ -173,6 +173,40 @@ func TestConcernLabelSkipsGenericSegments(t *testing.T) { assert.Equal(t, "billing", label) } +func TestConcernLabelGroupsSiblingModules(t *testing.T) { + assert.Equal(t, "mypkg", concernLabel("mypkg._actor", "mypkg._errors")) + assert.Equal(t, "unit", concernLabel("engine.unit.unit", "engine.unit.add_leader_buff")) + assert.Equal(t, "routers", concernLabel("myapp.core", "myapp.routers.user_router")) + assert.Equal(t, "dns", concernLabel("aiomisc.service.dns.service", "aiomisc.service.dns.records")) + assert.Equal(t, "", concernLabel("app.utils.dates", "app.utils.strings")) +} + +// Regression for #846: a facade composing private helpers from its own +// package must count them as one concern, not one per sibling module. +func TestAnalyzeResponsibilityCountsSiblingModulesAsOneConcern(t *testing.T) { + service := NewSystemAnalysisService() + graph := analyzer.NewDependencyGraph("/test/project") + + siblings := []string{ + "mypkg._errors", + "mypkg._messages", + "mypkg._ref", + "mypkg._registry", + } + graph.AddModule("mypkg._actor", "/test/project/mypkg/_actor.py") + for _, module := range siblings { + graph.AddModule(module, "/test/project/"+module+".py") + graph.AddDependency("mypkg._actor", module, analyzer.DependencyEdgeImport, nil) + } + + responsibility, _, violations := service.analyzeResponsibility(graph, defaultResponsibilityOptions()) + + require.NotNil(t, responsibility) + assert.Equal(t, []string{"mypkg"}, responsibility.ModuleResponsibilities["mypkg._actor"]) + assert.Empty(t, responsibility.SRPViolations) + assert.Empty(t, violations) +} + func TestAnalyzeResponsibilityForRequestKeepsCohesionIndependent(t *testing.T) { service := NewSystemAnalysisService() graph := analyzer.NewDependencyGraph("/test/project") diff --git a/website/docs/fr/rules/single-responsibility.md b/website/docs/fr/rules/single-responsibility.md index 87b16e32..93218bcf 100644 --- a/website/docs/fr/rules/single-responsibility.md +++ b/website/docs/fr/rules/single-responsibility.md @@ -8,7 +8,7 @@ Signale un module qui mélange plus de `architecture.max_responsibilities` (par défaut `3`) préoccupations de dépendance distinctes, ou qui agit comme un hub fan-in/fan-out pour plus de préoccupations que la moyenne du reste du projet. -Une « préoccupation » est déduite des noms des dépendances du module : pour chaque module qu'il importe, l'analyseur prend le premier segment du chemin de la dépendance qui ne fait pas partie du chemin du module courant et qui n'est pas un terme générique fourre-tout (`base`, `common`, `helpers`, `node`, `shared`, `util`, `utils`). Ces segments sont dédupliqués ; le compte donne le nombre de responsabilités que pyscn attribue au module. Les modules qui l'importent (fan-in) ne contribuent aucune préoccupation — être largement réutilisé n'est pas une responsabilité. +Une « préoccupation » est déduite des noms des dépendances du module : pour chaque module qu'il importe, l'analyseur prend le premier segment du chemin de la dépendance qui ne fait pas partie du chemin du module courant et qui n'est pas un terme générique fourre-tout (`base`, `common`, `helpers`, `node`, `shared`, `util`, `utils`). Les modules du même paquet que le module (ses modules frères) comptent tous comme une seule préoccupation nommée d'après ce paquet, afin qu'une façade sur des helpers privés ne compte pas une préoccupation par fichier ; les sous-paquets frères continuent de compter séparément. Ces segments sont dédupliqués ; le compte donne le nombre de responsabilités que pyscn attribue au module. Les modules qui l'importent (fan-in) ne contribuent aucune préoccupation — être largement réutilisé n'est pas une responsabilité. Un module est signalé lorsqu'au moins une des conditions suivantes est remplie : diff --git a/website/docs/ja/rules/single-responsibility.md b/website/docs/ja/rules/single-responsibility.md index 0ef39821..56867738 100644 --- a/website/docs/ja/rules/single-responsibility.md +++ b/website/docs/ja/rules/single-responsibility.md @@ -8,7 +8,7 @@ `architecture.max_responsibilities`(デフォルト `3`)を超える数の異なる依存関心事を抱えているモジュール、またはプロジェクト平均と比較してファンイン/ファンアウトが両方とも高いハブモジュールを検出します。 -「関心事」は依存先モジュールの名前から推定されます。当該モジュールがインポートする先のそれぞれについて、現在のモジュールのパスと一致しない最初のセグメントを取り出し、汎用的すぎる接尾辞(`base`, `common`, `helpers`, `node`, `shared`, `util`, `utils`)を除外します。残ったセグメントを重複排除した個数が、このモジュールに割り当てられた関心事の数になります。当該モジュールをインポートしてくる側(ファンイン)は関心事に数えません。広く再利用されていること自体は責務ではないためです。 +「関心事」は依存先モジュールの名前から推定されます。当該モジュールがインポートする先のそれぞれについて、現在のモジュールのパスと一致しない最初のセグメントを取り出し、汎用的すぎる接尾辞(`base`, `common`, `helpers`, `node`, `shared`, `util`, `utils`)を除外します。同じパッケージ内の兄弟モジュールは、そのパッケージ名を持つ1つの関心事としてまとめて数えます。そのため、プライベートなヘルパーを束ねるファサードがファイルごとに別の関心事を持つとは見なされません。兄弟のサブパッケージは引き続き個別に数えます。残ったセグメントを重複排除した個数が、このモジュールに割り当てられた関心事の数になります。当該モジュールをインポートしてくる側(ファンイン)は関心事に数えません。広く再利用されていること自体は責務ではないためです。 次のいずれかに該当するとレポートされます: diff --git a/website/docs/rules/single-responsibility.md b/website/docs/rules/single-responsibility.md index 0421844b..83cabaee 100644 --- a/website/docs/rules/single-responsibility.md +++ b/website/docs/rules/single-responsibility.md @@ -8,7 +8,7 @@ Flags a module that mixes more than `architecture.max_responsibilities` (default `3`) distinct dependency concerns, or that acts as a fan-in/fan-out hub for more concerns than the rest of the project does on average. -A "concern" is inferred from the names of the module's dependencies: for each module it imports, the analyzer takes the first segment of the dependency's path that is not part of the current module's path and not a generic catch-all (`base`, `common`, `helpers`, `node`, `shared`, `util`, `utils`). Those segments are deduplicated; the count is the number of responsibilities pyscn attributes to the module. Modules that import it (fan-in) do not contribute concerns — being widely reused is not a responsibility. +A "concern" is inferred from the names of the module's dependencies: for each module it imports, the analyzer takes the first segment of the dependency's path that is not part of the current module's path and not a generic catch-all (`base`, `common`, `helpers`, `node`, `shared`, `util`, `utils`). Modules in the module's own package (its siblings) all count as one concern named after that package, so a facade over private helpers is not counted as one concern per file; sibling subpackages still count separately. Those segments are deduplicated; the count is the number of responsibilities pyscn attributes to the module. Modules that import it (fan-in) do not contribute concerns — being widely reused is not a responsibility. A module is reported when either condition holds: diff --git a/website/docs/zh/rules/single-responsibility.md b/website/docs/zh/rules/single-responsibility.md index 551933a0..ca11f8ca 100644 --- a/website/docs/zh/rules/single-responsibility.md +++ b/website/docs/zh/rules/single-responsibility.md @@ -8,7 +8,7 @@ 标记承担超过 `architecture.max_responsibilities`(默认 `3`)个不同依赖关注点的模块,或扇入扇出均高于项目平均水平的枢纽模块。 -"关注点"由该模块依赖的名称推断而来:对于它导入的每个模块,分析器取依赖路径中与当前模块不重叠的第一个段,并跳过通用兜底名称(`base`、`common`、`helpers`、`node`、`shared`、`util`、`utils`)。去重后的段数即为 pyscn 归属于该模块的职责数量。导入它的模块(扇入)不计入关注点——被广泛复用本身不是一种职责。 +"关注点"由该模块依赖的名称推断而来:对于它导入的每个模块,分析器取依赖路径中与当前模块不重叠的第一个段,并跳过通用兜底名称(`base`、`common`、`helpers`、`node`、`shared`、`util`、`utils`)。同一包内的兄弟模块统一计为一个以该包命名的关注点,因此组合私有辅助模块的门面模块不会按文件逐个计为关注点;兄弟子包仍分别计数。去重后的段数即为 pyscn 归属于该模块的职责数量。导入它的模块(扇入)不计入关注点——被广泛复用本身不是一种职责。 满足以下任一条件即会报告: