Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 10 additions & 9 deletions .coupling-baseline.json
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
{
"version": 1,
"pairs": {
"Techtrain\\CouplingMeter\\Balance -> Techtrain\\CouplingMeter": 7,
"Techtrain\\CouplingMeter\\Balance -> Techtrain\\CouplingMeter\\Config": 8,
"Techtrain\\CouplingMeter\\History -> Techtrain\\CouplingMeter": 2,
"Techtrain\\CouplingMeter\\Report -> Techtrain\\CouplingMeter": 2,
"Techtrain\\CouplingMeter\\Balance -> Techtrain\\CouplingMeter": 10,
"Techtrain\\CouplingMeter\\Balance -> Techtrain\\CouplingMeter\\Config": 5,
"Techtrain\\CouplingMeter\\Config -> Techtrain\\CouplingMeter\\History": 5,
"Techtrain\\CouplingMeter\\History -> Techtrain\\CouplingMeter": 10,
"Techtrain\\CouplingMeter\\Report -> Techtrain\\CouplingMeter": 10,
"Techtrain\\CouplingMeter\\Report -> Techtrain\\CouplingMeter\\Balance": 8,
"Techtrain\\CouplingMeter\\Report -> Techtrain\\CouplingMeter\\Config": 8,
"Techtrain\\CouplingMeter\\Report -> Techtrain\\CouplingMeter\\History": 8,
"Techtrain\\CouplingMeter\\Report -> Techtrain\\CouplingMeter\\Source": 8,
"Techtrain\\CouplingMeter\\Source -> Techtrain\\CouplingMeter": 2,
"Techtrain\\CouplingMeter\\Source -> Techtrain\\CouplingMeter\\Config": 8
"Techtrain\\CouplingMeter\\Report -> Techtrain\\CouplingMeter\\Config": 5,
"Techtrain\\CouplingMeter\\Report -> Techtrain\\CouplingMeter\\History": 5,
"Techtrain\\CouplingMeter\\Report -> Techtrain\\CouplingMeter\\Source": 10,
"Techtrain\\CouplingMeter\\Source -> Techtrain\\CouplingMeter": 10,
"Techtrain\\CouplingMeter\\Source -> Techtrain\\CouplingMeter\\Config": 6
}
}
5 changes: 5 additions & 0 deletions .github/workflows/coupling.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ jobs:

# 基準から増えた組だけを見る。基準は .coupling-baseline.json で、
# 直すか受け入れるかを決めたら --write-baseline で更新する。
#
# 均衡度は変動性を含み、変動性は git 履歴の分位なので、コミットが増えると
# 全モジュールの順位が動く。履歴が短いうちは基準が揺れやすい。
# 測り方を変えるオプション(--max-commit-files、--depth、--since、--preset)を
# 変えたときも、基準は作り直す必要がある。
- name: Measure coupling balance
run: >-
bin/coupling-meter . --include=src --depth=3
Expand Down
14 changes: 14 additions & 0 deletions README.ja.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,20 @@ BALANCE = (STRENGTH XOR DISTANCE) OR NOT VOLATILITY
| 変更の中身 | git log | Conventional Commits の prefix から、機能を足す変更(feat、perf)、修正(fix)、整備(refactor ほか)に分ける |
| co-change | git log | 2 つのモジュールが同じコミットで変わった割合。コミット集合の Jaccard 係数(共起 / 和集合)。何とでも一緒に変わる巨大モジュールとの組が 100% に張り付かないようにしている |

<<<<<<< HEAD
### 大量のファイルを触ったコミットは外す

全体の一括整形やライセンスヘッダの更新は、1 コミットで全モジュールの組に共起を作るが、知識は何も共有していない。
原著の結合は「変更が伝播する関係」なので、伝播していない変更は数えない。解析対象のファイルを `--max-commit-files`(既定 50)より多く触ったコミットは履歴ごと外す。
変動性と所有者の重なりからも同時に消える。`--max-commit-files=0` で無効にできる。

10 年分の履歴がある公開 OSS の PHP プロジェクトで測ると、3,358 件中 35 件が外れる(最大の一括整形コミットは PHP を 800 ファイル以上触っている)。同時変更率の平均は 0.048 から 0.023 へ半減し、
一緒に変わっているように見えていた 33 組は、共有するコミットが 1 件もなくなる。

