dart-decimate 0.0.5 → 0.0.6

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.
@@ -1,5 +1,7 @@
1
1
  use std::ffi::OsString;
2
2
 
3
+ use super::common_args::REPORT_FORMAT_VALUES;
4
+
3
5
  const COMMANDS: &[&str] = &[
4
6
  "audit",
5
7
  "check",
@@ -16,6 +18,7 @@ const COMMANDS: &[&str] = &[
16
18
  "fix",
17
19
  "flags",
18
20
  "health",
21
+ "html",
19
22
  "hooks",
20
23
  "impact",
21
24
  "init",
@@ -37,6 +40,8 @@ const COMMANDS: &[&str] = &[
37
40
  "trace-symbol",
38
41
  "watch",
39
42
  "workspaces",
43
+ "human",
44
+ "json",
40
45
  ];
41
46
 
42
47
  pub(super) fn args_with_default_check<I, T>(args: I) -> Vec<OsString>
@@ -45,12 +50,147 @@ where
45
50
  T: Into<OsString>,
46
51
  {
47
52
  let mut args = args.into_iter().map(Into::into).collect::<Vec<_>>();
53
+ if let Some(expanded) = args_with_output_alias(&args) {
54
+ return expanded;
55
+ }
48
56
  if should_insert_check(&args) {
49
57
  args.insert(1, OsString::from("check"));
50
58
  }
51
59
  args
52
60
  }
53
61
 
62
+ fn args_with_output_alias(args: &[OsString]) -> Option<Vec<OsString>> {
63
+ let alias = args.get(1)?.to_str()?;
64
+ if args
65
+ .iter()
66
+ .skip(2)
67
+ .take_while(|arg| !is_delimiter(arg))
68
+ .any(is_help_arg)
69
+ {
70
+ return None;
71
+ }
72
+ let format = match alias {
73
+ "human" => "human",
74
+ "json" => "json",
75
+ "html" => "html",
76
+ _ => return None,
77
+ };
78
+ let mut expanded = Vec::with_capacity(args.len() + 3);
79
+ expanded.push(args[0].clone());
80
+ expanded.push(OsString::from("check"));
81
+ let mut stdout_html = false;
82
+ let mut open_html = false;
83
+ let mut explicit_format_error = false;
84
+ let mut index = 2;
85
+ while let Some(arg) = args.get(index) {
86
+ if is_delimiter(arg) {
87
+ if !explicit_format_error {
88
+ push_output_alias_flags(&mut expanded, alias, format, stdout_html, open_html);
89
+ }
90
+ expanded.push(arg.clone());
91
+ expanded.extend(args.iter().skip(index + 1).cloned());
92
+ return Some(expanded);
93
+ }
94
+ if alias == "html" && arg == "--stdout" {
95
+ stdout_html = true;
96
+ index += 1;
97
+ continue;
98
+ }
99
+ if alias == "html" && arg == "--open" {
100
+ open_html = true;
101
+ }
102
+ if arg == "--format" {
103
+ let Some(value) = args.get(index + 1) else {
104
+ expanded.push(arg.clone());
105
+ explicit_format_error = true;
106
+ index += 1;
107
+ continue;
108
+ };
109
+ match value.to_str() {
110
+ Some(value) if value.starts_with('-') => {
111
+ expanded.push(arg.clone());
112
+ explicit_format_error = true;
113
+ index += 1;
114
+ }
115
+ Some(value) if is_report_format(value) => {
116
+ index += 2;
117
+ }
118
+ _ => {
119
+ expanded.push(arg.clone());
120
+ expanded.push(value.clone());
121
+ explicit_format_error = true;
122
+ index += 2;
123
+ }
124
+ }
125
+ continue;
126
+ }
127
+ if let Some(value) = arg
128
+ .to_str()
129
+ .and_then(|value| value.strip_prefix("--format="))
130
+ {
131
+ if !is_report_format(value) {
132
+ expanded.push(arg.clone());
133
+ explicit_format_error = true;
134
+ }
135
+ index += 1;
136
+ continue;
137
+ }
138
+ expanded.push(arg.clone());
139
+ index += 1;
140
+ }
141
+ if !explicit_format_error {
142
+ push_output_alias_flags(&mut expanded, alias, format, stdout_html, open_html);
143
+ }
144
+ Some(expanded)
145
+ }
146
+
147
+ fn push_output_alias_flags(
148
+ expanded: &mut Vec<OsString>,
149
+ alias: &str,
150
+ format: &str,
151
+ stdout_html: bool,
152
+ open_html: bool,
153
+ ) {
154
+ expanded.push(OsString::from("--format"));
155
+ expanded.push(OsString::from(format));
156
+ if alias == "html" && !stdout_html && !open_html {
157
+ expanded.push(OsString::from("--open"));
158
+ }
159
+ }
160
+
161
+ pub(super) fn output_alias_help_requested(args: &[OsString]) -> bool {
162
+ matches!(
163
+ args.get(1).and_then(|arg| arg.to_str()),
164
+ Some("human" | "json" | "html")
165
+ ) && args
166
+ .iter()
167
+ .skip(2)
168
+ .take_while(|arg| !is_delimiter(arg))
169
+ .any(is_help_arg)
170
+ }
171
+
172
+ pub(super) fn json_output_alias_requested(args: &[OsString]) -> bool {
173
+ args.get(1).and_then(|arg| arg.to_str()) == Some("json")
174
+ && !args
175
+ .iter()
176
+ .skip(2)
177
+ .take_while(|arg| !is_delimiter(arg))
178
+ .any(is_help_arg)
179
+ }
180
+
181
+ fn is_report_format(value: &str) -> bool {
182
+ REPORT_FORMAT_VALUES.contains(&value)
183
+ }
184
+
185
+ pub(super) fn is_help_arg(arg: &OsString) -> bool {
186
+ arg.to_str()
187
+ .is_some_and(|value| matches!(value, "-h" | "--help"))
188
+ }
189
+
190
+ fn is_delimiter(arg: &OsString) -> bool {
191
+ arg == "--"
192
+ }
193
+
54
194
  fn should_insert_check(args: &[OsString]) -> bool {
55
195
  let Some(first) = args.get(1).and_then(|arg| arg.to_str()) else {
56
196
  return args.len() == 1;
@@ -58,12 +198,170 @@ fn should_insert_check(args: &[OsString]) -> bool {
58
198
  if matches!(first, "-h" | "--help" | "-V" | "--version") {
59
199
  return false;
60
200
  }
61
- first_non_flag(args).is_none_or(|candidate| !COMMANDS.contains(&candidate))
201
+ !COMMANDS.contains(&first)
62
202
  }
63
203
 
64
- fn first_non_flag(args: &[OsString]) -> Option<&str> {
65
- args.iter()
66
- .skip(1)
67
- .filter_map(|arg| arg.to_str())
68
- .find(|arg| !arg.starts_with('-'))
204
+ #[cfg(test)]
205
+ mod tests {
206
+ use super::*;
207
+
208
+ fn values(items: &[&str]) -> Vec<OsString> {
209
+ items.iter().map(OsString::from).collect()
210
+ }
211
+
212
+ #[test]
213
+ fn output_aliases_expand_to_check_formats() {
214
+ assert_eq!(
215
+ args_with_default_check(["dart-decimate", "human", "app"]),
216
+ values(&["dart-decimate", "check", "app", "--format", "human"])
217
+ );
218
+ assert_eq!(
219
+ args_with_default_check(["dart-decimate", "json", "app", "--format", "human"]),
220
+ values(&["dart-decimate", "check", "app", "--format", "json"])
221
+ );
222
+ }
223
+
224
+ #[test]
225
+ fn output_aliases_preserve_malformed_explicit_format_errors() {
226
+ assert_eq!(
227
+ args_with_default_check(["dart-decimate", "json", "app", "--format"]),
228
+ values(&["dart-decimate", "check", "app", "--format"])
229
+ );
230
+ assert_eq!(
231
+ args_with_default_check(["dart-decimate", "json", "app", "--format", "--quiet"]),
232
+ values(&["dart-decimate", "check", "app", "--format", "--quiet"])
233
+ );
234
+ }
235
+
236
+ #[test]
237
+ fn output_aliases_preserve_invalid_explicit_format_errors() {
238
+ for alias in ["human", "json", "html"] {
239
+ assert_eq!(
240
+ args_with_default_check(["dart-decimate", alias, "app", "--format", "xml"]),
241
+ values(&["dart-decimate", "check", "app", "--format", "xml"])
242
+ );
243
+ assert_eq!(
244
+ args_with_default_check(["dart-decimate", alias, "app", "--format=xml"]),
245
+ values(&["dart-decimate", "check", "app", "--format=xml"])
246
+ );
247
+ }
248
+ }
249
+
250
+ #[test]
251
+ fn output_aliases_keep_check_flags_with_invalid_explicit_format_errors() {
252
+ assert_eq!(
253
+ args_with_default_check([
254
+ "dart-decimate",
255
+ "json",
256
+ "app",
257
+ "--file",
258
+ "lib/main.dart",
259
+ "--format",
260
+ "xml",
261
+ ]),
262
+ values(&[
263
+ "dart-decimate",
264
+ "check",
265
+ "app",
266
+ "--file",
267
+ "lib/main.dart",
268
+ "--format",
269
+ "xml",
270
+ ])
271
+ );
272
+ }
273
+
274
+ #[test]
275
+ fn output_aliases_insert_forced_flags_before_delimiter() {
276
+ assert_eq!(
277
+ args_with_default_check(["dart-decimate", "json", "--", "app"]),
278
+ values(&["dart-decimate", "check", "--format", "json", "--", "app"])
279
+ );
280
+ assert_eq!(
281
+ args_with_default_check(["dart-decimate", "html", "--stdout", "--", "app"]),
282
+ values(&["dart-decimate", "check", "--format", "html", "--", "app"])
283
+ );
284
+ assert_eq!(
285
+ args_with_default_check(["dart-decimate", "html", "--", "app"]),
286
+ values(&[
287
+ "dart-decimate",
288
+ "check",
289
+ "--format",
290
+ "html",
291
+ "--open",
292
+ "--",
293
+ "app",
294
+ ])
295
+ );
296
+ }
297
+
298
+ #[test]
299
+ fn output_aliases_treat_help_after_delimiter_as_positional() {
300
+ assert_eq!(
301
+ args_with_default_check(["dart-decimate", "json", "--", "--help"]),
302
+ values(&["dart-decimate", "check", "--format", "json", "--", "--help",])
303
+ );
304
+ }
305
+
306
+ #[test]
307
+ fn html_alias_opens_unless_stdout_is_requested() {
308
+ assert_eq!(
309
+ args_with_default_check(["dart-decimate", "html", "app"]),
310
+ values(&[
311
+ "dart-decimate",
312
+ "check",
313
+ "app",
314
+ "--format",
315
+ "html",
316
+ "--open",
317
+ ])
318
+ );
319
+ assert_eq!(
320
+ args_with_default_check(["dart-decimate", "html", "app", "--stdout"]),
321
+ values(&["dart-decimate", "check", "app", "--format", "html"])
322
+ );
323
+ }
324
+
325
+ #[test]
326
+ fn html_alias_does_not_duplicate_explicit_open() {
327
+ assert_eq!(
328
+ args_with_default_check(["dart-decimate", "html", "app", "--open"]),
329
+ values(&[
330
+ "dart-decimate",
331
+ "check",
332
+ "app",
333
+ "--open",
334
+ "--format",
335
+ "html",
336
+ ])
337
+ );
338
+ assert_eq!(
339
+ args_with_default_check(["dart-decimate", "html", "--open", "--", "app"]),
340
+ values(&[
341
+ "dart-decimate",
342
+ "check",
343
+ "--open",
344
+ "--format",
345
+ "html",
346
+ "--",
347
+ "app",
348
+ ])
349
+ );
350
+ }
351
+
352
+ #[test]
353
+ fn leading_format_values_do_not_block_default_check() {
354
+ assert_eq!(
355
+ args_with_default_check(["dart-decimate", "--format", "json"]),
356
+ values(&["dart-decimate", "check", "--format", "json"])
357
+ );
358
+ assert_eq!(
359
+ args_with_default_check(["dart-decimate", "--format", "html", "app"]),
360
+ values(&["dart-decimate", "check", "--format", "html", "app"])
361
+ );
362
+ assert_eq!(
363
+ args_with_default_check(["dart-decimate", "--format=json", "app"]),
364
+ values(&["dart-decimate", "check", "--format=json", "app"])
365
+ );
366
+ }
69
367
  }
package/src/cli/error.rs CHANGED
@@ -47,6 +47,9 @@ pub enum CliError {
47
47
  /// Cross-language duplicate detection is JavaScript/TypeScript-specific in Fallow.
48
48
  #[error("dupes --cross-language is not supported for Dart-only analysis")]
49
49
  UnsupportedCrossLanguageDupes,
50
+ /// Browser opening only applies to HTML report output.
51
+ #[error("--open only supports HTML reports; use --open by itself or --format html --open")]
52
+ HtmlOpenRequiresHtml,
50
53
  /// User-level agent hook installation is intentionally not supported.
51
54
  #[error(
52
55
  "setup-hooks --user is not supported; Dart Decimate only manages repo-local agent hooks"
@@ -3,7 +3,7 @@ use std::io::{self, Write};
3
3
 
4
4
  use serde::Serialize;
5
5
 
6
- use super::{CliError, run_from};
6
+ use super::{CliError, default_command, run_from};
7
7
 
8
8
  /// Run Dart Decimate from process arguments and return an exit code.
9
9
  #[must_use]
@@ -36,7 +36,15 @@ pub fn run_from_env() -> i32 {
36
36
  }
37
37
 
38
38
  fn format_json_requested(args: &[OsString]) -> bool {
39
- let mut args = args.iter().skip(1).filter_map(|arg| arg.to_str());
39
+ if default_command::output_alias_help_requested(args) {
40
+ return false;
41
+ }
42
+ if default_command::json_output_alias_requested(args) {
43
+ return true;
44
+ }
45
+
46
+ let expanded_args = default_command::args_with_default_check(args.iter().cloned());
47
+ let mut args = expanded_args.iter().skip(1).filter_map(|arg| arg.to_str());
40
48
  while let Some(arg) = args.next() {
41
49
  if arg == "--format" && args.next().is_some_and(|value| value == "json") {
42
50
  return true;
@@ -0,0 +1,240 @@
1
+ use std::fmt::Write as FmtWrite;
2
+ use std::io::{self, Write};
3
+ use std::path::{Path, PathBuf};
4
+ use std::process::Command;
5
+
6
+ use tempfile::Builder;
7
+
8
+ use crate::output::{JsonReport, render_html_report};
9
+
10
+ pub(super) fn write_and_open_html_report<W: Write>(
11
+ report: &JsonReport,
12
+ mut writer: W,
13
+ ) -> io::Result<()> {
14
+ write_and_open_html_document_with(
15
+ report.command.as_str(),
16
+ &render_html_report(report),
17
+ &mut writer,
18
+ open_url,
19
+ )
20
+ }
21
+
22
+ pub(super) fn write_and_open_html_document_with<W, F>(
23
+ command: &str,
24
+ html: &str,
25
+ writer: &mut W,
26
+ opener: F,
27
+ ) -> io::Result<()>
28
+ where
29
+ W: Write,
30
+ F: FnOnce(&str) -> io::Result<()>,
31
+ {
32
+ let path = write_temp_html_document(command, html)?;
33
+ let url = file_url(&path);
34
+ opener(&url)?;
35
+ writeln!(writer, "Opened HTML report: {url}")?;
36
+ Ok(())
37
+ }
38
+
39
+ fn write_temp_html_document(command: &str, html: &str) -> io::Result<PathBuf> {
40
+ let prefix = format!("dart-decimate-{}-", safe_filename_part(command));
41
+ let mut file = Builder::new()
42
+ .prefix(&prefix)
43
+ .suffix(".html")
44
+ .tempfile_in(std::env::temp_dir())?;
45
+ file.write_all(html.as_bytes())?;
46
+ file.as_file_mut().flush()?;
47
+ let (_file, path) = file.keep().map_err(|error| error.error)?;
48
+ Ok(path)
49
+ }
50
+
51
+ fn safe_filename_part(value: &str) -> String {
52
+ value
53
+ .chars()
54
+ .map(|character| {
55
+ if character.is_ascii_alphanumeric() || character == '-' {
56
+ character
57
+ } else {
58
+ '-'
59
+ }
60
+ })
61
+ .collect()
62
+ }
63
+
64
+ fn file_url(path: &Path) -> String {
65
+ let raw = path.to_string_lossy().replace('\\', "/");
66
+ let encoded = percent_encode_path(&raw);
67
+ if encoded.starts_with('/') {
68
+ format!("file://{encoded}")
69
+ } else {
70
+ format!("file:///{encoded}")
71
+ }
72
+ }
73
+
74
+ fn percent_encode_path(path: &str) -> String {
75
+ let mut encoded = String::with_capacity(path.len());
76
+ for byte in path.bytes() {
77
+ match byte {
78
+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'/' | b':' | b'-' | b'_' | b'.' | b'~' => {
79
+ encoded.push(byte as char);
80
+ }
81
+ _ => {
82
+ let _ = write!(encoded, "%{byte:02X}");
83
+ }
84
+ }
85
+ }
86
+ encoded
87
+ }
88
+
89
+ pub(super) fn open_url(url: &str) -> io::Result<()> {
90
+ let command = open_command(url, OpenPlatform::current());
91
+ let status = Command::new(command.program).args(command.args).status()?;
92
+
93
+ if status.success() {
94
+ Ok(())
95
+ } else {
96
+ Err(io::Error::other(format!(
97
+ "failed to open HTML report in browser: {status}"
98
+ )))
99
+ }
100
+ }
101
+
102
+ struct OpenCommand {
103
+ program: &'static str,
104
+ args: Vec<String>,
105
+ }
106
+
107
+ #[derive(Clone, Copy)]
108
+ enum OpenPlatform {
109
+ Macos,
110
+ Windows,
111
+ Other,
112
+ }
113
+
114
+ impl OpenPlatform {
115
+ fn current() -> Self {
116
+ if cfg!(target_os = "macos") {
117
+ Self::Macos
118
+ } else if cfg!(target_os = "windows") {
119
+ Self::Windows
120
+ } else {
121
+ Self::Other
122
+ }
123
+ }
124
+ }
125
+
126
+ fn open_command(url: &str, platform: OpenPlatform) -> OpenCommand {
127
+ match platform {
128
+ OpenPlatform::Macos => OpenCommand {
129
+ program: "open",
130
+ args: vec![url.to_owned()],
131
+ },
132
+ OpenPlatform::Windows => OpenCommand {
133
+ program: "explorer.exe",
134
+ args: vec![url.to_owned()],
135
+ },
136
+ OpenPlatform::Other => OpenCommand {
137
+ program: "xdg-open",
138
+ args: vec![url.to_owned()],
139
+ },
140
+ }
141
+ }
142
+
143
+ #[cfg(test)]
144
+ mod tests {
145
+ use std::cell::RefCell;
146
+ use std::fs;
147
+
148
+ use crate::output::{ReportCommand, ReportSummary, Verdict};
149
+
150
+ use super::*;
151
+
152
+ #[test]
153
+ fn file_urls_are_percent_encoded() {
154
+ let url = file_url(Path::new("/tmp/dart-decimate/report <1>.html"));
155
+
156
+ assert_eq!(url, "file:///tmp/dart-decimate/report%20%3C1%3E.html");
157
+ }
158
+
159
+ #[test]
160
+ fn windows_open_command_preserves_encoded_file_url() {
161
+ let url = "file:///C:/Users/Ada%20Lovelace/report%20%C3%A9.html";
162
+ let command = open_command(url, OpenPlatform::Windows);
163
+
164
+ assert_eq!(command.program, "explorer.exe");
165
+ assert_eq!(command.args, vec![url.to_owned()]);
166
+ }
167
+
168
+ #[test]
169
+ fn temp_html_documents_use_random_unique_names() -> Result<(), Box<dyn std::error::Error>> {
170
+ let first = write_temp_html_document("audit --brief", "<!doctype html>first")?;
171
+ let second = write_temp_html_document("audit --brief", "<!doctype html>second")?;
172
+
173
+ assert_ne!(first, second);
174
+ assert_eq!(fs::read_to_string(&first)?, "<!doctype html>first");
175
+ assert_eq!(fs::read_to_string(&second)?, "<!doctype html>second");
176
+ assert!(first.file_name().is_some_and(|name| {
177
+ let name = name.to_string_lossy();
178
+ name.starts_with("dart-decimate-audit---brief-") && name.ends_with(".html")
179
+ }));
180
+ Ok(())
181
+ }
182
+
183
+ #[cfg(unix)]
184
+ #[test]
185
+ fn temp_html_documents_are_private() -> Result<(), Box<dyn std::error::Error>> {
186
+ use std::os::unix::fs::PermissionsExt;
187
+
188
+ let path = write_temp_html_document("check", "<!doctype html>private")?;
189
+ let mode = fs::metadata(path)?.permissions().mode() & 0o777;
190
+
191
+ assert_eq!(mode, 0o600);
192
+ Ok(())
193
+ }
194
+
195
+ #[test]
196
+ fn writes_temp_html_and_opens_file_url() -> Result<(), Box<dyn std::error::Error>> {
197
+ let report = JsonReport {
198
+ schema_version: "dart-decimate.report.v1".to_owned(),
199
+ kind: "combined".to_owned(),
200
+ tool: "dart-decimate".to_owned(),
201
+ command: ReportCommand::Check,
202
+ verdict: Verdict::Pass,
203
+ summary: ReportSummary {
204
+ files: 1,
205
+ ..ReportSummary::default()
206
+ },
207
+ findings: Vec::new(),
208
+ clone_groups: Vec::new(),
209
+ complexity: Vec::new(),
210
+ file_scores: Vec::new(),
211
+ hotspots: Vec::new(),
212
+ refactoring_targets: Vec::new(),
213
+ threshold_overrides: Vec::new(),
214
+ feature_flags: Vec::new(),
215
+ security_candidates: Vec::new(),
216
+ attack_surface: Vec::new(),
217
+ runtime_coverage: None,
218
+ next_steps: Vec::new(),
219
+ };
220
+ let opened = RefCell::new(String::new());
221
+ let mut output = Vec::new();
222
+
223
+ let result = write_and_open_html_document_with(
224
+ report.command.as_str(),
225
+ &render_html_report(&report),
226
+ &mut output,
227
+ |url| {
228
+ opened.replace(url.to_owned());
229
+ Ok(())
230
+ },
231
+ );
232
+ assert!(result.is_ok());
233
+
234
+ let opened = opened.into_inner();
235
+ assert!(opened.starts_with("file:///"));
236
+ let message = String::from_utf8(output)?;
237
+ assert!(message.contains("Opened HTML report: file:///"));
238
+ Ok(())
239
+ }
240
+ }
@@ -35,6 +35,9 @@ pub(super) fn run_inspect_request<W: Write>(
35
35
  serde_json::to_writer_pretty(&mut writer, &report)?;
36
36
  writeln!(writer)?;
37
37
  }
38
+ ReportOutputFormat::Html | ReportOutputFormat::HtmlOpen => {
39
+ unreachable!("HTML is rejected before inspect rendering")
40
+ }
38
41
  ReportOutputFormat::Sarif => unreachable!("SARIF is rejected before inspect rendering"),
39
42
  }
40
43
 
@@ -11,6 +11,8 @@ pub(super) enum OutputFormat {
11
11
  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
12
12
  pub(super) enum ReportOutputFormat {
13
13
  Human,
14
+ Html,
15
+ HtmlOpen,
14
16
  Json,
15
17
  Sarif,
16
18
  }
@@ -55,6 +57,7 @@ fn report_output_format_value(subcommand: &ArgMatches) -> ReportOutputFormat {
55
57
  .get_one::<String>("format")
56
58
  .map_or("human", String::as_str)
57
59
  {
60
+ "html" => ReportOutputFormat::Html,
58
61
  "json" => ReportOutputFormat::Json,
59
62
  "sarif" => ReportOutputFormat::Sarif,
60
63
  _ => ReportOutputFormat::Human,