Zum Inhalt springen

A baseline quality gate for legacy .NET solutions

A baseline freezes existing findings. Which combination with diff analysis lets new errors through, and how review checks baseline updates.

by CodeCharter
  • code-quality
  • legacy-code
  • continuous-integration

A tech lead runs CodeCharter v1.7.0 for the first time over a .NET solution that has been in production for years. The solution and its Git history are constructed for this article; the output comes from real runs. The profile codeguard/csharp-all v1.3.0 ships 248 rules. The run ends with exit 1:

> codecharter analyze Shop.slnx
…
  145 violations (4 errors, 7 warnings, 134 infos)
  …

122 of the 145 findings report missing XML documentation. The four errors are an empty catch, a throw ex; that loses the stack trace, and two reports about an async void method. A gate on the full analysis therefore keeps main and every pull request red until the existing code is fixed.

With four errors that is a workable path: the team fixes them and then runs the gate with --fail-on error. If the first run reports more errors, or if the gate is meant to block at warn or info already, that path does not hold up.

Baseline

A baseline records the existing state. --write-baseline analyzes the solution and writes all findings to a file. The console confirms this only with --verbose:

> codecharter analyze Shop.slnx --write-baseline .codecharter/baseline.json --verbose
Rules: 248 from codeguard/csharp-all@1.3.0
Found 32 types, 65 methods
Wrote baseline with 145 finding(s) to ...\.codecharter\baseline.json

The file contains a fingerprint for each finding. It is a hash of the rule, the element, the file path and, for methods, the parameter types. The line number and the message text are not part of it, so shifted lines do not make a finding new. Similar occurrences in the same file, such as two empty catch blocks, are distinguished by a counter based on their order. Findings on a declaration also get an identity made of the rule and the symbol name:

{
  "schemaVersion": 1,
  "fingerprints": [
    "002869cae4d1ac2c891f0ec2999c7165",
    "009b41fb6c82dab2d8cc0f5ccce7811b",
    …
  ],
  "identities": [
    …
    "class-too-large\nT:Shop.Orders.OrderService",
    "high-efferent-coupling\nT:Shop.Orders.OrderExporter",
    …
    "rethrow-loses-stack-trace\nM:Shop.Infrastructure.SqlOrderRepository.Save(Shop.Orders.Order)",
    …
  ],
  "migrationJournal": [],
  "fingerprintAnchor": "repository"
}

135 of the 145 findings have an identity. The other ten are attached to a code location without a declaration of its own, such as an empty catch or a numeric literal. A finding counts as known if its fingerprint or its identity is in the file. Against the baseline, the same run reports nothing:

> codecharter analyze Shop.slnx --baseline .codecharter/baseline.json --fail-on error
Rules: 248 from codeguard/csharp-all@1.3.0
No violations found.
  0 violations
  …

The output does not say that 145 findings were suppressed. The first pull request adds a method with an empty catch to SqlOrderRepository:

public Order? FindOrDefault(int id)
{
    try
    {
        return _orders[id];
    }
    catch (KeyNotFoundException)
    {
    }

    return null;
}

Against the baseline, the gate reports the empty catch at line 42 and the method's missing XML documentation. It ends with exit 1. The baseline documentation describes the file format and the matching in detail.

Baseline and diff analysis

With --git-ref, CodeCharter reports only findings on the lines the PR changes. Findings on other lines of touched files are merely counted on stderr:

> codecharter analyze Shop.slnx --baseline .codecharter/baseline.json --git-ref main..HEAD --fail-on error --output json
Note: 6 finding(s) in diff-touched files fall outside the changed lines (e.g. class- or namespace-level findings) and were NOT gated. Re-run with --diff-context to report them.
…

In the example all six are already in the baseline, yet the note still counts them. This run, too, reports the new error with exit 1.

Two more PRs show where the variants differ. In pr/try-find, the same code appears as TryFind above the old method Find, which has an empty catch of its own. In pr/order-step33, OrderService gets a 33rd method and exceeds 1000 lines of code. The god-class rule then reports the class at its declaration on line 5, which the PR does not change.

The table summarizes the JSON output. pr/try-find runs with --fail-on error, pr/order-step33 with --fail-on warn, because god-class has severity warn:

