Duplicated code
assay finds copied code: a run of code that stands at two or more places of your project’s shipped code. It compares tokens, not text. A copy whose labels, sizes, comments, indentation or line breaks were changed is still a copy; one whose names were changed is not.
The check, duplicated_code, is advisory and on under every preset. It never fails a turn. Only a gate condition you write fails anything on it, where the gate is run with --duplication, in CI or by hand.
Running the check
Section titled “Running the check”It is one of the five cross-file checks, and runs in the one pass they share:
assay cross-file # every cross-file checkassay cross-file duplicated_code # this check aloneThe whole-project pass of assay gate and of assay baseline update runs it too, and assay metrics shows the share of duplicated lines (In the metric report).
Each copy is reported as a duplicated region: a run of lines in one file that copied code covers. The console report groups them: every place of the same code stands in one numbered group, by its file, its line range and its size, the largest group first, and how to fix it is said once below the groups. On a project whose detail and home screens share 29 lines, and whose repository holds one block twice:
╭─ assay cross-file ───────────────────────────────────────────────────────────╮│ Preset recommended ││ Checks duplicated_code ││ Files 4 │╰──────────────────────────────────────────────────────────────────────────────╯
╭─ ! duplicated_code · advisory ───────────────────────── 2 groups · 4 places ─╮│ File Lines Size ││ ──────────────────────────────────────────────────────────────────────── ││ 1 2 places ││ lib/screens/detail.dart 4–32 29 lines ││ lib/screens/home.dart 4–32 29 lines ││ ││ 2 2 places in one file ││ lib/data/repository.dart 5–16 12 lines ││ 19–30 12 lines ││ ││ → Move the shared code into one function, widget or class, and use it from ││ each place. │╰──────────────────────────────────────────────────────────────────────────────╯
╭─ ✓ PASS ─────────────────────────────────────────────────────────────────────╮│ 0 blocking · 4 advisory · 3 of 4 files │╰──────────────────────────────────────────────────────────────────────────────╯The cross-file pass read 4 Dart files and took 1.0 s.The verdict counts results, and each region is one. The other reports carry each region as a result of its own, whose message names the other places of the same code, three by their files and lines and the rest by their number (see duplicated_code).
To fix it, move the shared code into one function, widget or class, and use it from each place. Where a copy is kept on purpose, take its path out with the check’s exclude (Configuration).
Results
Section titled “Results”- Each region is one advisory result. Two copies of a widget in two files are two results, each naming the other. Two copies of one block in one file are two regions as well.
- The JSON and SARIF results also carry the other places as related locations, the first ten in the order of their paths and lines; code scanning shows them with the alert. The console report draws the places of each group itself, as above. The GitHub, GitLab and Markdown reports show the message, which names them.
- A copy in a test, a generated file, a file of an excluded path, a path under the check’s own
excludeor a file that does not compile is not reported, and makes nothing elsewhere reported either. - A suppression comment does not silence a result. The check’s
excludeor a highermin_tokensdoes. - In the project judgement (
assay gate) the regions are whole-project results like those of the other cross-file checks: listed,knownornewagainst the baseline, never failing it.assay baseline update --addrecords them, andbaseline updateand the gate remove the entry of a region that is no longer found.
Which files are read
Section titled “Which files are read”The Dart files under the lib/ directory of each package of the project (of the project itself where it has no pubspec), nested packages among them, that assay judges. These are not read:
- files in an excluded path of
assay.excludeoranalyzer.exclude(the default**/*.g.dart,**/*.freezed.dart,**/*.gen.dart,**/*.mocks.dartand the generated localization files among them); - files in a path the check’s own
excludecovers; - files of a package whose pubspec cannot be read as one that names the package;
- files that look generated: their comments before the first token say
GENERATED CODE,DO NOT EDIT,DO NOT MODIFY,generated byor@generated, in any case. A doc comment counts, since some generators write their header as one. This takes out FlutterFire’sfirebase_options.dart(// File generated by FlutterFire CLI.) and the files of protocol buffers, routers and asset tables; - tests, programs under
bin/, tools, and files outside a package’slib/(anexample/lib/is read only whereexample/is a package of its own).
A file written by hand that holds a section of generated code is read, without that section (How a copy is found).
Configuration
Section titled “Configuration”Under the assay: key of the project’s root analysis_options.yaml:
| Key | Default | Effect |
|---|---|---|
assay.cross_file.duplicated_code.enabled |
true |
false switches the check off; the short form duplicated_code: false means the same. Switched off, the pass reads no token and takes as long as without the check. |
assay.cross_file.duplicated_code.exclude |
[] |
Path globs whose files the check does not read at all. |
assay.cross_file.duplicated_code.min_tokens |
100 |
The fewest tokens a block has; a whole number, 20 or more. |
assay.cross_file.duplicated_code.min_lines |
10 |
The fewest lines each copy of a block spans, from its first token to its last; a whole number, 1 or more. |
assay: cross_file: duplicated_code: exclude: ["lib/legacy/**"] min_tokens: 150For this check, exclude takes a file out of the detection altogether, where for the other cross-file checks it only places no result there. So a legacy copy kept on purpose is neither reported nor makes the live code it copies reported.
Every key is a configuration change at the gate: an agent that raises min_tokens or switches the check off is shown it at turn end. The ceilings on duplicated code are under assay.gate.duplication (In the gate).
The turn end
Section titled “The turn end”At turn end the agent is handed only the duplication the session made. A region is handed over only where it holds a new code line: a code line the session wrote, found by a line diff of the file with what it held when the session was first seen, as the new lines of coverage are (Coverage in the gate). A new file has every line new.
- The region of a copy the session made is handed over, in a new file or in one that was there, and so is the region of a copy the session wrote code into.
- A region of a file the session did not touch never is.
- Copy a screen once more, or copy the middle of two copies into a third file, and only the region of the new copy is handed over, once, naming the copies it repeats:
Whole project (1 new) - in a file the change touched or in another; they do not fail the gatelib/screens/tally.dart 5:3 duplicated_code: This block of 19 lines is duplicated at lib/screens/detail.dart:8-26 and lib/screens/home.dart:8-26. fix: Move the shared code into one function, widget or class, and use it from each place.Every region that holds no new code line stood before, whatever the session did around it. That holds also where the session moved the first line of a standing region, by which the baseline knows it: by splitting a copy in two, by copying a whole file that holds a standing copy, or by putting a copy above a standing one in its file. Only the region holding the code the session wrote is handed over. A comment or a blank line written inside a copy is no code line and hands nothing over.
The JSON result marks a region that holds no new code line as standing (inMark) on every change, since a mark, since a commit (--base) or against the commit checked out, so a reader of the result in CI tells them apart the same way.
Duplication never blocks the turn end and never fails the gate there: the agent plugin never passes --duplication.
Code lines and density
Section titled “Code lines and density”A code line is a line a token lies on. A comment line, a doc comment or a blank line is not; each line of a multi-line string is; the directives count. The duplication density of a set of files is their duplicated code lines (the code lines inside regions) over their code lines.
A density is shown rounded up to one decimal, so that a share above a ceiling never shows as the ceiling met: 101 of 2,000 lines are 5.1%, 1 of 2,000 is 0.1%, and only no duplicated line at all is 0.0%.
In the metric report
Section titled “In the metric report”Where duplicated_code is on, assay metrics shows the duplication density of the files it measures that the detector reads, and for each its code lines, duplicated lines and regions, with the thresholds and the number of blocks. Every file measured has its code lines, whether the check is on or not. There is no option: the box is there while the check is on, and absent when it is switched off (assay.cross_file.duplicated_code: false). It judges nothing, and the exit code does not depend on it. Duplicated code on the page of assay metrics shows the box and each form of the report.
metrics runs no cross-file pass; it reads the tokens itself. The detection always runs over every file the check reads, whatever paths metrics is given, since a copy has two ends: a file of lib/feature/ whose code is copied in lib/screens/ has those lines duplicated though lib/screens/ was not asked for. The files outside the paths are only parsed for this, in each file’s own language version. So one that parses but does not compile still counts, while the whole-project run and the cross-file check leave out every file that does not compile; one that does not parse counts nowhere.
Where no file asked for is one the detector reads, as with assay metrics test/, nothing is detected, and the box says that no file under lib/ was measured.
In the gate
Section titled “In the gate”assay gate --duplication judges the gate conditions under assay.gate.duplication, ceilings on the duplicated code (Gate conditions). No preset writes one.
assay: gate: duplication: max_on_new_lines: 3 # percent of the new code lines of a change max_overall: 5 # percent of all code lines the check reads small_change: 20 # a change of fewer new code lines is not judged on themmax_overallcounts every file the check reads (Which files are read): the duplication density of the project, in both judgements.max_on_new_linescounts the new code lines of the changed files the check reads, and the duplicated ones among them. The new lines are found as for coverage (Coverage in the gate): a new file has every line new, a file git only moved (git mv, or a rename in a commit since the base) has none, and a copy elsewhere of a new line counts wherever it is. A changed test, a file ofbin/ortool/and an excluded file count nothing. Only a change judges it.small_change: a change with fewer new code lines than this (20 unless written) is not judged on its new lines. It is apart from thesmall_changeof coverage.
A ceiling is a percent from 0 to 100, whole or not, and no rounding decides: 50 of 1000 lines (5.0%) pass a ceiling of 5, and 51 fail it. The share shown is rounded up, to as many decimals as its ceiling has and at least one, so it never shows on the other side of its ceiling: 58 of 1150 lines (5.04%) show as 5.1% beside a ceiling of 5.
With --duplication, a condition written and duplicated_code on, the gate on a change always runs the cross-file checks, even for a change of a README alone, so that the density of the whole project is measured. In CI that pass is the whole cost of the flag. Without a condition, or with the check off, the flag runs nothing more, and shows the duplication where the pass ran.
A condition is listed as not judged, and fails nothing, for the first of these that applies:
- the gate was not asked: without
--duplication, as at turn end, every condition is listed so and the verdict is what it would be without them; duplicated_codeis switched off (assay.cross_file.duplicated_code.enabled: false); a note says that--duplicationthen measures nothing;- the cross-file pass, or the check, failed;
- for
max_on_new_lines, the project judgement, which judges no change; - the change has no new code line, or no file the check reads has a code line;
- the change is a small change.
A failed condition fails the gate, exit code 1, with gate_condition in failedBecause. Under a configuration error nothing is judged and no condition is listed.
The console report lists the conditions in a box above the verdict, those on coverage first, with a row of the duplicated code. The Next: row of the verdict says how far to lower the duplication:
╭─ Gate conditions ───────────────────────────────────────────────── 2 failed ─╮│ Condition Share Threshold Status ││ ────────────────────────────────────────────────────── ││ duplication on the new lines 3.0% most 2.5% failed ││ duplication overall 5.7% most 5% failed ││ ││ Duplication 57 of 1000 code lines duplicated (5.7%), 12 of 400 new ones ││ (3.0%), in blocks of at least 100 tokens and 10 lines │╰──────────────────────────────────────────────────────────────────────────────╯
╭─ ✗ FAIL ─────────────────────────────────────────────────────────────────────╮│ 0 blocking · 5 advisory · 5 of 5 files ││ → Next: lower the duplication of the new lines to 2.5% (2 fewer duplicated ││ lines) and lower the duplication of the project to 5% (7 fewer duplicated ││ lines), then run `assay gate --scope changed --duplication` again. │╰──────────────────────────────────────────────────────────────────────────────╯The other reporters:
- JSON: each condition in
conditions[], as a coverage condition is held, withmetric: duplication, its ceiling inmostandleast: null(a coverage condition hasmost: null). With--duplication, where the check ran, the fieldduplication, written asmetrics.duplicationis: every file the check read, by its path, withnewLines(the new code lines and the duplicated ones) and, for each changed file,newCodeLinesandnewDuplicatedLines. --reporter githubwrites a failed condition as anerrorof the run (duplication overall is 5.7%, above the 5% the condition allows: lower the duplication of the project to 5% (7 fewer duplicated lines).).--reporter markdown:<file>lists it in the table of the conditions,at most 5%in its column Threshold, with the line of the duplicated code below.
The pull request job passes --duplication beside --coverage.
How a copy is found
Section titled “How a copy is found”The detector reads the analyzer’s own token stream of each file, the one the analysis already holds, so no file is read twice. A comment is no token. Each token is then normalised:
- Every string literal is one token, each part of an interpolated one too:
Text('Save')andText('Cancel')are the same. Every number is one token:SizedBox(height: 8)andSizedBox(height: 12)are the same. - A trailing comma, the directives (
library,import,export,part,part of, with their annotations), the script tag and a token the parser made up where the code is incomplete are left out. Two files that import the same thirty libraries are no copy. - A section of generated code is left out: from a comment that begins with
BEGIN GENERATEDto one that begins withEND GENERATED, in any case, as the Flutter framework marks the code it generates into a file written by hand (// BEGIN GENERATED TOKEN PROPERTIES - Chip). It stands as one token no other place has, so no copy is found across it. Its lines are still code lines, never duplicated ones. A section that is not ended runs to the end of the file. - Names, keywords (
constandnewamong them), operators and punctuation stay as written. Names are kept on purpose: Flutter’s widget trees share their shape, and trees of different widgets that look alike are no copies (Defaults).
A duplicated block is a run of at least min_tokens such tokens found at two or more places that do not overlap, each place spanning at least min_lines lines. Two fixed floors keep out runs that are long but no copy:
- At least 20 distinct tokens, against lists of data (
[0, 1, 2, …]is two distinct tokens) and long runs of the same few widgets. - At least 40 distinct shapes, against code that repeats one short pattern with other names, as two classes with the same fields do in their parameter lists, field lists,
copyWith,==,hashCodeandtoJson. A shape is a run of four tokens with every name read as the same word:final String id;andfinal String title;are one shape. Several such members in a row can still reach 40 and be found.
All the places of one run are the copies of one block: three copies of a widget are one block of three. A region is a maximal run of lines of one file that copies cover, from the first token of its first copy to the last token of the copy that ends last; two copies of the same block are never one region. A region names the other copies of every block it holds, so when a third copy of part of a standing pair is made elsewhere, the pair keeps its regions and each names the new place besides.
Defaults
Section titled “Defaults”- Names are kept and every literal is one token, so widget trees of the same shape with other widgets are no copies, while copies that differ only in their texts and numbers are.
constandneware kept as written. min_tokens100 andmin_lines10.- The two floors, 20 distinct tokens and 40 distinct shapes, and the sections of generated code left out (How a copy is found).
- On under every preset.
Classes of the same fields, such as a theme that mirrors the parameters of its widget, can repeat their parameter lists, copyWith and debugFillProperties over 100 tokens. Where such a region is not worth merging, leave its files out with exclude or raise min_tokens.