dart-decimate 0.0.9 → 0.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Cargo.lock CHANGED
@@ -92,7 +92,7 @@ checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
92
92
 
93
93
  [[package]]
94
94
  name = "dart-decimate"
95
- version = "0.0.9"
95
+ version = "0.0.10"
96
96
  dependencies = [
97
97
  "clap",
98
98
  "glob",
package/Cargo.toml CHANGED
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "dart-decimate"
3
- version = "0.0.9"
3
+ version = "0.0.10"
4
4
  edition = "2024"
5
5
  rust-version = "1.85"
6
6
  description = "Rust-native codebase intelligence for Dart and Flutter module graphs."
package/README.md CHANGED
@@ -91,7 +91,7 @@ Add this to `package.json` if you want a short project command:
91
91
  "dart-decimate": "dart-decimate json ."
92
92
  },
93
93
  "devDependencies": {
94
- "dart-decimate": "^0.0.9"
94
+ "dart-decimate": "^0.0.10"
95
95
  }
96
96
  }
97
97
  ```
@@ -204,6 +204,17 @@ Dart Decimate finds:
204
204
  - missing entry points
205
205
  - stale `dart-decimate-ignore` comments
206
206
 
207
+ Default entry points are evaluated across the root and discovered local package
208
+ roots. They include public `lib/` Dart files outside `lib/src/`, `lib/main.dart`,
209
+ direct `bin/` scripts, and, outside production mode, direct `test/`,
210
+ `integration_test/`, `test_driver/`, `tool/`, `scripts/`, and `pigeon/`
211
+ scripts. Generated Dart companions, Flutter l10n outputs, and FlutterFire
212
+ options are protected from dead-file cleanup; generated-only cycles are also
213
+ suppressed.
214
+
215
+ Unused-symbol checks count references from non-raw Dart string interpolation;
216
+ raw strings and escaped dollars stay literal.
217
+
207
218
  Useful commands:
208
219
 
209
220
  ```bash
@@ -247,6 +258,8 @@ Dart Decimate finds exact and semantic clone groups. Each clone group gets a sta
247
258
  fingerprint like `dup:abc12345`, so agents can trace it before touching code.
248
259
  Clone windows must meet both line and token thresholds; sparse duplicated blocks
249
260
  can span more than `--min-lines`, and `line_count` reports the actual match.
261
+ Copied local Pub packages with the same package name and identical relative
262
+ matches are ignored.
250
263
 
251
264
  Useful commands:
252
265
 
@@ -313,6 +326,15 @@ Dart Decimate finds:
313
326
  - imports into another package's private `lib/src`
314
327
  - duplicate public API exports
315
328
 
329
+ Dart Decimate follows Pub package ownership when resolving `package:` imports,
330
+ using `.dart_tool/package_config.json` when present while keeping same-package
331
+ imports and owner-local path dependencies local. Workspace members and copied
332
+ nested packages with the same package name are resolved by owner. Non-Dart
333
+ tooling references in Flutter config files, including launcher and splash
334
+ config, workflow files, Makefiles, and `tool/` scripts can count as dependency
335
+ usage. Known generator-internal imports from generated Dart, such as
336
+ `package:slang/generated.dart`, are not reported as unlisted dependencies.
337
+
316
338
  Useful commands:
317
339
 
318
340
  ```bash
@@ -349,6 +371,13 @@ Dart Decimate finds candidates for:
349
371
  - Firebase client API keys in `FirebaseOptions`
350
372
  - plain local storage of secret-like material
351
373
 
374
+ Firebase client API keys are warning-level by default because FlutterFire
375
+ generates client config. To make them fail a gate, set
376
+ `"dart-decimate/security-firebase-api-key" = "error"` in `[rules]`. Common
377
+ authentication copy such as password reset and password requirement text is
378
+ filtered before reporting hardcoded-secret candidates unless it is bound to a
379
+ secret-like name or contains a concrete token-like segment.
380
+
352
381
  Useful commands:
353
382
 
354
383
  ```bash
@@ -374,6 +403,13 @@ Dart Decimate reports:
374
403
  - findings that already existed
375
404
  - risky changed files
376
405
 