Variant pr/try-find pr/order-step33
Baseline only Error at line 28, exit 1 god-class, exit 1
--git-ref only Error at line 15, exit 1 Nothing, exit 0
--git-ref --diff-context 9 findings, 3 of them errors, exit 1 42 findings, exit 1
Baseline and --git-ref No error, exit 0 Nothing, exit 0
Baseline, --git-ref and --diff-context Error at line 28, exit 1 god-class, exit 1

Both empty catch blocks in pr/try-find have the same base key; the baseline tells them apart only by their order in the file. The new catch at line 15 therefore takes over the fingerprint of the old one. The old one at line 28 shows up as new, and the baseline alone reports the error at the wrong location. With --git-ref, line 28 drops out as unchanged, and the new error passes the gate.

Without a baseline, --diff-context pulls all old findings of the touched file into the PR, for OrderService 41 old ones next to the god class. With a baseline, only the new finding remains. The baseline alone and the baseline with --git-ref --diff-context blocked both PRs with exit 1, although in pr/try-find the baseline alone did so at the old line. The baseline with --git-ref alone let both cases through. These results come from v1.7.0. In versions after v1.7.1, --git-ref without --diff-context no longer only counts these findings: those at or above --fail-on (every one when --fail-on is not given) fail the run and are named on stderr by severity and rule; --diff-context still reports all of them, and --no-diff-context-gate restores the count-only behaviour (analyze documentation). For the table this means: on findings at or above the threshold, --git-ref alone and the baseline with --git-ref then block like their counterparts with --diff-context.

Findings in files the PR does not touch are not covered by --diff-context either, for example a namespace rule triggered by another type. This follows from the implementation; the example does not demonstrate it. The baseline alone does not have this limit. Every PR therefore runs against the baseline. Anyone who also sets --git-ref needs --diff-context up to v1.7.1; later versions gate findings at the threshold without it, and --diff-context adds those below. How the diff analysis treats a feature PR on a large class is shown in the article on prioritizing technical debt.

Gate severity

In the csharp-all v1.3.0 profile, no architecture or size rule has severity error. god-class is warn; class-too-large, high-afferent-coupling and high-efferent-coupling are info. With --fail-on error, the gate reports the god class from pr/order-step33 and still ends with exit 0:

> codecharter analyze Shop.slnx --baseline .codecharter/baseline.json --fail-on error
  WARN   [Architecture] God class
        Shop.Orders.OrderService
        ...\src\Shop\Orders\OrderService.cs:5
  1 violation (1 warning)

The same happens to a new class AuditCatalog that references 22 model types through fields. The high-efferent-coupling rule reports it with severity info:

> codecharter analyze Shop.slnx --baseline .codecharter/baseline.json
  INFO   [Architecture] High efferent coupling
        Shop.Orders.AuditCatalog
        ...\src\Shop\Orders\AuditCatalog.cs:6
  1 violation (1 info)
  …

Without --fail-on and with --fail-on info, this run ends with exit 1; with --fail-on warn or --fail-on error, it ends with exit 0. Without a baseline, --fail-on info on the full analysis would not be sustainable, because the 122 missing doc comments would hold up every PR. With a baseline, the gate reports only new findings. --fail-on selects a threshold, not individual rules: with --fail-on info, the new coupling blocks, but so does every missing XML doc comment.

A study on SonarQube shows that a rule's severity says little about defects. Lenarduzzi, Saarimäki and Taibi examined its rules in 33 Apache Java projects with around 200,000 classes. Classes with issues were practically no more fault-prone; the difference was significant, the effect negligible. Of 36 rules in the "Bug" category, only one increased fault-proneness. The study concerns Java and SonarQube, not .NET and not CodeCharter. The authors recommend choosing rules based on one's own defect history. For the gate this means: the threshold is the team's own decision and does not follow from the severity a profile assigns.

Moves and renames

Refactorings of existing code change what the baseline recognizes. If a PR moves PriceHelper.cs to another folder and keeps the namespace, the findings on declarations stay suppressed. The file's three numeric literals show up as new, because their fingerprint contains the file path. If the PR also changes the namespace, all eight findings in the file are new. Both runs end with exit 0 under --fail-on error, because none of the findings is an error.

If a PR renames the class SqlOrderRepository to OrderRepository, the old rethrow-loses-stack-trace error on Save shows up as new. The gate ends with exit 1. For such cases there is codecharter baseline migrate. If the file name stays the same, it finds nothing:

