dart-decimate 0.0.13 → 0.0.14

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 {
@@ -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
  }
@@ -11,6 +11,7 @@ use crate::{DependencyKind, 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;
@@ -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
  },
package/src/scan/tests.rs CHANGED
@@ -221,6 +221,139 @@ fn scans_pub_workspace_member_files() -> Result<(), Box<dyn std::error::Error>>
221
221
  Ok(())
222
222
  }
223
223
 
224
+ #[test]
225
+ fn repository_scan_stops_parent_gitignore_discovery_at_git_root()
226
+ -> Result<(), Box<dyn std::error::Error>> {
227
+ let fixture = tempfile::tempdir()?;
228
+ write(&fixture, ".gitignore", "*.dart\n")?;
229
+ write(&fixture, "repo/.git/HEAD", "ref: refs/heads/main\n")?;
230
+ write(&fixture, "repo/.gitignore", "ignored.dart\n")?;
231
+ write(&fixture, "repo/pubspec.yaml", "name: app\n")?;
232
+ write(&fixture, "repo/lib/main.dart", "void main() {}\n")?;
233
+ write(&fixture, "repo/lib/ignored.dart", "class Ignored {}\n")?;
234
+
235
+ let project = scan_project(fixture.path().join("repo"))?;
236
+
237
+ assert_eq!(project.files.len(), 1);
238
+ assert_eq!(
239
+ project.files[0].path,
240
+ fixture.path().join("repo/lib/main.dart")
241
+ );
242
+
243
+ Ok(())
244
+ }
245
+
246
+ #[test]
247
+ fn non_repository_scan_uses_root_gitignore_without_parent_rules()
248
+ -> Result<(), Box<dyn std::error::Error>> {
249
+ let fixture = tempfile::tempdir()?;
250
+ write(&fixture, ".gitignore", "*.dart\n")?;
251
+ write(&fixture, "app/.gitignore", "ignored.dart\n")?;
252
+ write(&fixture, "app/pubspec.yaml", "name: app\n")?;
253
+ write(&fixture, "app/lib/main.dart", "void main() {}\n")?;
254
+ write(&fixture, "app/lib/ignored.dart", "class Ignored {}\n")?;
255
+
256
+ let project = scan_project(fixture.path().join("app"))?;
257
+
258
+ assert_eq!(project.files.len(), 1);
259
+ assert_eq!(
260
+ project.files[0].path,
261
+ fixture.path().join("app/lib/main.dart")
262
+ );
263
+
264
+ Ok(())
265
+ }
266
+
267
+ #[test]
268
+ fn ignored_external_package_root_is_not_scanned() -> Result<(), Box<dyn std::error::Error>> {
269
+ let fixture = tempfile::tempdir()?;
270
+ write(&fixture, ".git/HEAD", "ref: refs/heads/main\n")?;
271
+ write(&fixture, ".gitignore", "shared/\n")?;
272
+ write(
273
+ &fixture,
274
+ "app/pubspec.yaml",
275
+ "name: app\ndependencies:\n shared:\n path: ../shared\n",
276
+ )?;
277
+ write(&fixture, "app/lib/main.dart", "void main() {}\n")?;
278
+ write(&fixture, "shared/pubspec.yaml", "name: shared\n")?;
279
+ write(
280
+ &fixture,
281
+ "shared/lib/generated.dart",
282
+ "class Generated {}\n",
283
+ )?;
284
+
285
+ let project = scan_project(fixture.path().join("app"))?;
286
+
287
+ assert_eq!(project.files.len(), 1);
288
+ assert_eq!(
289
+ project.files[0].path,
290
+ fixture.path().join("app/lib/main.dart")
291
+ );
292
+ Ok(())
293
+ }
294
+
295
+ #[test]
296
+ fn tracked_dart_files_override_gitignore_rules() -> Result<(), Box<dyn std::error::Error>> {
297
+ let fixture = tempfile::tempdir()?;
298
+ let status = crate::git_command::for_repository(fixture.path())
299
+ .args(["init", "--quiet"])
300
+ .status()?;
301
+ assert!(status.success());
302
+ write(&fixture, ".gitignore", "*.g.dart\n")?;
303
+ write(&fixture, "pubspec.yaml", "name: app\n")?;
304
+ write(&fixture, "lib/main.dart", "void main() {}\n")?;
305
+ write(&fixture, "lib/tracked.g.dart", "class Tracked {}\n")?;
306
+ write(&fixture, "lib/untracked.g.dart", "class Untracked {}\n")?;
307
+ let status = crate::git_command::for_repository(fixture.path())
308
+ .args([
309
+ "add",
310
+ "--force",
311
+ ".gitignore",
312
+ "pubspec.yaml",
313
+ "lib/main.dart",
314
+ "lib/tracked.g.dart",
315
+ ])
316
+ .status()?;
317
+ assert!(status.success());
318
+
319
+ let project = scan_project(fixture.path())?;
320
+ let paths = project
321
+ .files
322
+ .iter()
323
+ .map(|file| file.path.strip_prefix(fixture.path()))
324
+ .collect::<Result<Vec<_>, _>>()?;
325
+
326
+ assert!(paths.contains(&Path::new("lib/tracked.g.dart")));
327
+ assert!(!paths.contains(&Path::new("lib/untracked.g.dart")));
328
+ Ok(())
329
+ }
330
+
331
+ #[test]
332
+ fn existing_ignored_dependency_targets_are_not_unresolved() -> Result<(), Box<dyn std::error::Error>>
333
+ {
334
+ let fixture = tempfile::tempdir()?;
335
+ write(&fixture, ".gitignore", "*.gen.dart\n")?;
336
+ write(&fixture, "pubspec.yaml", "name: app\n")?;
337
+ write(
338
+ &fixture,
339
+ "lib/main.dart",
340
+ "import 'assets.gen.dart';\nvoid main() {}\n",
341
+ )?;
342
+ write(
343
+ &fixture,
344
+ "lib/assets.gen.dart",
345
+ "class GeneratedAssets {}\n",
346
+ )?;
347
+
348
+ let project = scan_project(fixture.path())?;
349
+
350
+ assert_eq!(project.files.len(), 1);
351
+ assert_eq!(project.graph.node_count(), 1);
352
+ assert_eq!(project.graph.edge_count(), 0);
353
+ assert!(project.graph.unresolved().is_empty());
354
+ Ok(())
355
+ }
356
+
224
357
  #[test]
225
358
  fn scans_all_conditional_import_targets() -> Result<(), Box<dyn std::error::Error>> {
226
359
  let fixture = tempfile::tempdir()?;