406
+ Compile-time environment feature flags are warning-level only when every
407
+ occurrence is in a non-`lib/` development, tooling, example, or test path, or in
408
+ `lib/main_dev.dart`, `lib/main_debug.dart`, `lib/main_e2e.dart`,
409
+ `lib/main_test.dart`, or `lib/main_driver.dart`. Other `lib/` files, including
410
+ `lib/dev_flags.dart`, services, and screens, remain error-level. SDK/config flag
411
+ calls stay error-level by default.
412
+
377
413
  Useful commands:
378
414
 
379
415
  ```bash
@@ -567,6 +603,7 @@ categories = ["hardcoded-secret", "firebase-api-key", "insecure-transport", "tls
567
603
  unused-files = "error"
568
604
  unused-exports = "warn"
569
605
  security-candidate = "warn"
606
+ "dart-decimate/security-firebase-api-key" = "error"
570
607
  ```
571
608
 
572
609
  ## Full Issue List
@@ -584,62 +621,8 @@ you need the installed binary's exact list.
584
621
 
585
622
  ## CI
586
623
 
587
- Add Dart Decimate to CI so every PR gets the same repo health check:
588
-
589
- ```yaml
590
- - name: Dart Decimate
591
- run: npx --yes dart-decimate json .
592
- ```
593
-
594
- That is the easiest CI command. It checks everything Dart Decimate knows how to
595
- check in one pass.
596
-
597
- For PR-only regression checks, use:
598
-
599
- ```bash
600
- npx --yes dart-decimate audit . --base origin/main --format json --summary --gate new-only
601
- ```
602
-
603
- You can also put the full check in a git hook:
604
-
605
- ```bash
606
- mkdir -p .git/hooks
607
- cat > .git/hooks/pre-commit <<'SH'
608
- #!/usr/bin/env sh
609
- npx --yes dart-decimate json .
610
- SH
611
- chmod +x .git/hooks/pre-commit
612
- ```
613
-
614
- This repository already runs:
615
-
616
- - Rust format, clippy, and tests
617
- - npm package checks
618
- - version sync between `Cargo.toml` and `package.json`
619
- - a PR version-bump gate requiring both package files to increase to an
620
- unpublished version
621
- - release guards that reject reused npm versions or tags on different commits
622
- - migration checks that block previous package, command, schema, and MCP names
623
- - Dependabot and weekly dependency/security audits
624
-
625
- Generate CI templates:
626
-
627
- ```bash
628
- dart-decimate ci-template github --format yaml
629
- dart-decimate ci-template gitlab --format yaml
630
- ```
631
-
632
- Preview review-thread reconciliation without changing GitHub or GitLab:
633
-
634
- ```bash
635
- dart-decimate ci reconcile-review \
636
- --provider github \
637
- --repo owner/repo \
638
- --pr 123 \
639
- --envelope review-github.json \
640
- --dry-run \
641
- --format json
642
- ```
624
+ See [docs/ci.md](docs/ci.md) for CI checks, PR gates, hook setup, CI
625
+ templates, and review-thread reconciliation.
643
626
 
644
627
  ## Scope
645
628
 
@@ -672,7 +655,7 @@ This repository forbids `unsafe_code`.
672
655
 
673
656
  ## Release Flow
674
657
 
675
- Current version: `0.0.9`.
658
+ Current version: `0.0.10`.
676
659
 
677
660
  After the first public release, changes should go through pull requests. Every
678
661
  PR to `main` must bump both `Cargo.toml` and `package.json` above the base
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dart-decimate",
3
- "version": "0.0.9",
3
+ "version": "0.0.10",
4
4
  "description": "Rust-native codebase intelligence for Dart and Flutter module graphs.",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -1,6 +1,7 @@
1
1
  use std::path::Path;
2
2
 
3
3
  use crate::config::{filter_ignored_dependencies, filter_ignored_dependency_overrides};
4
+ use crate::generated::is_generated_dart_path;
4
5
  use crate::output::{AnalysisResults, ReportCommand};
5
6
  use crate::scan::ScannedProject;
