dart-decimate 0.0.13 → 0.0.15

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.
@@ -151,7 +151,6 @@ fn decision_surface_output_format(
151
151
  mod tests {
152
152
  use std::cell::RefCell;
153
153
  use std::fs;
154
- use std::process::Command;
155
154
 
156
155
  use tempfile::TempDir;
157
156
 
@@ -217,9 +216,8 @@ mod tests {
217
216
  fixture: &TempDir,
218
217
  args: [&str; N],
219
218
  ) -> Result<(), Box<dyn std::error::Error>> {
220
- let output = Command::new("git")
219
+ let output = crate::git_command::for_repository(fixture.path())
221
220
  .args(args)
222
- .current_dir(fixture.path())
223
221
  .output()?;
224
222
  if output.status.success() {
225
223
  return Ok(());
@@ -1,3 +1,4 @@
1
+ use std::fs;
1
2
  use std::path::{Component, Path, PathBuf};
2
3
 
3
4
  use super::CliError;
@@ -37,13 +38,27 @@ pub(super) fn entry_points_for_dead_code(
37
38
 
38
39
  fn default_entry_points(project: &ScannedProject, mode: EntryPointMode) -> Vec<PathBuf> {
39
40
  let roots = entry_point_roots(project);
41
+ let patrol_suffixes = roots
42
+ .iter()
43
+ .map(|root| (root, patrol_test_suffix(root)))
44
+ .collect::<Vec<_>>();
40
45
  let mut entries = project
41
46
  .files
42
47
  .iter()
43
48
  .filter(|file| {
44
- roots
49
+ patrol_suffixes
45
50
  .iter()
46
- .any(|root| is_default_entry_point(root, &file.path, mode))
51
+ .filter(|(root, _)| file.path.starts_with(root))
52
+ .max_by_key(|(root, _)| root.components().count())
53
+ .is_some_and(|(root, suffix)| {
54
+ is_default_entry_point(
55
+ root,
56
+ &file.path,
57
+ file_has_main(file),
58
+ suffix.as_deref(),
59
+ mode,
60
+ )
61
+ })
47
62
  })
48
63
  .map(|file| file.path.clone())
49
64
  .collect::<Vec<_>>();
@@ -62,13 +77,39 @@ fn entry_point_roots(project: &ScannedProject) -> Vec<PathBuf> {
62
77
  roots
63
78
  }
64
79
 
65
- fn is_default_entry_point(root: &Path, path: &Path, mode: EntryPointMode) -> bool {
66
- let relative = path.strip_prefix(root).unwrap_or(path);
80
+ fn is_default_entry_point(
81
+ root: &Path,
82
+ path: &Path,
83
+ has_main: bool,
84
+ patrol_suffix: Option<&str>,
85
+ mode: EntryPointMode,
86
+ ) -> bool {
87
+ let Ok(relative) = path.strip_prefix(root) else {
88
+ return false;
89
+ };
67
90
  is_public_library_entry_point(relative)
68
91
  || has_path_suffix(relative, &["lib", "main.dart"])
69
92
  || is_bin_entry_point(relative)
70
93
  || (mode == EntryPointMode::All
71
- && (is_direct_script_entry_point(relative) || is_test_entry_point(relative)))
94
+ && (is_direct_script_entry_point(relative)
95
+ || is_test_entry_point(relative)
96
+ || is_test_tree_main(relative, has_main)
97
+ || is_patrol_entry_point(relative, patrol_suffix)))
98
+ }
99
+
100
+ fn file_has_main(file: &crate::DartFile) -> bool {
101
+ crate::extract::has_top_level_function(file, "main")
102
+ }
103
+
104
+ fn patrol_test_suffix(root: &Path) -> Option<String> {
105
+ let source = fs::read_to_string(root.join("pubspec.yaml")).ok()?;
106
+ let pubspec = serde_yaml_ng::from_str::<serde_yaml_ng::Value>(&source).ok()?;
107
+ pubspec
108
+ .get("patrol")?
109
+ .get("test_file_suffix")?
110
+ .as_str()
111
+ .filter(|suffix| !suffix.is_empty())
112
+ .map(str::to_owned)
72
113
  }
73
114
 
74
115
  fn is_public_library_entry_point(path: &Path) -> bool {
@@ -102,19 +143,40 @@ fn is_direct_script_entry_point(path: &Path) -> bool {
102
143
  Some("test" | "integration_test" | "test_driver" | "tool" | "scripts" | "pigeon")
103
144
  )
104
145
  })
146
+ && path.components().count() == 2
105
147
  }
106
148
 
107
149
  fn is_test_entry_point(path: &Path) -> bool {
108
150
  let file_name = path.file_name().and_then(|name| name.to_str());
109
151
  let is_test_file = file_name.is_some_and(|name| name.ends_with("_test.dart"));
110
- is_test_file
111
- && path.components().any(|component| {
112
- matches!(
113
- component,
114
- Component::Normal(name)
115
- if name == "test" || name == "integration_test" || name == "test_driver"
116
- )
117
- })
152
+ is_test_file && starts_in_test_tree(path)
153
+ }
154
+
155
+ fn is_test_tree_main(path: &Path, has_main: bool) -> bool {
156
+ has_main && starts_in_test_tree(path)
157
+ }
158
+
159
+ fn is_patrol_entry_point(path: &Path, patrol_suffix: Option<&str>) -> bool {
160
+ let Some(suffix) = patrol_suffix else {
161
+ return false;
162
+ };
163
+ starts_with_component(path, "integration_test")
164
+ && path
165
+ .file_name()
166
+ .and_then(|name| name.to_str())
167
+ .is_some_and(|name| name.ends_with(suffix))
168
+ }
169
+
170
+ fn starts_in_test_tree(path: &Path) -> bool {
171
+ ["test", "integration_test", "test_driver"]
172
+ .iter()
173
+ .any(|name| starts_with_component(path, name))
174
+ }
175
+
176
+ fn starts_with_component(path: &Path, expected: &str) -> bool {
177
+ path.components()
178
+ .next()
179
+ .is_some_and(|component| matches!(component, Component::Normal(name) if name == expected))
118
180
  }
119
181
 
120
182
  fn has_path_suffix(path: &Path, suffix: &[&str]) -> bool {
@@ -387,9 +387,7 @@ fn is_null_aware_collection_marker(bytes: &[u8], cursor: usize) -> bool {
387
387
  return false;
388
388
  };
389
389
  matches!(previous, b'[' | b'{' | b',' | b':')
390
- || (previous == b'.'
391
- && cursor >= 3
392
- && bytes.get(cursor - 3..cursor) == Some(&[b'.', b'.', b'.'][..]))
390
+ || (previous == b'.' && cursor >= 3 && bytes.get(cursor - 3..cursor) == Some(b"..."))
393
391
  }
394
392
 
395
393
  fn apply_text_replacements(source: &mut String, replacements: Vec<(usize, usize, String)>) -> bool {
@@ -1,9 +1,11 @@
1
- use std::collections::BTreeMap;
1
+ use std::collections::{BTreeMap, BTreeSet};
2
2
  use std::path::{Path, PathBuf};
3
3
 
4
4
  use crate::dependency_scripts::package_used_in_tooling;
5
5
  use crate::generated::is_generated_dart_path;
6
- use crate::{DependencyKind, Location, scan::ScannedProject};
6
+ use crate::graph::resolve_local_uri;
7
+ use crate::package_map::PackageMap;
8
+ use crate::{DartFile, DependencyKind, Location, extract_dart_file, scan::ScannedProject};
7
9
 
8
10
  use super::codegen::codegen_dependencies_for_file;
9
11
  use super::usage::DependencyUsage;
@@ -31,7 +33,8 @@ pub fn analyze_dependency_hygiene(
31
33
  project: &ScannedProject,
32
34
  ) -> Result<DependencyHygieneReport, DependencyHygieneError> {
33
35
  let packages = discover_packages(&project.root)?;
34
- let mut imports = collect_import_usage(project, &packages);
36
+ let generated_runtime_files = reachable_generated_runtime_files(project, &packages)?;
37
+ let mut imports = collect_import_usage(project, &packages, &generated_runtime_files);
35
38
  let mut unused_dependencies = unused_dependencies(&packages, &imports.used_by_package);
36
39
 
37
40
  sort_unused_dependencies(&mut unused_dependencies);
@@ -48,7 +51,11 @@ pub fn analyze_dependency_hygiene(
48
51
  })
49
52
  }
50
53
 
51
- fn collect_import_usage(project: &ScannedProject, packages: &[PubPackage]) -> ImportUsage {
54
+ fn collect_import_usage(
55
+ project: &ScannedProject,
56
+ packages: &[PubPackage],
57
+ generated_runtime_files: &[DartFile],
58
+ ) -> ImportUsage {
52
59
  let mut usage = ImportUsage::default();
53
60
  for file in &project.files {
54
61
  let Some(owner) = owning_package(packages, &file.path) else {
@@ -80,9 +87,76 @@ fn collect_import_usage(project: &ScannedProject, packages: &[PubPackage]) -> Im
80
87
  }
81
88
  }
82
89
  }
90
+ for file in generated_runtime_files {
91
+ let Some(owner) = owning_package(packages, &file.path) else {
92
+ continue;
93
+ };
94
+ for specifier in file
95
+ .imports
96
+ .iter()
97
+ .map(|import| import.uri.as_str())
98
+ .chain(file.exports.iter().map(|export| export.uri.as_str()))
99
+ {
100
+ let Some(dependency) = package_name(specifier) else {
101
+ continue;
102
+ };
103
+ if dependency != owner.name {
104
+ record_dependency_usage(&mut usage, owner, &file.path, &dependency);
105
+ }
106
+ }
107
+ }
83
108
  usage
84
109
  }
85
110
 
111
+ fn reachable_generated_runtime_files(
112
+ project: &ScannedProject,
113
+ packages: &[PubPackage],
114
+ ) -> Result<Vec<DartFile>, DependencyHygieneError> {
115
+ let package_map = PackageMap::discover(&project.root)?;
116
+ let mut known_paths = project
117
+ .files
118
+ .iter()
119
+ .map(|file| file.path.clone())
120
+ .collect::<BTreeSet<_>>();
121
+ let mut frontier = project
122
+ .files
123
+ .iter()
124
+ .filter(|file| {
125
+ owning_package(packages, &file.path)
126
+ .is_some_and(|owner| !super::allows_dev_dependency(&owner.root, &file.path))
127
+ })
128
+ .cloned()
129
+ .collect::<Vec<_>>();
130
+ let mut generated = Vec::new();
131
+
132
+ while let Some(file) = frontier.pop() {
133
+ for specifier in file
134
+ .imports
135
+ .iter()
136
+ .map(|import| import.uri.as_str())
137
+ .chain(file.exports.iter().map(|export| export.uri.as_str()))
138
+ {
139
+ let Some(target) =
140
+ resolve_local_uri(&project.root, &package_map, &file.path, specifier)
141
+ else {
142
+ continue;
143
+ };
144
+ if !target.local
145
+ || !target.path.is_file()
146
+ || !is_generated_dart_path(&target.path)
147
+ || !known_paths.insert(target.path.clone())
148
+ {
149
+ continue;
150
+ }
151
+ let parsed = extract_dart_file(&target.path)?;
152
+ frontier.push(parsed.clone());
153
+ generated.push(parsed);
154
+ }
155
+ }
156
+ generated.sort_by(|left, right| left.path.cmp(&right.path));
157
+ Ok(generated)
158
+ }
159
+
86
160
  fn record_directive(
87
161
  usage: &mut ImportUsage,
88
162
  owner: &PubPackage,
@@ -110,13 +184,7 @@ fn record_directive(
110
184
  });
111
185
  }
112
186
 
113
- usage
114
- .used_by_package
115
- .entry(owner.root.clone())
116
- .or_default()
117
- .entry(dependency.clone())
118
- .or_default()
119
- .record(&owner.root, file_path);
187
+ record_dependency_usage(usage, owner, file_path, &dependency);
120
188
 
121
189
  if !owner.declares_dependency_for_path(&dependency, file_path)
122
190
  && !is_known_generated_internal_import(file_path, specifier)
@@ -137,6 +205,21 @@ fn record_directive(
137
205
  }
138
206
  }
139
207
 
208
+ fn record_dependency_usage(
209
+ usage: &mut ImportUsage,
210
+ owner: &PubPackage,
211
+ file_path: &Path,
212
+ dependency: &str,
213
+ ) {
214
+ usage
215
+ .used_by_package
216
+ .entry(owner.root.clone())
217
+ .or_default()
218
+ .entry(dependency.to_owned())
219
+ .or_default()
220
+ .record(&owner.root, file_path);
221
+ }
222
+
140
223
  fn is_known_generated_internal_import(file_path: &Path, specifier: &str) -> bool {
141
224
  is_generated_dart_path(file_path) && matches!(specifier, "package:slang/generated.dart")
142
225
  }
@@ -29,16 +29,27 @@ pub(super) fn codegen_dependencies_for_file(file: &DartFile) -> BTreeSet<Codegen
29
29
  dependencies.insert(dev_dependency("build_runner"));
30
30
  dependencies.insert(dev_dependency("go_router_builder"));
31
31
  }
32
+ if signals.contains(&CodegenSignal::Envied) {
33
+ dependencies.insert(dev_dependency("build_runner"));
34
+ dependencies.insert(dev_dependency("envied_generator"));
35
+ }
32
36
 
33
37
  dependencies
34
38
  }