この値を変えると測るものが変わるので、**ある値で書いた基準(`--baseline`)は別の値と比べられない**。変えたら `--write-baseline` で基準を作り直す。
=======
`--json` には `co_change_subjects` も入る。両方のモジュールを変えたコミットの subject が最大 5 件。率だけでは、構造から来る必然なのか、同じ機能追加に巻き込まれただけなのかが分からないので、そこを判断する側に中身を渡す。
>>>>>>> origin/main

3 以上を高、2 以下を低として規則に入れ、象限とバランスの成否を出す。

Expand Down Expand Up @@ -195,6 +208,7 @@ Findings
| `--rules` | 自動検出 | 意図した依存の許可ルール。省略時は root の `coupling-meter.yaml` / `deptrac.yaml` / `deptrac.config.yaml` を探す |
| `--codeowners` | 自動検出 | 所有者の宣言。省略時は root、`.github/`、`docs/`、`.gitlab/` の `CODEOWNERS` を探す。あれば git の著者より優先する |
| `--split` | 0 | この数を超えるクラスを持つ名前空間は、その子名前空間を別モジュールとして切る。`App\Models` のような巨大モジュールとの組で VOL と同時変更率が天井に張り付くのを防ぐ。子もまだ大きければさらに切る |
| `--max-commit-files` | 50 | 解析対象のファイルをこの数より多く触ったコミットを履歴から外す。一括整形やライセンス更新は、知識を共有しないまま全組に共起を作るため。`0` で無効 |
| `--weight-by-references` | なし | 順位づけを参照数の対数で重み付けする。原著は数ではなく性質を見る立場なので既定では使わない。参照 1 箇所の組が上位を埋めて読みにくいときに |
| `--format` | text | 出力の形(`text` / `json` / `samples` / `github`)。`--json` と `--samples` は同じものの別名 |
| `--fail-on` | なし | 均衡度がこの値以下の組があれば終了コード 1 を返す |
Expand Down
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ A pair is modular when strength and distance cancel each other out, and complex

`--json` also carries `co_change_subjects`: the messages of up to five commits that changed both modules. The rate alone cannot tell a structural necessity from two modules being swept into the same feature; the messages are there for whoever, or whatever, makes that call.

### Bulk commits are dropped

A single commit that reformats the whole tree or updates every license header creates co-change between every pair of modules while sharing no knowledge at all. Coupling in the book is a relationship through which *change propagates*, so a change that propagates nothing is not counted: commits touching more than `--max-commit-files` analyzed files (default 50) are removed from the history entirely, which keeps them out of volatility and ownership as well. Pass `--max-commit-files=0` to keep them.

Measured on an open-source PHP project with ten years of history, 35 of 3,358 commits are dropped — the largest reformatting commit touched over 800 PHP files — and the average co-change rate halves from 0.048 to 0.023. 33 pairs that appeared to change together turn out to have no shared commit at all.

Changing this value changes what is measured, so a baseline written under one value cannot be compared against another. Rewrite the baseline with `--write-baseline` after changing it.

Three and above counts as high, two and below as low. Those feed the rules and produce the quadrant and the balance verdict.