6
7
  use crate::{
@@ -419,9 +420,9 @@ where
419
420
  P: AsRef<Path>,
420
421
  {
421
422
  let mut report = find_dead_code(&project.graph, entry_points);
422
- report
423
- .dead_files
424
- .retain(|dead_file| is_project_path(project, &dead_file.path));
423
+ report.dead_files.retain(|dead_file| {
424
+ is_project_path(project, &dead_file.path) && !is_generated_dart_path(&dead_file.path)
425
+ });
425
426
  report
426
427
  .reachable_files
427
428
  .retain(|path| is_project_path(project, path));
@@ -441,6 +442,7 @@ fn detect_project_cycles(project: &ScannedProject) -> Vec<crate::DependencyCycle
441
442
  .files
442
443
  .iter()
443
444
  .any(|path| is_project_path(project, path))
445
+ && !cycle.files.iter().all(|path| is_generated_dart_path(path))
444
446
  })
445
447
  .collect()
446
448
  }
@@ -453,6 +455,7 @@ fn detect_project_re_export_cycles(project: &ScannedProject) -> Vec<crate::ReExp
453
455
  .files
454
456
  .iter()
455
457
  .any(|path| is_project_path(project, path))
458
+ && !cycle.files.iter().all(|path| is_generated_dart_path(path))
456
459
  })
457
460
  .collect()
458
461
  }
@@ -36,16 +36,32 @@ pub(super) fn entry_points_for_dead_code(
36
36
  }
37
37
 
38
38
  fn default_entry_points(project: &ScannedProject, mode: EntryPointMode) -> Vec<PathBuf> {
39
+ let roots = entry_point_roots(project);
39
40
  let mut entries = project
40
41
  .files
41
42
  .iter()
42
- .filter(|file| is_default_entry_point(&project.root, &file.path, mode))
43
+ .filter(|file| {
44
+ roots
45
+ .iter()
46
+ .any(|root| is_default_entry_point(root, &file.path, mode))
47
+ })
43
48
  .map(|file| file.path.clone())
44
49
  .collect::<Vec<_>>();
45
50
  entries.sort();
51
+ entries.dedup();
46
52
  entries
47
53
  }
48
54
 
