dart-decimate 0.0.8 → 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.
@@ -3,7 +3,9 @@ use std::fs;
3
3
  use tempfile::TempDir;
4
4
 
5
5
  use super::*;
6
- use crate::{analyze_symbols, find_dead_code, scan::scan_project};
6
+ use crate::{
7
+ FeatureFlagOptions, analyze_symbols, detect_feature_flags, find_dead_code, scan::scan_project,
8
+ };
7
9
 
8
10
  #[test]
9
11
  fn emits_agent_actionable_dead_file_findings() -> Result<(), Box<dyn std::error::Error>> {
@@ -105,6 +107,107 @@ fn emits_agent_actionable_duplicate_export_findings() -> Result<(), Box<dyn std:
105
107
  Ok(())
106
108
  }
107
109
 
110
+ #[test]
111
+ fn compile_time_feature_flag_severity_depends_on_path_not_name()
112
+ -> Result<(), Box<dyn std::error::Error>> {
113
+ let fixture = tempfile::tempdir()?;
114
+ write(&fixture, "pubspec.yaml", "name: app\n")?;
115
+ write(
116
+ &fixture,
117
+ "lib/main.dart",
118
+ "const variant = bool.fromEnvironment('AB_TEST_VARIANT');\n",
119
+ )?;
120
+ write(
121
+ &fixture,
122
+ "lib/dev_flags.dart",
123
+ "const debugFlag = bool.fromEnvironment('DEBUG_PROD_ONLY');\n",
124
+ )?;
125
+ write(
126
+ &fixture,
127
+ "lib/debug_flags.dart",
128
+ "const e2eFlag = bool.fromEnvironment('E2E_PROD_ONLY');\n",
129
+ )?;
130
+ write(
131
+ &fixture,
132
+ "lib/main_dev.dart",
133
+ "const e2eDevFlag = bool.fromEnvironment('E2E_DEV_ENTRY_ONLY');\n",
134
+ )?;
135
+ write(
136
+ &fixture,
137
+ "test/flag_test.dart",
138
+ "const debug = bool.fromEnvironment('DEBUG_TEST_ONLY');\n",
139
+ )?;
140
+ let project = scan_project(fixture.path())?;
141
+ let feature_flags = detect_feature_flags(&project, &FeatureFlagOptions::default())?;
142
+
143
+ let report = build_json_report(
144
+ &project,
145
+ &AnalysisResults {
146
+ command: ReportCommand::Check,
147
+ dead_code: None,
148
+ symbols: None,
149
+ cycles: Vec::new(),
150
+ re_export_cycles: Vec::new(),
151
+ boundary_violations: Vec::new(),
152
+ boundary_coverage: Vec::new(),
153
+ boundary_call_violations: Vec::new(),
154
+ policy_violations: Vec::new(),
155
+ dependency_hygiene: None,
156
+ duplicates: None,
157
+ health: None,
158
+ feature_flags: Some(feature_flags),
159
+ security: None,
160
+ routes: None,
161
+ widgets: None,
162
+ file_scope: None,
163
+ require_suppression_reasons: false,
164
+ },
165
+ );
166
+
167
+ assert_eq!(
168
+ report
169
+ .findings
170
+ .iter()
171
+ .find(|finding| finding.path == "lib/main.dart")
172
+ .map(|finding| finding.severity),
173
+ Some(Severity::Error)
174
+ );
175
+ assert_eq!(
176
+ report
177
+ .findings
178
+ .iter()
179
+ .find(|finding| finding.path == "lib/dev_flags.dart")
180
+ .map(|finding| finding.severity),
181
+ Some(Severity::Error)
182
+ );
183
+ assert_eq!(
184
+ report
185
+ .findings
186
+ .iter()
187
+ .find(|finding| finding.path == "lib/debug_flags.dart")
188
+ .map(|finding| finding.severity),
189
+ Some(Severity::Error)
190
+ );
191
+ assert_eq!(
192
+ report
193
+ .findings
194
+ .iter()
195
+ .find(|finding| finding.path == "lib/main_dev.dart")
196
+ .map(|finding| finding.severity),
197
+ Some(Severity::Warning)
198
+ );
199
+ assert_eq!(
200
+ report
201
+ .findings
202
+ .iter()
203
+ .find(|finding| finding.path == "test/flag_test.dart")
204
+ .map(|finding| finding.severity),
205
+ Some(Severity::Warning)
206
+ );
207
+
208
+ Ok(())
209
+ }
210
+
108
211
  fn write(fixture: &TempDir, path: &str, source: &str) -> Result<(), std::io::Error> {
109
212
  let path = fixture.path().join(path);
110
213
  if let Some(parent) = path.parent() {
@@ -9,14 +9,18 @@ use crate::graph::{GraphError, normalize_path};
9
9
 
10
10
  #[derive(Debug, Clone, Default)]
11
11
  pub(crate) struct PackageMap {
12
- by_name: BTreeMap<String, PackageRoot>,
12
+ by_name: BTreeMap<String, Vec<PackageRoot>>,
13
+ by_owner_dependency: BTreeMap<PathBuf, BTreeMap<String, PackageRoot>>,
14
+ uses_package_config: bool,
13
15
  }
14
16
 
15
17
  #[derive(Debug, Clone, PartialEq, Eq)]
16
18
  struct PackageRoot {
19
+ name: String,
17
20
  root: PathBuf,
18
21
  package_path: PathBuf,
19
22
  local: bool,
23
+ from_package_config: bool,
20
24
  }
21
25
 
22
26
  #[derive(Debug, Clone, PartialEq, Eq)]
@@ -28,11 +32,11 @@ pub(crate) struct PackageResolution {
28
32
  impl PackageMap {
29
33
  pub(crate) fn discover(root: &Path) -> Result<Self, GraphError> {
30
34
  if let Some(config) = PackageConfigFile::read(root)? {
31
- return Ok(Self::from_package_config(
32
- root,
33
- &config.config_dir,
34
- &config.config,
35
- ));
35
+ let mut packages = Self::from_package_config(root, &config.config_dir, &config.config);
36
+ let mut visited = BTreeSet::new();
37
+ packages.discover_pubspec(root, &mut visited)?;
38
+ packages.discover_nested_pubspecs(root, &mut visited)?;
39
+ return Ok(packages);
36
40
  }
37
41
 
38
42
  let mut packages = Self::default();
@@ -49,16 +53,70 @@ impl PackageMap {
49
53
  pub(crate) fn local_roots(&self) -> BTreeSet<PathBuf> {
50
54
  self.by_name
51
55
  .values()
56
+ .flatten()
52
57
  .filter(|package| package.local)
53
58
  .map(|package| package.root.clone())
54
59
  .collect()
55
60
  }
56
61
 
57
- pub(crate) fn resolve(&self, package: &str, path: &str) -> Option<PackageResolution> {
58
- self.by_name.get(package).map(|root| PackageResolution {
59
- path: normalize_path(&root.package_path.join(path)),
60
- local: root.local,
61
- })
62
+ pub(crate) fn resolve_from(
63
+ &self,
64
+ from_path: &Path,
65
+ package: &str,
66
+ path: &str,
67
+ ) -> Option<PackageResolution> {
68
+ let roots = self.by_name.get(package)?;
69
+ let owner_package = self.owner_package(from_path);
70
+ let owner_root = owner_package.map(|package| package.root.as_path());
71
+ if let Some(owner_package) = owner_package {
72
+ if owner_package.name == package {
73
+ return Some(package_resolution(owner_package, path));
74
+ }
75
+ }
76
+ let configured_root = roots.iter().find(|root| root.from_package_config);
77
+ if owner_package.is_some_and(|package| package.from_package_config) {
78
+ if let Some(root) = configured_root {
79
+ return Some(package_resolution(root, path));
80
+ }
81
+ }
82
+ if let Some(owner_root) = owner_root {
83
+ if let Some(root) = self
84
+ .by_owner_dependency
85
+ .get(owner_root)
86
+ .and_then(|dependencies| dependencies.get(package))
87
+ {
88
+ return Some(package_resolution(root, path));
89
+ }
90
+ }
91
+ if let Some(owner_package) = owner_package {
92
+ if owner_package.from_package_config || self.uses_package_config {
93
+ return None;
94
+ }
95
+ }
96
+ if let Some(root) = configured_root {
97
+ return Some(package_resolution(root, path));
98
+ }
99
+ if roots.len() == 1 {
100
+ return roots.first().map(|root| package_resolution(root, path));
101
+ }
102
+
103
+ owner_root
104
+ .and_then(|owner_root| {
105
+ roots
106
+ .iter()
107
+ .filter(|candidate| candidate.root.starts_with(owner_root))
108
+ .min_by_key(|candidate| candidate.root.components().count())
109
+ })
110
+ .or_else(|| roots.first())
111
+ .map(|root| package_resolution(root, path))
112
+ }
113
+
114
+ fn owner_package(&self, path: &Path) -> Option<&PackageRoot> {
115
+ self.by_name
116
+ .values()
117
+ .flatten()
118
+ .filter(|package| path.starts_with(&package.root))
119
+ .max_by_key(|package| package.root.components().count())
62
120
  }
63
121
 
64
122
  fn from_package_config(root: &Path, config_dir: &Path, config: &PackageConfig) -> Self {
@@ -75,16 +133,22 @@ impl PackageMap {
75
133
  is_local_package_config_root(root, config_root, root_uri, &package_root);
76
134
  Some((
77
135
  package.name.clone(),
78
- PackageRoot {
136
+ vec![PackageRoot {
137
+ name: package.name.clone(),
79
138
  root: package_root,
80
139
  package_path,
81
140
  local,
82
- },
141
+ from_package_config: true,
142
+ }],
83
143
  ))
84
144
  })
85
145
  .collect();
86
146
 
87
- Self { by_name }
147
+ Self {
148
+ by_name,
149
+ by_owner_dependency: BTreeMap::new(),
150
+ uses_package_config: true,
151
+ }
88
152
  }
89
153
 
90
154
  fn discover_pubspec(
@@ -102,7 +166,7 @@ impl PackageMap {
102
166
  };
103
167
 
104
168
  if let Some(name) = pubspec.name {
105
- self.insert(name, package_root.clone(), PathBuf::from("lib"));
169
+ self.insert(name, &package_root, PathBuf::from("lib"));
106
170
  }
107
171
 
108
172
  for dependency in pubspec.path_dependencies {
@@ -110,11 +174,15 @@ impl PackageMap {
110
174
  if !dependency_root.join("pubspec.yaml").is_file() {
111
175
  continue;
112
176
  }
113
- self.insert(
114
- dependency.name,
115
- dependency_root.clone(),
177
+ let package = self.insert(
178
+ dependency.name.clone(),
179
+ &dependency_root,
116
180
  PathBuf::from("lib"),
117
181
  );
182
+ self.by_owner_dependency
183
+ .entry(package_root.clone())
184
+ .or_default()
185
+ .insert(dependency.name, package);
118
186
  self.discover_pubspec(&dependency_root, visited)?;
119
187
  }
120
188
 
@@ -157,7 +225,7 @@ impl PackageMap {
157
225
  && path.file_name().is_some_and(|name| name == "pubspec.yaml")
158
226
  {
159
227
  if let Some(package_root) = path.parent() {
160
- self.discover_pubspec(package_root, visited)?;
228
+ self.discover_optional_pubspec(package_root, visited)?;
161
229
  }
162
230
  }
163
231
  }
@@ -165,18 +233,60 @@ impl PackageMap {
165
233
  Ok(())
166
234
  }
167
235
 
168
- fn insert(&mut self, name: String, root: PathBuf, package_uri: PathBuf) {
169
- self.by_name.insert(
236
+ fn discover_optional_pubspec(
237
+ &mut self,
238
+ package_root: &Path,
239
+ visited: &mut BTreeSet<PathBuf>,
240
+ ) -> Result<(), GraphError> {
241
+ let previous_packages = self.clone();
242
+ let previous_visited = visited.clone();
243
+ match self.discover_pubspec(package_root, visited) {
244
+ Ok(()) => Ok(()),
245
+ Err(error) if is_optional_pubspec_error(&error) => {
246
+ *self = previous_packages;
247
+ *visited = previous_visited;
248
+ Ok(())
249
+ }
250
+ Err(error) => Err(error),
251
+ }
252
+ }
253
+
254
+ fn insert(&mut self, name: String, root: &Path, package_uri: PathBuf) -> PackageRoot {
255
+ let packages = self.by_name.entry(name.clone()).or_default();
256
+ let root = normalize_path(root);
257
+ if let Some(package) = packages.iter().find(|package| package.root == root) {
258
+ return package.clone();
259
+ }
260
+ let package = PackageRoot {
170
261
  name,
171
- PackageRoot {
172
- package_path: normalize_path(&root.join(package_uri)),
173
- root,
174
- local: true,
175
- },
176
- );
262
+ package_path: normalize_path(&root.join(package_uri)),
263
+ root,
264
+ local: true,
265
+ from_package_config: false,
266
+ };
267
+ packages.push(package.clone());
268
+ packages.sort_by(|left, right| left.root.cmp(&right.root));
269
+ package
177
270
  }
178
271
  }
179
272
 
273
+ fn package_resolution(root: &PackageRoot, path: &str) -> PackageResolution {
274
+ PackageResolution {
275
+ path: normalize_path(&root.package_path.join(path)),
276
+ local: root.local,
277
+ }
278
+ }
279
+
280
+ fn is_optional_pubspec_error(error: &GraphError) -> bool {
281
+ matches!(
282
+ error,
283
+ GraphError::ReadPubspec { .. }
284
+ | GraphError::ParsePubspec { .. }
285
+ | GraphError::WorkspacePattern { .. }
286
+ | GraphError::WorkspaceGlob { .. }
287
+ )
288
+ }
289
+
180
290
  #[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
181
291
  struct PackageConfig {
182
292
  #[serde(default)]
@@ -363,9 +473,17 @@ fn path_dependencies(value: &Value, overrides: Option<&Value>) -> Vec<PathDepend
363
473
  .filter_map(|section| mapping_field(value, section))
364
474
  .flat_map(path_dependencies_from_mapping)
365
475
  .collect::<Vec<_>>();
476
+
366
477
  let override_source = overrides
367
478
  .filter(|value| has_top_level_field(value, "dependency_overrides"))
368
479
  .unwrap_or(value);
480
+ if let Some(overrides) = mapping_field(override_source, "dependency_overrides") {
481
+ let override_names = overrides
482
+ .keys()
483
+ .filter_map(Value::as_str)
484
+ .collect::<BTreeSet<_>>();
485
+ dependencies.retain(|dependency| !override_names.contains(dependency.name.as_str()));
486
+ }
369
487
  dependencies.extend(
370
488
  mapping_field(override_source, "dependency_overrides")
371
489
  .into_iter()
@@ -481,7 +599,81 @@ mod tests {
481
599
  let packages = PackageMap::discover(fixture.path())?;
482
600
 
483
601
  assert_eq!(packages.names(), vec!["example", "hydrated_bloc"]);
484
- assert!(packages.resolve("bloc", "bloc.dart").is_none());
602
+ assert!(
603
+ packages
604
+ .resolve_from(
605
+ &fixture.path().join("lib/hydrated_bloc.dart"),
606
+ "bloc",
607
+ "bloc.dart"
608
+ )
609
+ .is_none()
610
+ );
611
+
612
+ Ok(())
613
+ }
614
+
615
+ #[test]
616
+ fn optional_nested_pubspec_parse_failure_does_not_poison_later_strict_discovery()
617
+ -> Result<(), Box<dyn std::error::Error>> {
618
+ let fixture = TempDir::new()?;
619
+ write(
620
+ &fixture,
621
+ "app/pubspec.yaml",
622
+ "name: app\ndependencies:\n bad:\n path: ../scratch/bad\n",
623
+ )?;
624
+ write(&fixture, "scratch/bad/pubspec.yaml", "name: [\n")?;
625
+
626
+ let mut packages = PackageMap::default();
627
+ let mut visited = BTreeSet::new();
628
+ packages.discover_nested_pubspecs(&fixture.path().join("scratch"), &mut visited)?;
629
+
630
+ match packages.discover_pubspec(&fixture.path().join("app"), &mut visited) {
631
+ Err(GraphError::ParsePubspec { path, .. }) => {
632
+ assert_eq!(path, fixture.path().join("scratch/bad/pubspec.yaml"));
633
+ }
634
+ other => panic!("expected strict parse error, got {other:?}"),
635
+ }
636
+
637
+ Ok(())
638
+ }
639
+
640
+ #[test]
641
+ fn optional_nested_pubspec_workspace_errors_are_ignored_without_partial_owner()
642
+ -> Result<(), Box<dyn std::error::Error>> {
643
+ let fixture = TempDir::new()?;
644
+ write(&fixture, "pubspec.yaml", "name: app\n")?;
645
+ write(
646
+ &fixture,
647
+ "fixtures/bad/pubspec.yaml",
648
+ "name: bad\nworkspace:\n - '[bad'\n",
649
+ )?;
650
+
651
+ let packages = PackageMap::discover(fixture.path())?;
652
+
653
+ assert_eq!(packages.names(), vec!["app"]);
654
+
655
+ Ok(())
656
+ }
657
+
658
+ #[test]
659
+ fn declared_path_dependency_workspace_errors_stay_strict()
660
+ -> Result<(), Box<dyn std::error::Error>> {
661
+ let fixture = TempDir::new()?;
662
+ write(
663
+ &fixture,
664
+ "pubspec.yaml",
665
+ "name: app\ndependencies:\n bad:\n path: fixtures/bad\n",
666
+ )?;
667
+ write(
668
+ &fixture,
669
+ "fixtures/bad/pubspec.yaml",
670
+ "name: bad\nworkspace:\n - '[bad'\n",
671
+ )?;
672
+
673
+ match PackageMap::discover(fixture.path()) {
674
+ Err(GraphError::WorkspacePattern { .. }) => {}
675
+ other => panic!("expected strict workspace pattern error, got {other:?}"),
676
+ }
485
677
 
486
678
  Ok(())
487
679
  }
package/src/routes.rs CHANGED
@@ -349,6 +349,11 @@ final router = GoRouter(routes: [
349
349
  .map(|(path, source)| extract_dart_source(root.join(path), source))
350
350
  .collect::<Result<Vec<_>, _>>()?;
351
351
  let graph = crate::build_module_graph(&root, &files)?;
352
- Ok(ScannedProject { root, files, graph })
352
+ Ok(ScannedProject {
353
+ scan_roots: vec![root.clone()],
354
+ root,
355
+ files,
356
+ graph,
357
+ })
353
358
  }
354
359
  }
package/src/scan.rs CHANGED
@@ -17,8 +17,10 @@ use crate::{
17
17
  /// Parsed Dart files plus their resolved module graph.
18
18
  #[derive(Debug)]
19
19
  pub struct ScannedProject {
20
- /// Root directory used for discovery and dependency resolution.
20
+ /// Primary root used for dependency resolution and root-relative output.
21
21
  pub root: PathBuf,
22
+ /// Local roots included in discovery, sorted for deterministic entrypoint analysis.
23
+ pub scan_roots: Vec<PathBuf>,
22
24
  /// Extracted Dart files, sorted by path for deterministic output.
23
25
  pub files: Vec<DartFile>,
24
26
  /// Directed graph built from the extracted files.
@@ -115,7 +117,8 @@ pub enum ScanError {
115
117
  Graph(#[from] GraphError),
116
118
  }
117
119
 
118
- /// Discover, parse, and graph all `.dart` files under `root`.
120
+ /// Discover, parse, and graph all `.dart` files under `root` and discovered
121
+ /// local package roots.
119
122
  ///
120
123
  /// Parsing is parallelized with Rayon after a deterministic filesystem walk.
121
124
  ///
@@ -126,7 +129,8 @@ pub fn scan_project(root: impl AsRef<Path>) -> Result<ScannedProject, ScanError>
126
129
  scan_project_with_options(root, &ScanOptions::default())
127
130
  }
128
131
 
129
- /// Discover, parse, and graph all non-ignored `.dart` files under `root`.
132
+ /// Discover, parse, and graph all non-ignored `.dart` files under `root` and
133
+ /// discovered local package roots.
130
134
  ///
131
135
  /// Parsing is parallelized with Rayon after a deterministic filesystem walk.
132
136
  ///
@@ -139,9 +143,10 @@ pub fn scan_project_with_options(
139
143
  ) -> Result<ScannedProject, ScanError> {
140
144
  let root = normalize_scan_root(root.as_ref())?;
141
145
  let ignore_matcher = IgnoreMatcher::new(&options.ignore_patterns)?;
146
+ let package_map = PackageMap::discover(&root)?;
142
147
  let mut scan_roots = BTreeSet::new();
143
148
  scan_roots.insert(root.clone());
144
- scan_roots.extend(PackageMap::discover(&root)?.local_roots());
149
+ scan_roots.extend(package_map.local_roots());
145
150
 
146
151
  let mut paths = BTreeSet::new();
147
152
  for scan_root in &scan_roots {
@@ -163,7 +168,12 @@ pub fn scan_project_with_options(
163
168
  },
164
169
  )?;
165
170
 
166
- Ok(ScannedProject { root, files, graph })
171
+ Ok(ScannedProject {
172
+ root,
173
+ scan_roots: scan_roots.into_iter().collect(),
174
+ files,
175
+ graph,
176
+ })
167
177
  }
168
178
 
169
179
  fn normalize_scan_root(root: &Path) -> Result<PathBuf, ScanError> {