> codecharter baseline migrate Shop.slnx --baseline .codecharter/baseline.json --git-ref main..HEAD
No stale baseline identities found in the renamed files. Nothing to migrate.

migrate works only with files that Git detects as renamed. If both the class and the file are renamed, it maps the type but not the methods, because the file contains several candidates:

> codecharter baseline migrate Shop.slnx --baseline .codecharter/baseline.json --git-ref main..HEAD
Proposed rename mappings (1):
  [Renamed ] missing-xml-doc: T:Shop.Infrastructure.SqlOrderRepository -> T:Shop.Infrastructure.OrderRepository  (…SqlOrderRepository.cs -> …OrderRepository.cs)

Unresolved - needs manual attention (4):
  missing-xml-doc: M:Shop.Infrastructure.SqlOrderRepository.Count
    reason: Multiple candidate symbols were found in the renamed files.
  …
  rethrow-loses-stack-trace: M:Shop.Infrastructure.SqlOrderRepository.Save(Shop.Orders.Order)
…

The empty catch in the same file has only a fingerprint with the old file path and does not appear in the list at all. A PR that renames or moves code therefore rewrites the baseline in the same PR. The cross-check from the next section then also reports the relocated old findings. Renames therefore go into a separate PR without functional changes, so that every new entry corresponds to a relocated finding.

Baseline maintenance

If a PR fixes two of the old errors, the run against the baseline still reports "No violations found". It does not say that the entries of the two fixed findings no longer match. Only a new run with --write-baseline removes them:

> codecharter analyze Shop.slnx --write-baseline .codecharter/baseline.json --verbose
…
Wrote baseline with 143 finding(s) to ...\.codecharter\baseline.json
> git diff --stat
 .codecharter/baseline.json | 3 ---

A stale entry that stays in the file lets a later error of the same kind through. In the example, a PR adds a method Load with an empty catch (KeyNotFoundException) to the same file. Against the old baseline, the gate ends with exit 0 under --fail-on error; against the reduced one, with exit 1.

Rewriting, however, also absorbs new findings. If the author of the PR with FindOrDefault rewrites the baseline, the gate turns green. The baseline diff shows only hashes:

@@ -40,9 +40,11 @@
     "3d3e607321d24fe9dbd5db538ddf6ba4",
+    "3d6f3d3016200a4c785316c0d005768b",
     "41bef2fba3f86b456279e70156e78a31",
     "42861f0be70adb1cfccb60fc3cf10b90",
     "45566d0a950748c9d5b549c760bac5f7",
+    "4a4a3de6e84dfcdffe968ca50f8e0fcb",
     "4a6c4873bdba54d540eb7156a55c011a",
@@ -161,6 +163,7 @@
+    "missing-xml-doc\nM:Shop.Infrastructure.SqlOrderRepository.FindOrDefault(System.Int32)",

The first new hash is the empty catch. What it means only becomes visible in a cross-check against the baseline from main:

git show main:.codecharter/baseline.json > baseline-main.json
codecharter analyze Shop.slnx --baseline baseline-main.json --fail-on error --output json

The run ends with exit 1 and reports the empty catch at line 42 and the missing XML documentation of FindOrDefault. For both, the JSON output names exactly the two new fingerprints from the diff. A PR that only fixes existing findings removes lines from baseline.json. If lines are added, the review runs the cross-check against main, and every new entry needs a justification in the PR.

Imtiaz, Murphy and Williams (ISSRE 2019) evaluated 39,495 Coverity alerts from five open source projects, including Linux and Firefox. Depending on the project, 27.4% to 49.5% were fixed. An alert counted as fixed if it disappeared after a change to its file. The study excluded alerts from before the first recorded report. The fixes changed a median of only 2 to 7 lines and still remained outstanding for a median of 36 to 245 days. Even small fixes therefore stay open for a long time, and without regular rewriting, baseline entries remain in the file for a correspondingly long time.

A team whose existing code has hardly any errors and no large classes can do without a baseline. The diff gate then reports new errors on changed lines, needs no file and has no rename problem.

For the example this means: coupling and size are meant to block, so every PR runs against the baseline with --fail-on info. New methods then also need XML documentation. baseline.json changes only with a justification, and the review checks every new line with the cross-check against main. The article on technical debt in C# projects prioritizes paying down the existing code. The article on code quality in CI pipelines shows the pipeline integration, and the analysis documentation describes all options of analyze.