55
+ fn entry_point_roots(project: &ScannedProject) -> Vec<PathBuf> {
56
+ let mut roots = project.scan_roots.clone();
57
+ if !roots.iter().any(|root| root == &project.root) {
58
+ roots.push(project.root.clone());
59
+ }
60
+ roots.sort();
61
+ roots.dedup();
62
+ roots
63
+ }
64
+
49
65
  fn is_default_entry_point(root: &Path, path: &Path, mode: EntryPointMode) -> bool {
50
66
  let relative = path.strip_prefix(root).unwrap_or(path);
51
67
  is_public_library_entry_point(relative)
@@ -83,7 +99,7 @@ fn is_direct_script_entry_point(path: &Path) -> bool {
83
99
  && path.parent().and_then(Path::file_name).is_some_and(|name| {
84
100
  matches!(
85
101
  name.to_str(),
86
- Some("test" | "integration_test" | "test_driver" | "tool" | "pigeon")
102
+ Some("test" | "integration_test" | "test_driver" | "tool" | "scripts" | "pigeon")
87
103
  )
88
104
  })
89
105
  }
@@ -216,6 +216,7 @@ fn scoped_project(
216
216
  packages.retain(|package| package_in_scope(package, &package_roots, &scope));
217
217
  Ok(ScannedProject {
218
218
  root: project.root,
219
+ scan_roots: project.scan_roots,
219
220
  files: project
220
221
  .files
221
222
  .into_iter()
package/src/cli/tests.rs CHANGED
@@ -566,6 +566,70 @@ fn check_command_treats_public_library_files_as_default_entry_points()
566
566
  Ok(())
567
567
  }
568
568
 
569
+ #[test]
570
+ fn check_command_treats_nested_package_files_as_default_entry_points()
571
+ -> Result<(), Box<dyn std::error::Error>> {
572
+ let fixture = tempfile::tempdir()?;
573
+ write(&fixture, "pubspec.yaml", "name: app\n")?;
574
+ write(&fixture, "lib/main.dart", "void main() {}\n")?;
575
+ write(&fixture, "packages/shared/pubspec.yaml", "name: shared\n")?;
576
+ write(
577
+ &fixture,
578
+ "packages/shared/lib/shared.dart",
579
+ "import 'src/live.dart';\nclass Shared {}\n",
580
+ )?;
581
+ write(
582
+ &fixture,
583
+ "packages/shared/lib/src/live.dart",
584
+ "class Live {}\n",
585
+ )?;
586
+ write(
587
+ &fixture,
588
+ "packages/shared/lib/src/dead.dart",
589
+ "class Dead {}\n",
590
+ )?;
591
+ write(
592
+ &fixture,
593
+ "packages/shared/lib/core/errors/app_error.dart",
594
+ "class AppError {}\n",
595
+ )?;
596
+ write(
597
+ &fixture,
598
+ "packages/shared/bin/tool.dart",
599
+ "void main() {}\n",
600
+ )?;
601
+ write(
602
+ &fixture,
603
+ "packages/shared/scripts/sync.dart",
604
+ "void main() {}\n",
605
+ )?;
606
+ write(
607
+ &fixture,
608
+ "packages/shared/test/shared_test.dart",
609
+ "void main() {}\n",
610
+ )?;
611
+ let mut output = Vec::new();
612
+
613
+ let code = run_from(
614
+ [
615
+ "dart-decimate",
616
+ "check",
617
+ fixture.path().to_str().unwrap_or("."),
618
+ "--format",
619
+ "json",
620
+ ],
621
+ &mut output,
622
+ )?;
623
+
624
+ let json = serde_json::from_slice::<Value>(&output)?;
625
+ let paths = finding_paths(&json, "dart-decimate/dead-file");
626
+ assert_eq!(code, 1);
627
+ assert_eq!(json["summary"]["dead_files"], 1);
628
+ assert_eq!(paths, vec!["packages/shared/lib/src/dead.dart"]);
629
+
630
+ Ok(())
631
+ }
632
+
569
633
  #[test]
570
634
  fn output_alias_commands_run_check_formats() -> Result<(), Box<dyn std::error::Error>> {
571
635
  let fixture = tempfile::tempdir()?;
@@ -597,6 +661,16 @@ fn output_alias_commands_run_check_formats() -> Result<(), Box<dyn std::error::E
597
661
  Ok(())
598
662
  }
599
663
 
664
+ fn finding_paths<'a>(json: &'a Value, rule_id: &str) -> Vec<&'a str> {
665
+ json["findings"]
666
+ .as_array()
667
+ .into_iter()
668
+ .flatten()
669
+ .filter(|finding| finding["rule_id"] == rule_id)
670
+ .filter_map(|finding| finding["path"].as_str())
671
+ .collect()
672
+ }
673
+
600
674
  fn write(fixture: &TempDir, path: &str, source: &str) -> Result<(), std::io::Error> {
601
675
  let path = fixture.path().join(path);
602
676
  if let Some(parent) = path.parent() {
@@ -3,7 +3,10 @@ use std::collections::BTreeMap;
3
3
  use serde::{Deserialize, Serialize};
4
4
 
5
5
  use crate::SecurityCategory;
6
- use crate::output::{Finding, FindingKind, JsonAttackSurfaceEntry, JsonReport, Severity, Verdict};
6
+ use crate::output::{
7
+ Finding, FindingKind, JsonAttackSurfaceEntry, JsonReport, JsonSecurityCandidate, Severity,
8
+ Verdict,
9
+ };
7
10
 
8
11
  use super::rule_aliases::{
9
12
  aliases, known_rule, missing_suppression_reason_aliases, private_type_leak_aliases,
@@ -64,7 +67,7 @@ pub fn apply_rules_to_report(report: &mut JsonReport, rules: &RuleConfig) -> Res
64
67
  if rules.is_empty() {
65
68
  report
66
69
  .findings
67
- .retain(|finding| default_rule_level(finding.kind) != RuleLevel::Off);
70
+ .retain(|finding| default_rule_level(&finding.rule_id, finding.kind) != RuleLevel::Off);
68
71
  recompute_summary(report);
69
72
  return Ok(());
70
73
  }
@@ -93,8 +96,8 @@ pub fn apply_rules_to_report(report: &mut JsonReport, rules: &RuleConfig) -> Res
93
96
  report.feature_flags.retain(|_| {
94
97
  rules.level("dart-decimate/feature-flag", FindingKind::FeatureFlag) != RuleLevel::Off
95
98
  });
96
- report.security_candidates.retain(|candidate| {
97
- rules.level(&candidate.rule_id, FindingKind::SecurityCandidate) != RuleLevel::Off
99
+ report.security_candidates.retain_mut(|candidate| {
100
+ apply_security_candidate_level(candidate, &rules) != RuleLevel::Off
98
101
  });
99
102
  report
100
103
  .attack_surface
@@ -129,12 +132,34 @@ pub enum RuleError {
129
132
  }
130
133
 
131
134
  fn apply_finding_level(finding: &mut Finding, rules: &RuleMatcher) -> RuleLevel {
132
- let level = rules.level(&finding.rule_id, finding.kind);
133
- finding.severity = match level {
134
- RuleLevel::Error => Severity::Error,
135
- RuleLevel::Warn => Severity::Warning,
136
- RuleLevel::Off => finding.severity,
137
- };
135
+ let configured_level = rules.configured_level(&finding.rule_id, finding.kind);
136
+ let level =
137
+ configured_level.unwrap_or_else(|| default_rule_level(&finding.rule_id, finding.kind));
138
+ if configured_level.is_some() || level == RuleLevel::Warn {
139
+ finding.severity = match level {
140
+ RuleLevel::Error => Severity::Error,
141
+ RuleLevel::Warn => Severity::Warning,
142
+ RuleLevel::Off => finding.severity,
143
+ };
144
+ }
145
+ level
146
+ }
147
+
148
+ fn apply_security_candidate_level(
149
+ candidate: &mut JsonSecurityCandidate,
150
+ rules: &RuleMatcher,
151
+ ) -> RuleLevel {
152
+ let configured_level =
153
+ rules.configured_level(&candidate.rule_id, FindingKind::SecurityCandidate);
154
+ let level = configured_level
155
+ .unwrap_or_else(|| default_rule_level(&candidate.rule_id, FindingKind::SecurityCandidate));
156
+ if configured_level.is_some() || level == RuleLevel::Warn {
157
+ candidate.severity = match level {
158
+ RuleLevel::Error => Severity::Error,
159
+ RuleLevel::Warn => Severity::Warning,
160
+ RuleLevel::Off => candidate.severity,
161
+ };
162
+ }
138
163
  level
139
164
  }
140
165
 
@@ -305,22 +330,34 @@ impl<'a> RuleMatcher<'a> {
305
330
  }
306
331
 
307
332
  fn level(&self, rule_id: &str, kind: FindingKind) -> RuleLevel {
333
+ self.configured_level(rule_id, kind)
334
+ .unwrap_or_else(|| default_rule_level(rule_id, kind))
335
+ }
336
+
337
+ fn configured_level(&self, rule_id: &str, kind: FindingKind) -> Option<RuleLevel> {
308
338
  if let Some(level) = self.rules.get(rule_id).copied() {
309
- return level;
339
+ return Some(level);
310
340
  }
311
341
  aliases(rule_id, kind)
312
342
  .into_iter()
313
343
  .find_map(|alias| self.rules.get(alias).copied())
314
- .unwrap_or_else(|| default_rule_level(kind))
315
344
  }
316
345
  }
317
346
 
318
- const fn default_rule_level(kind: FindingKind) -> RuleLevel {
347
+ fn default_rule_level(rule_id: &str, kind: FindingKind) -> RuleLevel {
319
348
  match kind {
320
349
  FindingKind::UnusedDependencyOverride
321
350
  | FindingKind::CodeDuplication
322
351
  | FindingKind::UnusedWidgetParam
323
352
  | FindingKind::UnrenderedWidget => RuleLevel::Warn,
353
+ FindingKind::SecurityCandidate
354
+ if matches!(
355
+ rule_id.as_bytes(),
356
+ b"dart-decimate/security-firebase-api-key"
357
+ ) =>
358
+ {
359
+ RuleLevel::Warn
360
+ }
324
361
  FindingKind::PrivateWidgetClass
325
362
  | FindingKind::WidgetTopLevelFunctionBoundary
326
363
  | FindingKind::MissingContextMountedAfterAwait => RuleLevel::Off,
@@ -118,7 +118,9 @@ fn record_directive(
118
118
  .or_default()
119
119
  .record(&owner.root, file_path);
120
120
 
121
- if !owner.declares_dependency_for_path(&dependency, file_path) {
121
+ if !owner.declares_dependency_for_path(&dependency, file_path)
122
+ && !is_known_generated_internal_import(file_path, specifier)
123
+ {
122
124
  usage
123
125
  .unlisted_by_identity
124
126
  .entry((owner.root.clone(), dependency.clone()))
@@ -135,6 +137,10 @@ fn record_directive(
135
137
  }
136
138
  }
137
139
 
140
+ fn is_known_generated_internal_import(file_path: &Path, specifier: &str) -> bool {
141
+ is_generated_dart_path(file_path) && matches!(specifier, "package:slang/generated.dart")
142
+ }
143
+
138
144
  fn unused_dependencies(
139
145
  packages: &[PubPackage],
140
146
  used_by_package: &PackageUsage,
@@ -474,6 +474,35 @@ dependencies:\n collection: ^1.0.0\n",
474
474
  Ok(())
475
475
  }
476
476
 
477
+ #[test]
478
+ fn reports_unlisted_dependency_from_generated_flutterfire_options()
479
+ -> Result<(), Box<dyn std::error::Error>> {
480
+ let fixture = tempfile::tempdir()?;
481
+ write(&fixture, "pubspec.yaml", "name: app\n")?;
482
+ write(
483
+ &fixture,
484
+ "lib/firebase_options.dart",
485
+ "import 'package:firebase_core/firebase_core.dart';\n\
486
+ class DefaultFirebaseOptions {\n\
487
+ static const FirebaseOptions currentPlatform = FirebaseOptions(apiKey: 'key');\n\
488
+ }\n",
489
+ )?;
490
+ let project = scan_project(fixture.path())?;
491
+
492
+ let report = analyze_dependency_hygiene(&project)?;
493
+
494
+ assert_eq!(report.unlisted_dependencies.len(), 1);
495
+ assert_eq!(report.unlisted_dependencies[0].dependency, "firebase_core");
496
+ assert!(
497
+ report.unlisted_dependencies[0]
498
+ .path
499
+ .ends_with("lib/firebase_options.dart")
500
+ );
501
+ assert_eq!(report.unlisted_dependencies[0].location.line, 1);
502
+
503
+ Ok(())
504
+ }
505
+
477
506
  #[test]
478
507
  fn finds_declared_package_dependencies_for_trace() -> Result<(), Box<dyn std::error::Error>> {
479
508
  let fixture = tempfile::tempdir()?;
@@ -248,6 +248,25 @@ pub fn local_pub_packages(root: &Path) -> Result<Vec<LocalPubPackage>, Dependenc
248
248
  })
249
249
  }
250
250
 
251
+ pub(crate) fn local_pub_package_from_pubspec(
252
+ path: &Path,
253
+ ) -> Result<Option<LocalPubPackage>, DependencyHygieneError> {
254
+ let source = read_pubspec_source(path)?;
255
+ let value = parse_pubspec_value(path, &source)?;
256
+ let Some(name) = string_field(&value, "name") else {
257
+ return Ok(None);
258
+ };
259
+ let root = path
260
+ .parent()
261
+ .map_or_else(|| PathBuf::from("."), normalize_path);
262
+
263
+ Ok(Some(LocalPubPackage {
264
+ name: name.to_owned(),
265
+ root,
266
+ pubspec_path: path.to_path_buf(),
267
+ }))
268
+ }
269
+
251
270
  #[derive(Debug, Clone, PartialEq, Eq)]
252
271
  pub(super) struct PubPackage {
253
272
  name: String,
@@ -26,6 +26,8 @@ fn tooling_files(package_root: &Path) -> Vec<PathBuf> {
26
26
  let mut paths = [
27
27
  "analysis_options.yaml",
28
28
  "build.yaml",
29
+ "flutter_launcher_icons.yaml",
30
+ "flutter_native_splash.yaml",
29
31
  "melos.yaml",
30
32
  "codemagic.yaml",
31
33
  "Makefile",
@@ -0,0 +1,71 @@
1
+ use std::collections::{BTreeMap, BTreeSet};
2
+ use std::path::{Path, PathBuf};
3
+
4
+ use crate::dependencies::{LocalPubPackage, local_pub_package_from_pubspec};
5
+
6
+ use super::CodeClone;
7
+
8
+ pub(super) struct CopiedPackageFilter {
9
+ root: PathBuf,
10
+ package_cache: BTreeMap<PathBuf, Option<LocalPubPackage>>,
11
+ }
12
+
13
+ impl CopiedPackageFilter {
14
+ pub(super) fn new(root: &Path) -> Self {
15
+ Self {
16
+ root: root.to_path_buf(),
17
+ package_cache: BTreeMap::new(),
18
+ }
19
+ }
20
+
21
+ pub(super) fn is_copied_package_clone(&mut self, group: &CodeClone) -> bool {
22
+ if group.instances.len() < 2 {
23
+ return false;
24
+ }
25
+ let mut roots = BTreeSet::new();
26
+ let mut identity = None;
27
+ for instance in &group.instances {
28
+ let Some(package) = self.owning_package(&instance.path) else {
29
+ return false;
30
+ };
31
+ let Ok(relative_path) = instance.path.strip_prefix(&package.root) else {
32
+ return false;
33
+ };
34
+ roots.insert(package.root.clone());
35
+ let current = (
36
+ package.name.clone(),
37
+ relative_path.to_path_buf(),
38
+ instance.start_line,
39
+ instance.end_line,
40
+ );
41
+ if identity.is_none() {
42
+ identity = Some(current);
43
+ } else if identity != Some(current) {
44
+ return false;
45
+ }
46
+ }
47
+ roots.len() > 1
48
+ }
49
+
50
+ fn owning_package(&mut self, path: &Path) -> Option<LocalPubPackage> {
51
+ let mut current = path.parent();
52
+ while let Some(dir) = current {
53
+ if !dir.starts_with(&self.root) {
54
+ break;
55
+ }
56
+ let pubspec_path = dir.join("pubspec.yaml");
57
+ if pubspec_path.is_file() {
58
+ return self
59
+ .package_cache
60
+ .entry(pubspec_path.clone())
61
+ .or_insert_with(|| local_pub_package_from_pubspec(&pubspec_path).ok().flatten())
62
+ .clone();
63
+ }
64
+ if dir == self.root {
65
+ break;
66
+ }
67
+ current = dir.parent();
68
+ }
69
+ None
70
+ }
71
+ }
@@ -108,6 +108,33 @@ fn detects_sparse_duplicate_blocks_that_meet_default_tokens_as_a_whole()
108
108
  Ok(())
109
109
  }
110
110
 
111
+ #[test]
112
+ fn copied_package_filter_ignores_unrelated_malformed_pubspec()
113
+ -> Result<(), Box<dyn std::error::Error>> {
114
+ let fixture = tempfile::tempdir()?;
115
+ write(&fixture, "pubspec.yaml", "name: app\n")?;
116
+ write(&fixture, "fixtures/bad/pubspec.yaml", "name: [\n")?;
117
+ for package in ["copy_a", "copy_b"] {
118
+ write(
119
+ &fixture,
120
+ &format!("{package}/pubspec.yaml"),
121
+ "name: copied_package\n",
122
+ )?;
123
+ write(
124
+ &fixture,
125
+ &format!("{package}/lib/shared.dart"),
126
+ "String sharedHttp() {\n final headers = <String, String>{\n 'accept': 'application/json',\n 'content-type': 'application/json',\n 'x-client': 'function-client',\n };\n final values = ['alpha', 'beta', 'gamma', headers.keys.join('|')];\n final normalized = values.map((value) => value.trim().toLowerCase()).where((value) => value.isNotEmpty).toList();\n return normalized.join(',');\n}\n",
127
+ )?;
128
+ }
129
+ let project = scan_project(fixture.path())?;
130
+
131
+ let report = detect_duplicates(&project, &DuplicateOptions::default())?;
132
+
133
+ assert!(report.clone_groups.is_empty());
134
+
135
+ Ok(())
136
+ }
137
+
111
138
  #[test]
112
139
  fn trace_clone_matches_fingerprint_and_source_line() -> Result<(), Box<dyn std::error::Error>> {
113
140
  let fixture = tempfile::tempdir()?;