Ranking uses the balanced coupling equation from section 10.3, with all three dimensions placed on a 1 to 10 scale.
Expand Down Expand Up @@ -190,6 +198,7 @@ How to read it. `Shop\Checkout -> Shop\Catalog` is model coupling by type, and C
| `--rules` | auto-detect | Allowed dependencies. Looks for `coupling-meter.yaml` / `deptrac.yaml` / `deptrac.config.yaml` at root when omitted |
| `--codeowners` | auto-detect | Ownership declaration. Looks for `CODEOWNERS` at root, `.github/`, `docs/` and `.gitlab/` when omitted. Takes precedence over git authors |
| `--split` | 0 | Namespaces with more classes than this are split into their child namespaces. Prevents VOL and co-change from pinning at the ceiling for pairs involving a huge module such as `App\Models`. Splits again if a child is still too large |
| `--max-commit-files` | 50 | Drop commits that touched more than this many analyzed files. Bulk reformatting and license updates create co-change between everything while sharing no knowledge. `0` keeps them |
| `--weight-by-references` | none | Weight the ranking by the logarithm of the reference count. Off by default, since the book looks at the nature of a relationship rather than its count. Useful when pairs with a single reference crowd the top |
| `--format` | text | Output shape (`text` / `json` / `samples` / `github`). `--json` and `--samples` are aliases for the same thing |
| `--fail-on` | none | Exit with code 1 if a pair at or below this balance is present |
Expand Down
10 changes: 8 additions & 2 deletions bin/coupling-meter
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ if ($options->help || $options->path === null) {
--preset framework conventions (laravel / symfony / none, comma separated).
Guessed from composer.json when omitted. Define your own under
presets: in coupling-meter.yaml and call it by name
--max-commit-files
drop commits that touched more than this many analyzed files
(default 50, 0 to disable). Bulk reformatting and license updates
create co-change between everything while sharing no knowledge
--split split namespaces with more classes than this one level deeper
(default 0 = never split)
--weight-by-references
Expand Down Expand Up @@ -97,7 +101,7 @@ $includes = $options->includes;
$analyzer = new Analyzer($root, $excludes, $includes, $preset);
$analyzer->run();

$git = new GitHistory($root, $since);
$git = new GitHistory($root, $since, $options->maxCommitFiles);
$hasGit = $git->load();

try {
Expand Down Expand Up @@ -158,6 +162,7 @@ if ($options->json) {
$payload = [
'root' => $root,
'preset' => $preset->name,
'skipped_commits' => $git->skipped(),
'stats' => $stats,
'pairs' => array_map(static function (Pair $pair): array {
$array = $pair->toArray();
Expand Down Expand Up @@ -243,7 +248,7 @@ $dim = static fn (string $text): string => "\033[2m{$text}\033[0m";

fwrite(STDOUT, "\n" . $bold('coupling-meter') . ' ' . $dim($root) . "\n");
fwrite(STDOUT, sprintf(
" classes %d / references %d / modules %d / pairs %d / commits %s / preset %s\n\n",
" classes %d / references %d / modules %d / pairs %d / commits %s%s / preset %s\n\n",
$stats['classes'],
$stats['references'],
$stats['modules'],
Expand All @@ -253,6 +258,7 @@ fwrite(STDOUT, sprintf(
$git->isRepository() => '— (no commit touched PHP in this window; widen --since)',
default => '— (no git history)',
},
$git->skipped() === 0 ? '' : sprintf(' (%d bulk commits skipped)', $git->skipped()),
$preset->name,
));

Expand Down
7 changes: 6 additions & 1 deletion src/Config/Options.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace Techtrain\CouplingMeter\Config;

use Techtrain\CouplingMeter\History\GitHistory;

/**
* コマンドライン引数。
*
Expand All @@ -15,7 +17,7 @@ final class Options
public const DEFAULT_EXCLUDES = ['vendor', 'node_modules', 'storage', 'bootstrap/cache', 'tests', 'test'];

/** 値が要るオプション */
private const VALUED = ['depth', 'since', 'top', 'include', 'exclude', 'rules', 'split', 'codeowners', 'preset', 'format', 'fail-on', 'baseline'];
private const VALUED = ['depth', 'since', 'top', 'include', 'exclude', 'rules', 'split', 'codeowners', 'preset', 'format', 'fail-on', 'baseline', 'max-commit-files'];

/** 値を取らないオプション */
private const FLAGS = ['help', 'json', 'samples', 'weight-by-references', 'write-baseline'];
Expand Down Expand Up @@ -56,6 +58,8 @@ private function __construct(
public readonly ?string $baseline,
/** baseline のファイルを今の計測で書き直して終わる */
public readonly bool $writeBaseline,
/** この数を超える解析対象ファイルを触ったコミットは履歴から外す。0 で無効 */
public readonly int $maxCommitFiles,
) {
}

Expand Down Expand Up @@ -147,6 +151,7 @@ public static function parse(array $arguments): self
failOn: isset($values['fail-on']) ? self::integer('fail-on', $values['fail-on']) : null,
baseline: $values['baseline'] ?? null,
writeBaseline: $flags['write-baseline'] ?? false,
maxCommitFiles: self::integerOrZero('max-commit-files', $values['max-commit-files'] ?? (string) GitHistory::DEFAULT_MAX_FILES),
);
}

Expand Down
30 changes: 30 additions & 0 deletions src/History/GitHistory.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,33 @@ final class GitHistory
/** @var array<string, string> コミットハッシュ => 1 行目のメッセージ */
private array $subjects = [];

/**
* 一括整形やライセンス更新のような、1 コミットで大量のファイルを触る変更の既定の上限。
*
* この種のコミットは 1 件で全モジュールの組に共起を作るが、知識は何も共有していない。
* 原著の結合は「変更が伝播する関係」なので、伝播していない変更は数えない。
*/
public const DEFAULT_MAX_FILES = 50;

/** 大量のファイルを触ったせいで履歴から外したコミット数 */
private int $skipped = 0;

/**
* @param int $maxFiles この数を超える解析対象ファイルを触ったコミットは履歴から外す。0 で無効
*/
public function __construct(
private readonly string $root,
private readonly string $since = '12 months ago',
private readonly int $maxFiles = self::DEFAULT_MAX_FILES,
) {
}

/** 履歴から外したコミット数 */
public function skipped(): int
{
return $this->skipped;
}

private string $prefix = '';

/** 解析対象が git の作業ツリーの中にあるか。履歴が空でも true。 */
Expand Down Expand Up @@ -74,6 +95,15 @@ public function load(): bool
}
}

if ($this->maxFiles > 0) {
foreach ($this->commits as $hash => $files) {
if (\count($files) > $this->maxFiles) {
unset($this->commits[$hash], $this->authors[$hash], $this->subjects[$hash]);
++$this->skipped;
}
}
}

return $this->commits !== [];
}

Expand Down
40 changes: 40 additions & 0 deletions tests/GitHistoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -141,4 +141,44 @@ public function testCoChangeSubjectsAreCappedByTheLimit(): void
$this->assertNotNull($key);
$this->assertCount(2, $subjects[$key]);
}

public function testBulkCommitsAreDroppedFromHistory(): void
{
// 一括整形に相当するコミット。触ったファイルは多いが、知識は何も共有していない
for ($i = 0; $i < 6; ++$i) {
file_put_contents($this->repo . '/app/Bulk' . $i . '.php', '<?php');
}
$this->git('add -A');
$this->git('commit -q -m "chore: ライセンスヘッダを一括更新"');

$git = new GitHistory($this->repo, '1 year ago', 5);
$this->assertTrue($git->load());
$this->assertSame(1, $git->skipped());

$modules = $git->moduleCommits(['app/Bulk0.php' => ['App\\Bulk']]);
$this->assertSame([], $modules['App\\Bulk'] ?? []);
}

public function testBulkCommitsAreKeptWhenTheLimitIsZero(): void
{
for ($i = 0; $i < 6; ++$i) {
file_put_contents($this->repo . '/app/Bulk' . $i . '.php', '<?php');
}
$this->git('add -A');
$this->git('commit -q -m "chore: ライセンスヘッダを一括更新"');

$git = new GitHistory($this->repo, '1 year ago', 0);
$this->assertTrue($git->load());
$this->assertSame(0, $git->skipped());

$modules = $git->moduleCommits(['app/Bulk0.php' => ['App\\Bulk']]);
$this->assertCount(1, $modules['App\\Bulk'] ?? []);
}

public function testOrdinaryCommitsSurviveTheLimit(): void
{
$git = new GitHistory($this->repo, '1 year ago', 5);
$this->assertTrue($git->load());
$this->assertSame(0, $git->skipped());
}
}
7 changes: 7 additions & 0 deletions tests/OptionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,11 @@ public function testWriteBaselineNeedsABaselinePath(): void

Options::parse(['.', '--write-baseline']);
}

public function testMaxCommitFilesDefaultsToFiftyAndAcceptsZero(): void
{
$this->assertSame(50, Options::parse(['.'])->maxCommitFiles);
$this->assertSame(0, Options::parse(['.', '--max-commit-files=0'])->maxCommitFiles);
$this->assertSame(200, Options::parse(['.', '--max-commit-files=200'])->maxCommitFiles);
}
}
Loading