dart-decimate 0.0.1

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.
Files changed (188) hide show
  1. package/Cargo.lock +572 -0
  2. package/Cargo.toml +41 -0
  3. package/LICENSE +21 -0
  4. package/README.md +617 -0
  5. package/assets/dart-decimate-banner.png +0 -0
  6. package/npm/bin/dart-decimate-mcp.js +48 -0
  7. package/npm/bin/dart-decimate.js +48 -0
  8. package/npm/scripts/postinstall.js +46 -0
  9. package/npm/scripts/test-npx-local.js +54 -0
  10. package/npm/scripts/test-npx-mcp-local.js +56 -0
  11. package/package.json +45 -0
  12. package/src/baseline.rs +643 -0
  13. package/src/bin/dart-decimate-mcp.rs +11 -0
  14. package/src/boundaries/tests.rs +60 -0
  15. package/src/boundaries.rs +317 -0
  16. package/src/changed_scope.rs +117 -0
  17. package/src/ci_template.rs +399 -0
  18. package/src/cli/analyze.rs +462 -0
  19. package/src/cli/analyzer_options.rs +82 -0
  20. package/src/cli/audit_run.rs +327 -0
  21. package/src/cli/boundary_args.rs +44 -0
  22. package/src/cli/ci_template_run.rs +196 -0
  23. package/src/cli/command_name.rs +20 -0
  24. package/src/cli/common_args.rs +167 -0
  25. package/src/cli/config_run.rs +78 -0
  26. package/src/cli/coverage_run.rs +393 -0
  27. package/src/cli/decision_surface_run.rs +99 -0
  28. package/src/cli/default_command.rs +69 -0
  29. package/src/cli/dupes_args.rs +150 -0
  30. package/src/cli/entry_points.rs +121 -0
  31. package/src/cli/error.rs +149 -0
  32. package/src/cli/error_output.rs +68 -0
  33. package/src/cli/explain_run.rs +72 -0
  34. package/src/cli/fix_run.rs +162 -0
  35. package/src/cli/flags_args.rs +23 -0
  36. package/src/cli/health_args.rs +200 -0
  37. package/src/cli/hooks_run.rs +191 -0
  38. package/src/cli/impact_run.rs +95 -0
  39. package/src/cli/init_run.rs +49 -0
  40. package/src/cli/inspect_args.rs +20 -0
  41. package/src/cli/inspect_run.rs +66 -0
  42. package/src/cli/issue_filter_args.rs +240 -0
  43. package/src/cli/list_run.rs +311 -0
  44. package/src/cli/mode_args.rs +72 -0
  45. package/src/cli/output_format.rs +62 -0
  46. package/src/cli/regression_args.rs +156 -0
  47. package/src/cli/request_args.rs +175 -0
  48. package/src/cli/schema_commands.rs +72 -0
  49. package/src/cli/scope_args.rs +174 -0
  50. package/src/cli/security_args.rs +175 -0
  51. package/src/cli/security_gate_run.rs +66 -0
  52. package/src/cli/security_summary_run.rs +43 -0
  53. package/src/cli/summary_args.rs +12 -0
  54. package/src/cli/tests.rs +516 -0
  55. package/src/cli/trace_args.rs +67 -0
  56. package/src/cli/trace_run.rs +131 -0
  57. package/src/cli/trace_tests.rs +235 -0
  58. package/src/cli/unsupported_run.rs +116 -0
  59. package/src/cli/watch_run.rs +153 -0
  60. package/src/cli.rs +603 -0
  61. package/src/config/boundary_config.rs +235 -0
  62. package/src/config/cache.rs +25 -0
  63. package/src/config/dependencies.rs +114 -0
  64. package/src/config/health.rs +237 -0
  65. package/src/config/jsonc.rs +66 -0
  66. package/src/config/policy.rs +91 -0
  67. package/src/config/rule_aliases.rs +487 -0
  68. package/src/config/rules.rs +339 -0
  69. package/src/config.rs +635 -0
  70. package/src/coverage.rs +469 -0
  71. package/src/dart_parser.rs +673 -0
  72. package/src/decision_surface.rs +405 -0
  73. package/src/dependencies/analyze.rs +218 -0
  74. package/src/dependencies/codegen.rs +118 -0
  75. package/src/dependencies/discovery.rs +60 -0
  76. package/src/dependencies/overrides.rs +76 -0
  77. package/src/dependencies/private_src_imports.rs +32 -0
  78. package/src/dependencies/pubspec_document.rs +86 -0
  79. package/src/dependencies/pubspec_entry.rs +96 -0
  80. package/src/dependencies/tests.rs +544 -0
  81. package/src/dependencies/usage.rs +33 -0
  82. package/src/dependencies.rs +553 -0
  83. package/src/dependency_scripts.rs +91 -0
  84. package/src/dupes/lex.rs +236 -0
  85. package/src/dupes/tests.rs +119 -0
  86. package/src/dupes.rs +625 -0
  87. package/src/explain.rs +692 -0
  88. package/src/extract/directives.rs +252 -0
  89. package/src/extract/error_tests.rs +25 -0
  90. package/src/extract/members.rs +210 -0
  91. package/src/extract/primary_constructors.rs +421 -0
  92. package/src/extract/references.rs +151 -0
  93. package/src/extract/routes.rs +691 -0
  94. package/src/extract/signatures.rs +266 -0
  95. package/src/extract/string_tests.rs +18 -0
  96. package/src/extract/strings.rs +107 -0
  97. package/src/extract/tests.rs +697 -0
  98. package/src/extract.rs +680 -0
  99. package/src/feature_flags/tests.rs +76 -0
  100. package/src/feature_flags.rs +453 -0
  101. package/src/finding_identity.rs +60 -0
  102. package/src/fix.rs +551 -0
  103. package/src/generated.rs +53 -0
  104. package/src/graph/augment_tests.rs +212 -0
  105. package/src/graph/conditionals.rs +74 -0
  106. package/src/graph/package_config_tests.rs +100 -0
  107. package/src/graph/parts.rs +248 -0
  108. package/src/graph/pubspec_tests.rs +119 -0
  109. package/src/graph/tests.rs +837 -0
  110. package/src/graph/uri_tests.rs +102 -0
  111. package/src/graph.rs +644 -0
  112. package/src/health/coverage.rs +309 -0
  113. package/src/health/ownership.rs +175 -0
  114. package/src/health/runtime_coverage.rs +616 -0
  115. package/src/health/runtime_intelligence.rs +511 -0
  116. package/src/health/scores.rs +296 -0
  117. package/src/health/tests.rs +240 -0
  118. package/src/health/threshold_types.rs +163 -0
  119. package/src/health/thresholds.rs +229 -0
  120. package/src/health/types.rs +636 -0
  121. package/src/health.rs +597 -0
  122. package/src/hooks/agent_settings.rs +175 -0
  123. package/src/hooks/templates.rs +51 -0
  124. package/src/hooks.rs +569 -0
  125. package/src/impact.rs +287 -0
  126. package/src/init.rs +237 -0
  127. package/src/inspect.rs +142 -0
  128. package/src/intelligence/tests.rs +232 -0
  129. package/src/intelligence.rs +305 -0
  130. package/src/lib.rs +198 -0
  131. package/src/main.rs +5 -0
  132. package/src/manifest/mcp.rs +565 -0
  133. package/src/manifest.rs +552 -0
  134. package/src/mcp/cli_args/value_args.rs +175 -0
  135. package/src/mcp/cli_args.rs +658 -0
  136. package/src/mcp/cli_args_tests.rs +522 -0
  137. package/src/mcp/code_execute.rs +671 -0
  138. package/src/mcp/tools.rs +660 -0
  139. package/src/mcp.rs +325 -0
  140. package/src/output/audit_risk.rs +135 -0
  141. package/src/output/dependency_findings.rs +327 -0
  142. package/src/output/duplication_findings.rs +114 -0
  143. package/src/output/feature_flag_findings.rs +122 -0
  144. package/src/output/format.rs +31 -0
  145. package/src/output/graph_findings.rs +461 -0
  146. package/src/output/health_findings.rs +612 -0
  147. package/src/output/human.rs +27 -0
  148. package/src/output/next_steps.rs +92 -0
  149. package/src/output/route_findings.rs +76 -0
  150. package/src/output/runtime_coverage.rs +515 -0
  151. package/src/output/scope.rs +183 -0
  152. package/src/output/security_findings.rs +390 -0
  153. package/src/output/security_sarif.rs +150 -0
  154. package/src/output/suppressions.rs +323 -0
  155. package/src/output/symbol_findings.rs +257 -0
  156. package/src/output/tests.rs +114 -0
  157. package/src/output/types.rs +604 -0
  158. package/src/output/widget_findings.rs +213 -0
  159. package/src/output.rs +682 -0
  160. package/src/package_map.rs +495 -0
  161. package/src/policy/packs.rs +232 -0
  162. package/src/policy/tests.rs +134 -0
  163. package/src/policy.rs +640 -0
  164. package/src/project_list.rs +376 -0
  165. package/src/report_schema/inventory.rs +418 -0
  166. package/src/report_schema.rs +488 -0
  167. package/src/routes.rs +354 -0
  168. package/src/scan/tests.rs +250 -0
  169. package/src/scan.rs +275 -0
  170. package/src/security/detect.rs +639 -0
  171. package/src/security/tests.rs +178 -0
  172. package/src/security.rs +373 -0
  173. package/src/security_gate.rs +555 -0
  174. package/src/symbols/path_filters.rs +27 -0
  175. package/src/symbols/private_type_leaks.rs +125 -0
  176. package/src/symbols/riverpod.rs +113 -0
  177. package/src/symbols/tests.rs +692 -0
  178. package/src/symbols.rs +693 -0
  179. package/src/trace/tests.rs +225 -0
  180. package/src/trace.rs +690 -0
  181. package/src/unsupported.rs +47 -0
  182. package/src/widgets/lifecycle.rs +484 -0
  183. package/src/widgets/params.rs +236 -0
  184. package/src/widgets/tests.rs +430 -0
  185. package/src/widgets/top_level.rs +110 -0
  186. package/src/widgets/unrendered.rs +374 -0
  187. package/src/widgets.rs +590 -0
  188. package/src/workspace_scope.rs +358 -0