35
39
 
40
+ pub(crate) fn file_uses_codegen_dependency(file: &DartFile, dependency: &str) -> bool {
41
+ codegen_dependencies_for_file(file)
42
+ .iter()
43
+ .any(|candidate| candidate.name == dependency)
44
+ }
45
+
36
46
  #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
37
47
  enum CodegenSignal {
38
48
  Freezed,
39
49
  JsonSerializable,
40
50
  Riverpod,
41
51
  GoRouter,
52
+ Envied,
42
53
  }
43
54
 
44
55
  fn codegen_signals(file: &DartFile) -> BTreeSet<CodegenSignal> {
@@ -69,6 +80,13 @@ fn codegen_signals(file: &DartFile) -> BTreeSet<CodegenSignal> {
69
80
  }
70
81
  if imports.contains(&"package:json_annotation/json_annotation.dart")
71
82
  || parts.iter().any(|part| part.ends_with(".g.dart"))
83
+ && references.iter().any(|reference| {
84
+ matches!(
85
+ *reference,
86
+ "JsonSerializable" | "JsonKey" | "JsonEnum" | "JsonValue"
87
+ ) || reference.ends_with("FromJson")
88
+ || reference.ends_with("ToJson")
89
+ })
72
90
  || references.iter().any(|reference| {
73
91
  matches!(
74
92
  *reference,
@@ -99,6 +117,14 @@ fn codegen_signals(file: &DartFile) -> BTreeSet<CodegenSignal> {
99
117
  {
100
118
  signals.insert(CodegenSignal::GoRouter);
101
119
  }
120
+ if imports.contains(&"package:envied/envied.dart")
121
+ && (parts.iter().any(|part| part.ends_with(".g.dart"))
122
+ || references
123
+ .iter()
124
+ .any(|reference| matches!(*reference, "Envied" | "EnviedField")))
125
+ {
126
+ signals.insert(CodegenSignal::Envied);
127
+ }
102
128
 
103
129
  signals
104
130
  }
@@ -7,10 +7,11 @@ use serde_yaml_ng::{Mapping, Value};
7
7
  use thiserror::Error;
8
8
 
9
9
  use crate::graph::normalize_path;
10
- use crate::{DependencyKind, Location};
10
+ use crate::{DependencyKind, ExtractError, GraphError, Location};
11
11
 
12
12
  mod analyze;
13
13
  mod codegen;
14
+ pub(crate) use codegen::file_uses_codegen_dependency;
14
15
  mod discovery;
15
16
  mod overrides;
16
17
  mod private_src_imports;
@@ -144,6 +145,12 @@ impl DependencySection {
144
145
  /// Errors returned while analyzing pub dependency hygiene.
145
146
  #[derive(Debug, Error)]
146
147
  pub enum DependencyHygieneError {
148
+ /// Local package resolution failed while following a generated runtime file.
149
+ #[error(transparent)]
150
+ Graph(#[from] GraphError),
151
+ /// A reachable generated runtime file could not be parsed.
152
+ #[error(transparent)]
153
+ Extract(#[from] ExtractError),
147
154
  /// A directory could not be read.
148
155
  #[error("failed to read directory {path}: {source}")]
149
156
  ReadDir {
@@ -2,7 +2,8 @@ use std::fs;
2
2
  use std::path::{Path, PathBuf};
3
3
 
4
4
  pub(crate) fn package_used_in_tooling(package_root: &Path, dependency: &str) -> bool {
5
- pubspec_tooling_section(package_root, dependency)
5
+ pubspec_has_top_level_key(package_root, dependency)
6
+ || known_tooling_convention(package_root, dependency)
6
7
  || tooling_files(package_root).into_iter().any(|path| {
7
8
  fs::read_to_string(path)
8
9
  .ok()
@@ -10,18 +11,51 @@ pub(crate) fn package_used_in_tooling(package_root: &Path, dependency: &str) ->
10
11
  })
11
12
  }
12
13
 
13
- fn pubspec_tooling_section(package_root: &Path, dependency: &str) -> bool {
14
+ fn pubspec_has_top_level_key(package_root: &Path, key: &str) -> bool {
14
15
  let path = package_root.join("pubspec.yaml");
15
- fs::read_to_string(path).ok().is_some_and(|source| {
16
- source.lines().any(|line| {
17
- let trimmed = line.trim_end();
18
- !trimmed.starts_with(' ')
19
- && !trimmed.starts_with('\t')
20
- && trimmed == format!("{dependency}:")
16
+ fs::read_to_string(path)
17
+ .ok()
18
+ .and_then(|source| serde_yaml_ng::from_str::<serde_yaml_ng::Value>(&source).ok())
19
+ .is_some_and(|pubspec| pubspec.get(key).is_some())
20
+ }
21
+
22
+ fn known_tooling_convention(package_root: &Path, dependency: &str) -> bool {
23
+ match dependency {
24
+ "flutter_gen_runner" => pubspec_has_top_level_key(package_root, "flutter_gen"),
25
+ "test" => contains_runnable_test(&package_root.join("test")),
26
+ _ => false,
27
+ }
28
+ }
29
+
30
+ fn contains_runnable_test(dir: &Path) -> bool {
31
+ let Ok(entries) = fs::read_dir(dir) else {
32
+ return false;
33
+ };
34
+ entries.flatten().any(|entry| {
35
+ let path = entry.path();
36
+ entry.file_type().ok().is_some_and(|file_type| {
37
+ file_type.is_file() && is_runnable_test_file(&path)
38
+ || file_type.is_dir() && contains_runnable_test(&path)
21
39
  })
22
40
  })
23
41
  }
24
42
 
43
+ fn is_runnable_test_file(path: &Path) -> bool {
44
+ if path.extension().is_none_or(|extension| extension != "dart") {
45
+ return false;
46
+ }
47
+ if path
48
+ .file_name()
49
+ .and_then(|name| name.to_str())
50
+ .is_some_and(|name| name.ends_with("_test.dart"))
51
+ {
52
+ return true;
53
+ }
54
+ crate::extract_dart_file(path)
55
+ .ok()
56
+ .is_some_and(|file| crate::extract::has_top_level_function(&file, "main"))
57
+ }
58
+
25
59
  fn tooling_files(package_root: &Path) -> Vec<PathBuf> {
26
60
  let mut paths = [
27
61
  "analysis_options.yaml",
package/src/extract.rs CHANGED
@@ -91,6 +91,12 @@ pub struct DartFile {
91
91
  pub routes: Vec<DartRouteDeclaration>,
92
92
  }
93
93
 
94
+ pub(crate) fn has_top_level_function(file: &DartFile, name: &str) -> bool {
95
+ file.declarations.iter().any(|declaration| {
96
+ declaration.name == name && declaration.kind == DeclarationKind::Function
97
+ })
98
+ }
99
+
94
100
  /// A Dart `library` directive.
95
101
  #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96
102
  pub struct DartLibrary {
@@ -0,0 +1,58 @@
1
+ use std::ffi::OsStr;
2
+ use std::path::Path;
3
+ use std::process::Command;
4
+
5
+ const REPOSITORY_LOCAL_ENVIRONMENT: &[&str] = &[
6
+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",
7
+ "GIT_CONFIG",
8
+ "GIT_CONFIG_PARAMETERS",
9
+ "GIT_CONFIG_COUNT",
10
+ "GIT_OBJECT_DIRECTORY",
11
+ "GIT_DIR",
12
+ "GIT_WORK_TREE",
13
+ "GIT_IMPLICIT_WORK_TREE",
14
+ "GIT_GRAFT_FILE",
15
+ "GIT_INDEX_FILE",
16
+ "GIT_NO_REPLACE_OBJECTS",
17
+ "GIT_REPLACE_REF_BASE",
18
+ "GIT_PREFIX",
19
+ "GIT_SHALLOW_FILE",
20
+ "GIT_COMMON_DIR",
21
+ ];
22
+
23
+ pub(crate) fn for_repository(root: &Path) -> Command {
24
+ let mut command = Command::new("git");
25
+ command.current_dir(root);
26
+ for variable in REPOSITORY_LOCAL_ENVIRONMENT {
27
+ command.env_remove(variable);
28
+ }
29
+ for (variable, _) in std::env::vars_os() {
30
+ if is_scoped_config_variable(&variable) {
31
+ command.env_remove(variable);
32
+ }
33
+ }
34
+ command
35
+ }
36
+
37
+ fn is_scoped_config_variable(variable: &OsStr) -> bool {
38
+ let variable = variable.as_encoded_bytes();
39
+ variable.starts_with(b"GIT_CONFIG_KEY_") || variable.starts_with(b"GIT_CONFIG_VALUE_")
40
+ }
41
+
42
+ #[cfg(test)]
43
+ mod tests {
44
+ use super::*;
45
+
46
+ #[test]
47
+ fn removes_repository_local_environment() {
48
+ let command = for_repository(Path::new("."));
49
+ let removed = command
50
+ .get_envs()
51
+ .filter_map(|(key, value)| value.is_none().then_some(key))
52
+ .collect::<Vec<_>>();
53
+
54
+ for variable in REPOSITORY_LOCAL_ENVIRONMENT {
55
+ assert!(removed.contains(&OsStr::new(variable)), "kept {variable}");
56
+ }
57
+ }
58
+ }
package/src/graph.rs CHANGED
@@ -150,6 +150,11 @@ impl ModuleGraph {
150
150
  &self.unresolved
151
151
  }
152
152
 
153
+ pub(crate) fn suppress_existing_unresolved_targets(&mut self) {
154
+ self.unresolved
155
+ .retain(|dependency| !dependency.attempted_path.is_file());
156
+ }
157
+
153
158
  /// Resolved `part` edges whose target file does not declare a matching `part of`.
154
159
  #[must_use]
155
160
  pub fn invalid_part_relationships(&self) -> &[InvalidPartRelationship] {
package/src/lib.rs CHANGED
@@ -23,6 +23,7 @@ pub mod feature_flags;
23
23
  pub(crate) mod finding_identity;
24
24
  pub mod fix;
25
25
  pub(crate) mod generated;
26
+ pub(crate) mod git_command;
26
27
  pub mod graph;
27
28
  pub mod health;
28
29
  pub mod hooks;
package/src/manifest.rs CHANGED
@@ -288,7 +288,7 @@ fn evidence_commands() -> Value {
288
288
  {
289
289
  "name": "trace-dependency",
290
290
  "kind": "trace-dependency",
291
- "description": "Trace one pub dependency declaration and Dart import/export usage.",
291
+ "description": "Trace one pub dependency declaration and Dart, tooling, or code-generation usage.",
292
292
  "schema": TRACE_SCHEMA_VERSION,
293
293
  "flags": ["--root", "--format", "--config", "--entry", "--dart-platform", "--production", "--no-production", "--dependency"]
294
294
  },