package/src/hooks.rs ADDED
@@ -0,0 +1,569 @@
1
+ use std::fs;
2
+ use std::path::{Path, PathBuf};
3
+
4
+ use serde::{Deserialize, Serialize};
5
+ use thiserror::Error;
6
+
7
+ mod agent_settings;
8
+ mod templates;
9
+
10
+ use agent_settings::{claude_settings_status, install_claude_settings, uninstall_claude_settings};
11
+ use templates::{agent_hook_script, agents_block};
12
+
13
+ /// Stable schema version for hook management output.
14
+ pub const HOOKS_SCHEMA_VERSION: &str = "dart-decimate.hooks.v1";
15
+
16
+ pub(super) const HOOK_MARKER: &str = "dart-decimate-managed-hook";
17
+ const AGENT_SCRIPT_PATH: &str = ".claude/hooks/dart-decimate-gate.sh";
18
+ const CLAUDE_SETTINGS_PATH: &str = ".claude/settings.json";
19
+ const AGENTS_PATH: &str = "AGENTS.md";
20
+ pub(super) const AGENT_COMMAND: &str =
21
+ "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/dart-decimate-gate.sh";
22
+ pub(super) const AGENTS_BLOCK_START: &str = "<!-- dart-decimate-managed-hook:start -->";
23
+ pub(super) const AGENTS_BLOCK_END: &str = "<!-- dart-decimate-managed-hook:end -->";
24
+
25
+ /// Hook installation target.
26
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
27
+ #[serde(rename_all = "kebab-case")]
28
+ pub enum HookTarget {
29
+ /// Git pre-commit hook under `.git/hooks/pre-commit`.
30
+ Git,
31
+ /// Claude Code and repository agent guidance hook surfaces.
32
+ Agent,
33
+ }
34
+
35
+ impl HookTarget {
36
+ /// CLI target string.
37
+ #[must_use]
38
+ pub const fn as_str(self) -> &'static str {
39
+ match self {
40
+ Self::Git => "git",
41
+ Self::Agent => "agent",
42
+ }
43
+ }
44
+ }
45
+
46
+ /// Hook management options.
47
+ #[derive(Debug, Clone, PartialEq, Eq)]
48
+ pub struct HookOptions {
49
+ /// Hook target.
50
+ pub target: HookTarget,
51
+ /// Git base branch used by generated hooks.
52
+ pub branch: String,
53
+ /// Overwrite or remove existing unmanaged hook files.
54
+ pub force: bool,
55
+ }
56
+
57
+ /// Machine-readable hook report.
58
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59
+ pub struct HooksReport {
60
+ /// Schema identifier.
61
+ pub schema_version: String,
62
+ /// Typed JSON envelope discriminator.
63
+ pub kind: String,
64
+ /// Tool name.
65
+ pub tool: String,
66
+ /// Command that produced this report.
67
+ pub command: String,
68
+ /// Project root.
69
+ pub root: PathBuf,
70
+ /// Hook target.
71
+ pub target: HookTarget,
72
+ /// Git base branch used by generated hooks.
73
+ pub branch: String,
74
+ /// Target hook files.
75
+ pub files: Vec<HookFile>,
76
+ }
77
+
78
+ /// Hook file status or mutation.
79
+ #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
80
+ pub struct HookFile {
81
+ /// Path relative to root.
82
+ pub path: String,
83
+ /// Whether the hook file exists.
84
+ pub installed: bool,
85
+ /// Whether Dart Decimate owns the hook file content.
86
+ pub managed: bool,
87
+ /// Action performed.
88
+ pub action: HookAction,
89
+ }
90
+
91
+ /// Hook action.
92
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
93
+ #[serde(rename_all = "kebab-case")]
94
+ pub enum HookAction {
95
+ /// Status only; no changes.
96
+ Unchanged,
97
+ /// Hook file was created.
98
+ Created,
99
+ /// Managed hook file was overwritten.
100
+ Overwritten,
101
+ /// Managed hook file was removed.
102
+ Removed,
103
+ /// Hook file did not exist.
104
+ Missing,
105
+ }
106
+
107
+ /// Hook errors.
108
+ #[derive(Debug, Error)]
109
+ pub enum HooksError {
110
+ /// Git hook target requires an initialized Git repository.
111
+ #[error("cannot install git hook because {path} does not exist")]
112
+ MissingGitDir {
113
+ /// Missing `.git` directory.
114
+ path: PathBuf,
115
+ },
116
+ /// Existing hook is not Dart Decimate-managed and `force` was not set.
117
+ #[error("refusing to overwrite unmanaged hook {path}; pass --force")]
118
+ UnmanagedHook {
119
+ /// Existing hook path.
120
+ path: PathBuf,
121
+ },
122
+ /// Directory creation failed.
123
+ #[error("failed to create hook directory {path}: {source}")]
124
+ CreateDir {
125
+ /// Directory path.
126
+ path: PathBuf,
127
+ /// Underlying IO error.
128
+ source: std::io::Error,
129
+ },
130
+ /// Hook file write failed.
131
+ #[error("failed to write hook {path}: {source}")]
132
+ Write {
133
+ /// Hook path.
134
+ path: PathBuf,
135
+ /// Underlying IO error.
136
+ source: std::io::Error,
137
+ },
138
+ /// Hook file read failed.
139
+ #[error("failed to read hook {path}: {source}")]
140
+ Read {
141
+ /// Hook path.
142
+ path: PathBuf,
143
+ /// Underlying IO error.
144
+ source: std::io::Error,
145
+ },
146
+ /// Hook permission update failed.
147
+ #[error("failed to mark hook executable {path}: {source}")]
148
+ Permissions {
149
+ /// Hook path.
150
+ path: PathBuf,
151
+ /// Underlying IO error.
152
+ source: std::io::Error,
153
+ },
154
+ /// Hook removal failed.
155
+ #[error("failed to remove hook {path}: {source}")]
156
+ Remove {
157
+ /// Hook path.
158
+ path: PathBuf,
159
+ /// Underlying IO error.
160
+ source: std::io::Error,
161
+ },
162
+ }
163
+
164
+ /// Inspect hook status.
165
+ ///
166
+ /// # Errors
167
+ ///
168
+ /// Returns [`HooksError`] if an existing hook cannot be read.
169
+ pub fn hooks_status(
170
+ root: impl AsRef<Path>,
171
+ options: &HookOptions,
172
+ ) -> Result<HooksReport, HooksError> {
173
+ let root = root.as_ref();
174
+ let files = match options.target {
175
+ HookTarget::Git => {
176
+ vec![hook_status_file(
177
+ root,
178
+ &git_hook_path(root),
179
+ HookAction::Unchanged,
180
+ )?]
181
+ }
182
+ HookTarget::Agent => agent_status_files(root)?,
183
+ };
184
+ Ok(report("hooks status", root, options, files))
185
+ }
186
+
187
+ /// Install a Dart Decimate hook.
188
+ ///
189
+ /// # Errors
190
+ ///
191
+ /// Returns [`HooksError`] when the target is not available, the hook is
192
+ /// unmanaged without `force`, or file writes fail.
193
+ pub fn install_hooks(
194
+ root: impl AsRef<Path>,
195
+ options: &HookOptions,
196
+ ) -> Result<HooksReport, HooksError> {
197
+ let root = root.as_ref();
198
+ let files = match options.target {
199
+ HookTarget::Git => {
200
+ let path = git_hook_path(root);
201
+ ensure_git_dir(root)?;
202
+ let action = write_git_hook(root, &path, options)?;
203
+ vec![hook_status_file(root, &path, action)?]
204
+ }
205
+ HookTarget::Agent => install_agent_hooks(root, options)?,
206
+ };
207
+ Ok(report("hooks install", root, options, files))
208
+ }
209
+
210
+ /// Uninstall a Dart Decimate-managed hook.
211
+ ///
212
+ /// # Errors
213
+ ///
214
+ /// Returns [`HooksError`] when an unmanaged hook exists without `force`, or when
215
+ /// file removal fails.
216
+ pub fn uninstall_hooks(
217
+ root: impl AsRef<Path>,
218
+ options: &HookOptions,
219
+ ) -> Result<HooksReport, HooksError> {
220
+ let root = root.as_ref();
221
+ let files = match options.target {
222
+ HookTarget::Git => vec![remove_git_hook(root, &git_hook_path(root), options.force)?],
223
+ HookTarget::Agent => uninstall_agent_hooks(root, options.force)?,
224
+ };
225
+ Ok(report("hooks uninstall", root, options, files))
226
+ }
227
+
228
+ /// Render a human-readable hook report.
229
+ #[must_use]
230
+ pub fn render_hooks_report(report: &HooksReport) -> String {
231
+ let Some(file) = report.files.first() else {
232
+ return format!(
233
+ "Hooks: {} target {}\n",
234
+ report.command,
235
+ report.target.as_str()
236
+ );
237
+ };
238
+ let state = if file.installed {
239
+ if file.managed {
240
+ "installed"
241
+ } else {
242
+ "unmanaged"
243
+ }
244
+ } else {
245
+ "not installed"
246
+ };
247
+ format!(
248
+ "Hooks: {} target {} ({state})\n{}: {:?}\n",
249
+ report.command,
250
+ report.target.as_str(),
251
+ file.path,
252
+ file.action
253
+ )
254
+ }
255
+
256
+ fn report(command: &str, root: &Path, options: &HookOptions, files: Vec<HookFile>) -> HooksReport {
257
+ HooksReport {
258
+ schema_version: HOOKS_SCHEMA_VERSION.to_owned(),
259
+ kind: "hooks".to_owned(),
260
+ tool: "dart-decimate".to_owned(),
261
+ command: command.to_owned(),
262
+ root: root.to_path_buf(),
263
+ target: options.target,
264
+ branch: options.branch.clone(),
265
+ files,
266
+ }
267
+ }
268
+
269
+ fn ensure_git_dir(root: &Path) -> Result<(), HooksError> {
270
+ let path = root.join(".git");
271
+ if path.is_dir() {
272
+ Ok(())
273
+ } else {
274
+ Err(HooksError::MissingGitDir { path })
275
+ }
276
+ }
277
+
278
+ fn git_hook_path(root: &Path) -> PathBuf {
279
+ root.join(".git/hooks/pre-commit")
280
+ }
281
+
282
+ fn agent_script_path(root: &Path) -> PathBuf {
283
+ root.join(AGENT_SCRIPT_PATH)
284
+ }
285
+
286
+ pub(super) fn claude_settings_path(root: &Path) -> PathBuf {
287
+ root.join(CLAUDE_SETTINGS_PATH)
288
+ }
289
+
290
+ fn agents_path(root: &Path) -> PathBuf {
291
+ root.join(AGENTS_PATH)
292
+ }
293
+
294
+ fn hook_status_file(root: &Path, path: &Path, action: HookAction) -> Result<HookFile, HooksError> {
295
+ let installed = path.is_file();
296
+ let managed = installed && read_hook(path)?.contains(HOOK_MARKER);
297
+ Ok(HookFile {
298
+ path: relative_path(root, path),
299
+ installed,
300
+ managed,
301
+ action,
302
+ })
303
+ }
304
+
305
+ fn status_file_with_marker(
306
+ root: &Path,
307
+ path: &Path,
308
+ action: HookAction,
309
+ marker: &str,
310
+ ) -> Result<HookFile, HooksError> {
311
+ let installed = path.is_file();
312
+ let managed = installed && read_hook(path)?.contains(marker);
313
+ Ok(HookFile {
314
+ path: relative_path(root, path),
315
+ installed,
316
+ managed,
317
+ action,
318
+ })
319
+ }
320
+
321
+ pub(super) fn missing_file(root: &Path, path: &Path) -> HookFile {
322
+ HookFile {
323
+ path: relative_path(root, path),
324
+ installed: false,
325
+ managed: false,
326
+ action: HookAction::Missing,
327
+ }
328
+ }
329
+
330
+ fn agent_status_files(root: &Path) -> Result<Vec<HookFile>, HooksError> {
331
+ Ok(vec![
332
+ hook_status_file(root, &agent_script_path(root), HookAction::Unchanged)?,
333
+ claude_settings_status(root, HookAction::Unchanged)?,
334
+ status_file_with_marker(
335
+ root,
336
+ &agents_path(root),
337
+ HookAction::Unchanged,
338
+ AGENTS_BLOCK_START,
339
+ )?,
340
+ ])
341
+ }
342
+
343
+ fn install_agent_hooks(root: &Path, options: &HookOptions) -> Result<Vec<HookFile>, HooksError> {
344
+ Ok(vec![
345
+ write_managed_file(
346
+ root,
347
+ &agent_script_path(root),
348
+ &agent_hook_script(&options.branch),
349
+ options.force,
350
+ true,
351
+ )?,
352
+ install_claude_settings(root, options.force)?,
353
+ install_agents_block(root, &options.branch)?,
354
+ ])
355
+ }
356
+
357
+ fn uninstall_agent_hooks(root: &Path, force: bool) -> Result<Vec<HookFile>, HooksError> {
358
+ Ok(vec![
359
+ remove_git_hook(root, &agent_script_path(root), force)?,
360
+ uninstall_claude_settings(root, force)?,
361
+ uninstall_agents_block(root)?,
362
+ ])
363
+ }
364
+
365
+ fn write_managed_file(
366
+ root: &Path,
367
+ path: &Path,
368
+ source: &str,
369
+ force: bool,
370
+ executable: bool,
371
+ ) -> Result<HookFile, HooksError> {
372
+ let action = if path.exists() {
373
+ if !read_hook(path)?.contains(HOOK_MARKER) && !force {
374
+ return Err(HooksError::UnmanagedHook {
375
+ path: path.to_path_buf(),
376
+ });
377
+ }
378
+ HookAction::Overwritten
379
+ } else {
380
+ HookAction::Created
381
+ };
382
+ write_text(path, source)?;
383
+ if executable {
384
+ mark_executable(path)?;
385
+ }
386
+ hook_status_file(root, path, action)
387
+ }
388
+
389
+ fn write_git_hook(
390
+ root: &Path,
391
+ path: &Path,
392
+ options: &HookOptions,
393
+ ) -> Result<HookAction, HooksError> {
394
+ let action = if path.exists() {
395
+ if !read_hook(path)?.contains(HOOK_MARKER) && !options.force {
396
+ return Err(HooksError::UnmanagedHook {
397
+ path: path.to_path_buf(),
398
+ });
399
+ }
400
+ HookAction::Overwritten
401
+ } else {
402
+ HookAction::Created
403
+ };
404
+ write_text(path, &git_hook_script(&options.branch))?;
405
+ mark_executable(path)?;
406
+ let _ = root;
407
+ Ok(action)
408
+ }
409
+
410
+ fn install_agents_block(root: &Path, branch: &str) -> Result<HookFile, HooksError> {
411
+ let path = agents_path(root);
412
+ let block = agents_block(branch);
413
+ let (source, action) = if path.exists() {
414
+ let source = read_hook(&path)?;
415
+ if source.contains(AGENTS_BLOCK_START) && source.contains(AGENTS_BLOCK_END) {
416
+ (
417
+ replace_managed_block(&source, &block),
418
+ HookAction::Overwritten,
419
+ )
420
+ } else {
421
+ (
422
+ append_managed_block(&source, &block),
423
+ HookAction::Overwritten,
424
+ )
425
+ }
426
+ } else {
427
+ (block, HookAction::Created)
428
+ };
429
+ write_text(&path, &source)?;
430
+ status_file_with_marker(root, &path, action, AGENTS_BLOCK_START)
431
+ }
432
+
433
+ fn uninstall_agents_block(root: &Path) -> Result<HookFile, HooksError> {
434
+ let path = agents_path(root);
435
+ if !path.exists() {
436
+ return Ok(missing_file(root, &path));
437
+ }
438
+ let source = read_hook(&path)?;
439
+ if !source.contains(AGENTS_BLOCK_START) || !source.contains(AGENTS_BLOCK_END) {
440
+ return status_file_with_marker(root, &path, HookAction::Unchanged, AGENTS_BLOCK_START);
441
+ }
442
+ write_text(&path, &replace_managed_block(&source, ""))?;
443
+ status_file_with_marker(root, &path, HookAction::Removed, AGENTS_BLOCK_START)
444
+ }
445
+
446
+ fn replace_managed_block(source: &str, replacement: &str) -> String {
447
+ let Some(start) = source.find(AGENTS_BLOCK_START) else {
448
+ return source.to_owned();
449
+ };
450
+ let Some(end) = source.find(AGENTS_BLOCK_END) else {
451
+ return source.to_owned();
452
+ };
453
+ let end = end + AGENTS_BLOCK_END.len();
454
+ let mut output = String::new();
455
+ output.push_str(source[..start].trim_end());
456
+ if !replacement.is_empty() {
457
+ if !output.is_empty() {
458
+ output.push_str("\n\n");
459
+ }
460
+ output.push_str(replacement.trim());
461
+ }
462
+ output.push_str(source[end..].trim_start_matches('\n'));
463
+ if !output.ends_with('\n') {
464
+ output.push('\n');
465
+ }
466
+ output
467
+ }
468
+
469
+ fn append_managed_block(source: &str, block: &str) -> String {
470
+ let mut output = source.trim_end().to_owned();
471
+ if !output.is_empty() {
472
+ output.push_str("\n\n");
473
+ }
474
+ output.push_str(block.trim());
475
+ output.push('\n');
476
+ output
477
+ }
478
+
479
+ pub(super) fn write_text(path: &Path, source: &str) -> Result<(), HooksError> {
480
+ if let Some(parent) = path.parent() {
481
+ fs::create_dir_all(parent).map_err(|source| HooksError::CreateDir {
482
+ path: parent.to_path_buf(),
483
+ source,
484
+ })?;
485
+ }
486
+ fs::write(path, source).map_err(|source| HooksError::Write {
487
+ path: path.to_path_buf(),
488
+ source,
489
+ })
490
+ }
491
+
492
+ fn remove_git_hook(root: &Path, path: &Path, force: bool) -> Result<HookFile, HooksError> {
493
+ if !path.exists() {
494
+ return Ok(HookFile {
495
+ path: relative_path(root, path),
496
+ installed: false,
497
+ managed: false,
498
+ action: HookAction::Missing,
499
+ });
500
+ }
501
+ let managed = read_hook(path)?.contains(HOOK_MARKER);
502
+ if !managed && !force {
503
+ return Err(HooksError::UnmanagedHook {
504
+ path: path.to_path_buf(),
505
+ });
506
+ }
507
+ fs::remove_file(path).map_err(|source| HooksError::Remove {
508
+ path: path.to_path_buf(),
509
+ source,
510
+ })?;
511
+ Ok(HookFile {
512
+ path: relative_path(root, path),
513
+ installed: false,
514
+ managed,
515
+ action: HookAction::Removed,
516
+ })
517
+ }
518
+
519
+ pub(super) fn read_hook(path: &Path) -> Result<String, HooksError> {
520
+ fs::read_to_string(path).map_err(|source| HooksError::Read {
521
+ path: path.to_path_buf(),
522
+ source,
523
+ })
524
+ }
525
+
526
+ fn mark_executable(path: &Path) -> Result<(), HooksError> {
527
+ #[cfg(unix)]
528
+ {
529
+ use std::os::unix::fs::PermissionsExt;
530
+ let mut permissions = fs::metadata(path)
531
+ .map_err(|source| HooksError::Permissions {
532
+ path: path.to_path_buf(),
533
+ source,
534
+ })?
535
+ .permissions();
536
+ permissions.set_mode(0o755);
537
+ fs::set_permissions(path, permissions).map_err(|source| HooksError::Permissions {
538
+ path: path.to_path_buf(),
539
+ source,
540
+ })
541
+ }
542
+ #[cfg(not(unix))]
543
+ {
544
+ let _ = path;
545
+ Ok(())
546
+ }
547
+ }
548
+
549
+ fn git_hook_script(branch: &str) -> String {
550
+ format!(
551
+ r#"#!/bin/sh
552
+ # {HOOK_MARKER}
553
+ set -eu
554
+ BASE="${{DART_DECIMATE_BASE:-{branch}}}"
555
+ if ! command -v dart-decimate >/dev/null 2>&1; then
556
+ echo "dart-decimate hook: dart-decimate binary not found" >&2
557
+ exit 2
558
+ fi
559
+ dart-decimate audit . --base "$BASE" --format json --summary
560
+ "#
561
+ )
562
+ }
563
+
564
+ pub(super) fn relative_path(root: &Path, path: &Path) -> String {
565
+ path.strip_prefix(root)
566
+ .unwrap_or(path)
567
+ .to_string_lossy()
568
+ .replace('\\', "/")
569
+ }