@robhowley/pi-structured-return 1.10.1 → 2.0.0

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 (110) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -83
  3. package/extensions/structured-return/config/registry.ts +4 -30
  4. package/extensions/structured-return/index.ts +105 -76
  5. package/extensions/structured-return/native.ts +223 -0
  6. package/extensions/structured-return/parsers/ava-text.ts +2 -168
  7. package/extensions/structured-return/parsers/bandit-json.ts +2 -79
  8. package/extensions/structured-return/parsers/black-text.ts +2 -73
  9. package/extensions/structured-return/parsers/cargo-build.ts +2 -78
  10. package/extensions/structured-return/parsers/cargo-test.ts +2 -135
  11. package/extensions/structured-return/parsers/checkstyle-xml.ts +2 -182
  12. package/extensions/structured-return/parsers/clang-text.ts +2 -60
  13. package/extensions/structured-return/parsers/dbt-json.ts +2 -135
  14. package/extensions/structured-return/parsers/dotnet-build-text.ts +2 -49
  15. package/extensions/structured-return/parsers/eslint-json.ts +2 -38
  16. package/extensions/structured-return/parsers/go-test-json.ts +2 -138
  17. package/extensions/structured-return/parsers/hadolint-json.ts +2 -60
  18. package/extensions/structured-return/parsers/htmlhint-json.ts +2 -73
  19. package/extensions/structured-return/parsers/isort-text.ts +2 -63
  20. package/extensions/structured-return/parsers/javac-text.ts +2 -82
  21. package/extensions/structured-return/parsers/jsonlint-text.ts +2 -65
  22. package/extensions/structured-return/parsers/junit-xml.ts +2 -325
  23. package/extensions/structured-return/parsers/markdownlint-json.ts +2 -74
  24. package/extensions/structured-return/parsers/minitest-text.ts +2 -107
  25. package/extensions/structured-return/parsers/mocha-json.ts +2 -83
  26. package/extensions/structured-return/parsers/mypy-json.ts +2 -79
  27. package/extensions/structured-return/parsers/node-test-text.ts +2 -92
  28. package/extensions/structured-return/parsers/npm-audit-json.ts +2 -90
  29. package/extensions/structured-return/parsers/prettier-text.ts +2 -66
  30. package/extensions/structured-return/parsers/pylint-json.ts +2 -63
  31. package/extensions/structured-return/parsers/pyright-json.ts +2 -82
  32. package/extensions/structured-return/parsers/rspec-json.ts +2 -75
  33. package/extensions/structured-return/parsers/rubocop-json.ts +2 -75
  34. package/extensions/structured-return/parsers/ruff-json.ts +2 -36
  35. package/extensions/structured-return/parsers/shellcheck-json.ts +2 -60
  36. package/extensions/structured-return/parsers/stylelint-json.ts +2 -75
  37. package/extensions/structured-return/parsers/swiftc-text.ts +2 -52
  38. package/extensions/structured-return/parsers/tail-fallback.ts +2 -19
  39. package/extensions/structured-return/parsers/tidy-text.ts +2 -66
  40. package/extensions/structured-return/parsers/tsc-text.ts +2 -46
  41. package/extensions/structured-return/parsers/unittest-text.ts +2 -125
  42. package/extensions/structured-return/parsers/utils.ts +28 -0
  43. package/extensions/structured-return/parsers/vale-json.ts +2 -79
  44. package/extensions/structured-return/parsers/vitest-json.ts +2 -59
  45. package/extensions/structured-return/storage/log-store.ts +0 -15
  46. package/extensions/structured-return/types.ts +1 -14
  47. package/native/Cargo.lock +193 -0
  48. package/native/Cargo.toml +21 -0
  49. package/native/THIRD-PARTY-LICENSES.txt +3660 -0
  50. package/native/bin/darwin-arm64/build.json +7 -0
  51. package/native/bin/darwin-arm64/structured-return-native +0 -0
  52. package/native/bin/darwin-x64/build.json +7 -0
  53. package/native/bin/darwin-x64/structured-return-native +0 -0
  54. package/native/bin/linux-arm64-musl/build.json +7 -0
  55. package/native/bin/linux-arm64-musl/structured-return-native +0 -0
  56. package/native/bin/linux-x64-musl/build.json +7 -0
  57. package/native/bin/linux-x64-musl/structured-return-native +0 -0
  58. package/native/src/common.rs +118 -0
  59. package/native/src/main.rs +55 -0
  60. package/native/src/parsers/ava_text.rs +125 -0
  61. package/native/src/parsers/bandit_json.rs +120 -0
  62. package/native/src/parsers/black_text.rs +45 -0
  63. package/native/src/parsers/cargo_build.rs +96 -0
  64. package/native/src/parsers/cargo_test.rs +140 -0
  65. package/native/src/parsers/checkstyle_xml.rs +137 -0
  66. package/native/src/parsers/clang_text.rs +39 -0
  67. package/native/src/parsers/compiler_helpers.rs +74 -0
  68. package/native/src/parsers/dbt_json.rs +243 -0
  69. package/native/src/parsers/dotnet_build_text.rs +50 -0
  70. package/native/src/parsers/eslint_json.rs +58 -0
  71. package/native/src/parsers/go_test_json.rs +346 -0
  72. package/native/src/parsers/hadolint_json.rs +37 -0
  73. package/native/src/parsers/htmlhint_json.rs +71 -0
  74. package/native/src/parsers/isort_text.rs +22 -0
  75. package/native/src/parsers/javac_text.rs +49 -0
  76. package/native/src/parsers/json_support.rs +287 -0
  77. package/native/src/parsers/jsonlint_text.rs +50 -0
  78. package/native/src/parsers/junit_xml.rs +430 -0
  79. package/native/src/parsers/markdownlint_json.rs +68 -0
  80. package/native/src/parsers/minitest_text.rs +91 -0
  81. package/native/src/parsers/mocha_json.rs +75 -0
  82. package/native/src/parsers/mod.rs +119 -0
  83. package/native/src/parsers/mypy_json.rs +93 -0
  84. package/native/src/parsers/node_test_text.rs +106 -0
  85. package/native/src/parsers/npm_audit_json.rs +119 -0
  86. package/native/src/parsers/prettier_text.rs +34 -0
  87. package/native/src/parsers/pylint_json.rs +44 -0
  88. package/native/src/parsers/pyright_json.rs +88 -0
  89. package/native/src/parsers/rspec_json.rs +84 -0
  90. package/native/src/parsers/rubocop_json.rs +46 -0
  91. package/native/src/parsers/ruff_json.rs +30 -0
  92. package/native/src/parsers/shellcheck_json.rs +40 -0
  93. package/native/src/parsers/stylelint_json.rs +46 -0
  94. package/native/src/parsers/swiftc_text.rs +38 -0
  95. package/native/src/parsers/tail_fallback.rs +51 -0
  96. package/native/src/parsers/test_helpers.rs +172 -0
  97. package/native/src/parsers/tidy_text.rs +77 -0
  98. package/native/src/parsers/tsc_text.rs +28 -0
  99. package/native/src/parsers/unittest_text.rs +125 -0
  100. package/native/src/parsers/vale_json.rs +66 -0
  101. package/native/src/parsers/vitest_json.rs +71 -0
  102. package/native/src/parsers/xml_support.rs +241 -0
  103. package/native/src/runner.rs +252 -0
  104. package/package.json +20 -6
  105. package/scripts/build-native.mjs +73 -0
  106. package/scripts/native-artifacts.mjs +69 -0
  107. package/skills/structured-return/SKILL.md +103 -249
  108. package/extensions/structured-return/config/project-config.ts +0 -10
  109. package/extensions/structured-return/examples/.pi/machine-readable.json +0 -18
  110. package/extensions/structured-return/examples/.pi/parsers/foo-cli.ts +0 -25
@@ -0,0 +1,140 @@
1
+ use crate::common::{read_file, relative, result, Context};
2
+ use regex::Regex;
3
+ use serde_json::{json, Map, Value};
4
+
5
+ fn format_message(lines: &[&str]) -> String {
6
+ if lines.is_empty() {
7
+ return String::new();
8
+ }
9
+ let left = lines
10
+ .iter()
11
+ .find(|line| line.trim_start().starts_with("left:"));
12
+ let right = lines
13
+ .iter()
14
+ .find(|line| line.trim_start().starts_with("right:"));
15
+ if let (Some(left), Some(right)) = (left, right) {
16
+ format!("{}\n{}, {}", lines[0], left.trim(), right.trim())
17
+ } else {
18
+ lines
19
+ .iter()
20
+ .copied()
21
+ .filter(|line| !line.is_empty())
22
+ .collect::<Vec<_>>()
23
+ .join("; ")
24
+ }
25
+ }
26
+
27
+ pub fn parse(ctx: &Context) -> Result<Value, String> {
28
+ let log = read_file(&ctx.log_path)?;
29
+ let lines: Vec<_> = log.split('\n').map(str::trim).collect();
30
+ let count_re =
31
+ Regex::new(r"^test result: [A-Za-z0-9_]+\. ([0-9]+) passed; ([0-9]+) failed").unwrap();
32
+ let header_re = Regex::new(r"^---- (.+) stdout ----$").unwrap();
33
+ let mut passed = 0_u64;
34
+ let mut failed = 0_u64;
35
+ let mut found_summary = false;
36
+ let mut captured_stdout = false;
37
+ for line in &lines {
38
+ if header_re.is_match(line) {
39
+ captured_stdout = true;
40
+ } else if *line == "failures:" || *line == "successes:" {
41
+ captured_stdout = false;
42
+ } else if !captured_stdout {
43
+ if let Some(m) = count_re.captures(line) {
44
+ // Sum each binary/doc-test footer, not saved summaries printed
45
+ // inside a test's captured stdout.
46
+ found_summary = true;
47
+ passed += m[1].parse::<u64>().unwrap_or(0);
48
+ failed += m[2].parse::<u64>().unwrap_or(0);
49
+ }
50
+ }
51
+ }
52
+ if !found_summary {
53
+ return Ok(result(
54
+ "cargo",
55
+ "error",
56
+ "compilation failed — run `cargo build --message-format=json` for structured errors",
57
+ Vec::new(),
58
+ ctx,
59
+ ));
60
+ }
61
+ let new_re =
62
+ Regex::new(r"^thread '.+?' (?:\([0-9]+\) )?panicked at (.+?):([0-9]+):[0-9]+:?$").unwrap();
63
+ let old_re = Regex::new(r"(?s)thread '.+?' panicked at '(.*)', (.+?):([0-9]+):[0-9]+").unwrap();
64
+ let whitespace = Regex::new(r"\s+").unwrap();
65
+ let mut blocks: Vec<(String, Vec<&str>)> = Vec::new();
66
+ for line in &lines {
67
+ if let Some(m) = header_re.captures(line) {
68
+ blocks.push((m[1].to_owned(), Vec::new()));
69
+ } else if let Some((_, block)) = blocks.last_mut() {
70
+ block.push(line);
71
+ }
72
+ }
73
+ let mut failures = Vec::new();
74
+ for (name, lines) in blocks {
75
+ let mut file: Option<String> = None;
76
+ let mut line_number: Option<u64> = None;
77
+ let mut message = None;
78
+ for (i, line) in lines.iter().enumerate() {
79
+ if let Some(m) = new_re.captures(line) {
80
+ file = Some(relative(&ctx.cwd, &m[1]));
81
+ line_number = Some(m[2].parse().unwrap_or(0));
82
+ let following: Vec<_> = lines
83
+ .iter()
84
+ .skip(i + 1)
85
+ .copied()
86
+ .take_while(|line| {
87
+ !line.is_empty()
88
+ && !line.starts_with("note:")
89
+ && !line.starts_with("error:")
90
+ })
91
+ .collect();
92
+ message = Some(format_message(&following));
93
+ break;
94
+ }
95
+ }
96
+ if file.as_ref().is_none_or(String::is_empty) {
97
+ if let Some(m) = old_re.captures(&lines.join("\n")) {
98
+ message = Some(whitespace.replace_all(&m[1], " ").trim().to_owned());
99
+ file = Some(relative(&ctx.cwd, &m[2]));
100
+ line_number = Some(m[3].parse().unwrap_or(0));
101
+ }
102
+ }
103
+ let mut parts = Vec::new();
104
+ if let Some(file) = file.as_ref().filter(|s| !s.is_empty()) {
105
+ parts.push(file.clone());
106
+ }
107
+ if let Some(line) = line_number.filter(|n| *n != 0) {
108
+ parts.push(line.to_string());
109
+ }
110
+ if !name.is_empty() {
111
+ parts.push(name.clone());
112
+ }
113
+ let id = if parts.is_empty() {
114
+ name.clone()
115
+ } else {
116
+ parts.join(":")
117
+ };
118
+ let mut value = Map::new();
119
+ value.insert("id".to_owned(), json!(id));
120
+ if let Some(file) = file {
121
+ value.insert("file".to_owned(), json!(file));
122
+ }
123
+ if let Some(line) = line_number {
124
+ value.insert("line".to_owned(), json!(line));
125
+ }
126
+ value.insert("message".to_owned(), json!(message.unwrap_or(name)));
127
+ failures.push(Value::Object(value));
128
+ }
129
+ Ok(result(
130
+ "cargo",
131
+ if failed > 0 { "fail" } else { "pass" },
132
+ if failed > 0 {
133
+ format!("{failed} failed, {passed} passed")
134
+ } else {
135
+ format!("{passed} passed")
136
+ },
137
+ failures,
138
+ ctx,
139
+ ))
140
+ }
@@ -0,0 +1,137 @@
1
+ use super::json_support::{num_string, num_value, number_text, optional_string};
2
+ use super::xml_support::parse_xml;
3
+ use crate::common::{read_file, relative, result, Context};
4
+ use regex::Regex;
5
+ use serde_json::{Map, Value};
6
+ use std::{path::Path, sync::LazyLock};
7
+
8
+ static RULE: LazyLock<Regex> =
9
+ LazyLock::new(|| Regex::new(r"\.([A-Z][a-zA-Z0-9]*Check)$").unwrap());
10
+ fn normalize_rule(source: Option<&str>) -> Option<String> {
11
+ let source = source.filter(|s| !s.is_empty())?;
12
+ if source.contains(':') {
13
+ return Some(source.into());
14
+ }
15
+ Some(
16
+ RULE.captures(source)
17
+ .map(|m| m[1].to_owned())
18
+ .unwrap_or_else(|| source.into()),
19
+ )
20
+ }
21
+ fn category(severity: Option<&str>) -> &'static str {
22
+ match severity.unwrap_or("").to_lowercase().as_str() {
23
+ "" | "error" | "critical" | "fatal" => "error",
24
+ "warning" | "warn" => "warning",
25
+ "info" | "information" => "info",
26
+ _ => "unknown",
27
+ }
28
+ }
29
+ pub fn parse(ctx: &Context) -> Result<Value, String> {
30
+ let sources: Vec<&str> = if ctx.artifact_paths.is_empty() {
31
+ vec![&ctx.stdout_path]
32
+ } else {
33
+ ctx.artifact_paths.iter().map(String::as_str).collect()
34
+ };
35
+ let mut failures = Vec::new();
36
+ let mut invalid_report = false;
37
+ let (mut errors, mut warnings, mut info) = (0, 0, 0);
38
+ for source in sources {
39
+ let doc = match read_file(source).and_then(|xml| parse_xml(&xml)) {
40
+ Ok(doc) => doc,
41
+ Err(_) => {
42
+ invalid_report = true;
43
+ continue;
44
+ }
45
+ };
46
+ let Some(report) = doc.child("checkstyle") else {
47
+ invalid_report = true;
48
+ continue;
49
+ };
50
+ for file in report.children_named("file") {
51
+ let Some(name) = file.attr("name").filter(|s| !s.is_empty()) else {
52
+ continue;
53
+ };
54
+ let file_name = if Path::new(name).is_absolute() {
55
+ relative(&ctx.cwd, name)
56
+ } else {
57
+ name.into()
58
+ };
59
+ for error in file.children_named("error") {
60
+ if error.attr("severity") == Some("ignore") {
61
+ continue;
62
+ }
63
+ let line = error.attr("line").map(number_text);
64
+ let column = error.attr("column").map(number_text);
65
+ let rule = normalize_rule(error.attr("source"));
66
+ let severity = category(error.attr("severity"));
67
+ match severity {
68
+ "error" => errors += 1,
69
+ "warning" => warnings += 1,
70
+ "info" => info += 1,
71
+ _ => {}
72
+ }
73
+ let mut out = Map::new();
74
+ out.insert(
75
+ "id".into(),
76
+ Value::String(format!(
77
+ "{}:{}:{}",
78
+ file_name,
79
+ num_string(line.unwrap_or(0.0)),
80
+ rule.as_deref().unwrap_or("unknown")
81
+ )),
82
+ );
83
+ out.insert("file".into(), Value::String(file_name.clone()));
84
+ if let Some(n) = line {
85
+ out.insert("line".into(), num_value(n));
86
+ }
87
+ if let Some(n) = column {
88
+ out.insert("column".into(), num_value(n));
89
+ }
90
+ optional_string(
91
+ &mut out,
92
+ "message",
93
+ error
94
+ .attr("message")
95
+ .map(str::trim)
96
+ .filter(|s| !s.is_empty())
97
+ .map(str::to_owned),
98
+ );
99
+ optional_string(&mut out, "rule", rule);
100
+ if severity != "unknown" && error.attr("severity").is_some_and(|s| !s.is_empty()) {
101
+ out.insert("severity".into(), Value::String(severity.into()));
102
+ }
103
+ failures.push(Value::Object(out));
104
+ }
105
+ }
106
+ }
107
+ if invalid_report {
108
+ return Ok(result(
109
+ "checkstyle",
110
+ "error",
111
+ "failed to parse checkstyle XML output",
112
+ failures,
113
+ ctx,
114
+ ));
115
+ }
116
+ let status = if errors > 0 || warnings > 0 {
117
+ "fail"
118
+ } else {
119
+ "pass"
120
+ };
121
+ let summary = if failures.is_empty() {
122
+ "no lint errors".into()
123
+ } else {
124
+ let mut parts = Vec::new();
125
+ if errors > 0 {
126
+ parts.push(format!("{errors} errors"));
127
+ }
128
+ if warnings > 0 {
129
+ parts.push(format!("{warnings} warnings"));
130
+ }
131
+ if info > 0 {
132
+ parts.push(format!("{info} info"));
133
+ }
134
+ format!("{} findings ({})", failures.len(), parts.join(", "))
135
+ };
136
+ Ok(result("checkstyle", status, summary, failures, ctx))
137
+ }
@@ -0,0 +1,39 @@
1
+ use super::compiler_helpers::{errors, node_relative, number, regex, status, trim};
2
+ use crate::common::{read_file, result, Context};
3
+ use serde_json::{json, Value};
4
+
5
+ pub fn parse(ctx: &Context) -> Result<Value, String> {
6
+ let stderr = read_file(&ctx.stderr_path)?;
7
+ let issue = regex(r"^(.+?):(\d+):\d+: (error|fatal error): (.+?)(\s+\[-.+\])?$");
8
+ let driver_issue =
9
+ regex(r"^(?:clang(?:\+\+)?(?:-[0-9.]+)?|gcc|g\+\+|cc|c\+\+): (?:fatal )?error: (.+)$");
10
+ let summary_pattern = regex(r"^(\d+) errors? generated");
11
+ let mut failures = Vec::new();
12
+ let mut summary_line = String::new();
13
+ for line in trim(&stderr).lines() {
14
+ if let Some(m) = issue.captures(line) {
15
+ let file = node_relative(&ctx.cwd, &m[1])?;
16
+ let mut failure = json!({"id":format!("{file}:{}",&m[2]),"file":file,"line":number(&m[2]),"message":&m[4]});
17
+ if let Some(flag) = m.get(5) {
18
+ let flag = trim(flag.as_str());
19
+ let flag = flag.strip_prefix('[').unwrap_or(flag);
20
+ let flag = flag.strip_suffix(']').unwrap_or(flag);
21
+ failure["rule"] = Value::String(flag.to_owned());
22
+ }
23
+ failures.push(failure);
24
+ continue;
25
+ }
26
+ if let Some(m) = driver_issue.captures(line) {
27
+ failures.push(json!({"id":&m[1],"message":&m[1]}));
28
+ }
29
+ if summary_pattern.is_match(line) {
30
+ summary_line = line.to_owned();
31
+ }
32
+ }
33
+ let summary = if summary_line.is_empty() {
34
+ errors(failures.len(), "compilation successful")
35
+ } else {
36
+ summary_line
37
+ };
38
+ Ok(result("clang", status(&failures), summary, failures, ctx))
39
+ }
@@ -0,0 +1,74 @@
1
+ use crate::common::relative;
2
+ use regex::Regex;
3
+ use serde_json::{Number, Value};
4
+ use std::path::Path;
5
+
6
+ pub use crate::common::trim;
7
+
8
+ /// Preserve JavaScript's non-Unicode RegExp character classes and dot semantics.
9
+ pub fn regex(source: &str) -> Regex {
10
+ let mut pattern = String::new();
11
+ let mut chars = source.chars();
12
+ let mut in_class = false;
13
+ while let Some(c) = chars.next() {
14
+ if c == '\\' {
15
+ match chars.next() {
16
+ Some('d') => pattern.push_str("[0-9]"),
17
+ Some('w') => pattern.push_str("[A-Za-z0-9_]"),
18
+ Some('s') => pattern.push_str(r"[\x09-\x0D \u{00A0}\u{1680}\u{2000}-\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{FEFF}]"),
19
+ Some('S') => pattern.push_str(r"[^\x09-\x0D \u{00A0}\u{1680}\u{2000}-\u{200A}\u{2028}\u{2029}\u{202F}\u{205F}\u{3000}\u{FEFF}]"),
20
+ Some(next) => { pattern.push('\\'); pattern.push(next); },
21
+ None => pattern.push('\\'),
22
+ }
23
+ } else {
24
+ if c == '[' {
25
+ in_class = true;
26
+ }
27
+ if c == ']' {
28
+ in_class = false;
29
+ }
30
+ if c == '.' && !in_class {
31
+ pattern.push_str(r"[^\r\n\u{2028}\u{2029}]");
32
+ } else {
33
+ pattern.push(c);
34
+ }
35
+ }
36
+ }
37
+ Regex::new(&pattern).expect("constant JavaScript-compatible pattern")
38
+ }
39
+
40
+ pub fn number(text: &str) -> Value {
41
+ text.parse::<f64>()
42
+ .ok()
43
+ .and_then(Number::from_f64)
44
+ .map(Value::Number)
45
+ .unwrap_or(Value::Null)
46
+ }
47
+
48
+ /// Resolve report paths against the command directory, independent of Pi's cwd.
49
+ pub fn node_relative(cwd: &str, file: &str) -> Result<String, String> {
50
+ Ok(relative(cwd, file))
51
+ }
52
+ pub fn relative_if_absolute(cwd: &str, file: &str) -> String {
53
+ if Path::new(file).is_absolute() {
54
+ relative(cwd, file)
55
+ } else {
56
+ file.to_owned()
57
+ }
58
+ }
59
+
60
+ pub fn status(failures: &[Value]) -> &'static str {
61
+ if failures.is_empty() {
62
+ "pass"
63
+ } else {
64
+ "fail"
65
+ }
66
+ }
67
+
68
+ pub fn errors(count: usize, success: &str) -> String {
69
+ if count == 0 {
70
+ success.to_owned()
71
+ } else {
72
+ format!("{count} error{}", if count == 1 { "" } else { "s" })
73
+ }
74
+ }
@@ -0,0 +1,243 @@
1
+ use super::test_helpers::{js_string, number, optional};
2
+ use crate::common::{read_file, result, truthy, Context};
3
+ use regex::Regex;
4
+ use serde_json::{json, Map, Value};
5
+ use std::collections::HashMap;
6
+
7
+ fn info(event: &Value) -> Result<&Value, String> {
8
+ event
9
+ .get("info")
10
+ .filter(|v| !v.is_null())
11
+ .ok_or_else(|| "dbt event info is missing".to_owned())
12
+ }
13
+ fn data(event: &Value) -> Result<&Value, String> {
14
+ event
15
+ .get("data")
16
+ .filter(|v| !v.is_null())
17
+ .ok_or_else(|| "dbt event data is missing".to_owned())
18
+ }
19
+
20
+ fn compilation_failures(events: &[Value]) -> Result<Vec<Value>, String> {
21
+ let mut failures = Vec::new();
22
+ for event in events {
23
+ let event_info = info(event)?;
24
+ if event_info.get("level").and_then(Value::as_str) != Some("error") {
25
+ continue;
26
+ }
27
+ let mut failure = Map::new();
28
+ failure.insert("id".to_owned(), json!(failures.len().to_string()));
29
+ optional(&mut failure, "message", event_info.get("msg"));
30
+ failures.push(Value::Object(failure));
31
+ }
32
+ Ok(failures)
33
+ }
34
+
35
+ // Number.toFixed(2) rounds the exact binary value, with ties away from zero.
36
+ // Integer arithmetic avoids Rust's ties-to-even formatting and the extra
37
+ // rounding introduced by simply multiplying an f64 by 100 first.
38
+ fn fixed_two(value: f64) -> String {
39
+ if !value.is_finite() || value.abs() >= 1e21 {
40
+ return super::test_helpers::number_text(value);
41
+ }
42
+ let negative = value < 0.0;
43
+ let bits = value.abs().to_bits();
44
+ let raw_exp = ((bits >> 52) & 0x7ff) as i32;
45
+ let mut mantissa = (bits & ((1_u64 << 52) - 1)) as u128;
46
+ let exponent = if raw_exp == 0 {
47
+ -1074
48
+ } else {
49
+ mantissa |= 1_u128 << 52;
50
+ raw_exp - 1023 - 52
51
+ };
52
+ let numerator = mantissa * 100;
53
+ let rounded = if exponent >= 0 {
54
+ numerator << exponent
55
+ } else if -exponent >= 128 {
56
+ 0
57
+ } else {
58
+ let divisor = 1_u128 << (-exponent);
59
+ numerator / divisor + u128::from((numerator % divisor) * 2 >= divisor)
60
+ };
61
+ format!(
62
+ "{}{}.{:02}",
63
+ if negative { "-" } else { "" },
64
+ rounded / 100,
65
+ rounded % 100
66
+ )
67
+ }
68
+
69
+ pub fn parse(ctx: &Context) -> Result<Value, String> {
70
+ let raw = read_file(&ctx.stdout_path)?;
71
+ // SR-019: retain the first JSON event when the stream begins with a UTF-8 BOM.
72
+ let raw = raw.strip_prefix('\u{feff}').unwrap_or(&raw);
73
+ let mut events: Vec<Value> = Vec::new();
74
+ for line in raw.split('\n') {
75
+ if !line.trim().starts_with('{') {
76
+ continue;
77
+ }
78
+ if let Ok(value) = super::json_support::parse_json(line) {
79
+ events.push(value);
80
+ }
81
+ }
82
+ let mut summary = None;
83
+ let mut errors = Vec::new();
84
+ let mut warnings = Vec::new();
85
+ let mut compiled = Vec::new();
86
+ for event in &events {
87
+ match info(event)?.get("name").and_then(Value::as_str) {
88
+ Some("EndOfRunSummary") if summary.is_none() => summary = Some(event),
89
+ Some("RunResultError") => errors.push(event),
90
+ Some("RunResultWarning") => warnings.push(event),
91
+ Some("CompiledNode") => compiled.push(event),
92
+ _ => {}
93
+ }
94
+ }
95
+ if !compiled.is_empty() && summary.is_none() {
96
+ let mut names = Vec::new();
97
+ let mut sql_parts = Vec::new();
98
+ for event in &compiled {
99
+ let event_data = data(event)?;
100
+ let node = event_data.get("node_info").filter(|v| !v.is_null());
101
+ let name = node.and_then(|v| v.get("node_name"));
102
+ if let Some(name) = name.filter(|v| truthy(v)) {
103
+ names.push(js_string(Some(name)));
104
+ }
105
+ if let Some(sql) = event_data.get("compiled").filter(|v| truthy(v)) {
106
+ let name = name
107
+ .filter(|v| !v.is_null())
108
+ .map(|v| js_string(Some(v)))
109
+ .unwrap_or_else(|| "model".to_owned());
110
+ sql_parts.push(format!("-- {name}\n{}", js_string(Some(sql))));
111
+ }
112
+ }
113
+ let failures = compilation_failures(&events)?;
114
+ let compiled_summary = format!(
115
+ "compiled {} model{}: {}",
116
+ compiled.len(),
117
+ if compiled.len() == 1 { "" } else { "s" },
118
+ names.join(", ")
119
+ );
120
+ let summary = if failures.is_empty() {
121
+ compiled_summary
122
+ } else {
123
+ format!(
124
+ "{} error{}; {compiled_summary}",
125
+ failures.len(),
126
+ if failures.len() == 1 { "" } else { "s" }
127
+ )
128
+ };
129
+ let mut output = result(
130
+ "dbt",
131
+ if failures.is_empty() { "pass" } else { "error" },
132
+ summary,
133
+ failures,
134
+ ctx,
135
+ );
136
+ output
137
+ .as_object_mut()
138
+ .unwrap()
139
+ .insert("rawTail".to_owned(), json!(sql_parts.join("\n\n")));
140
+ return Ok(output);
141
+ }
142
+ let Some(summary) = summary else {
143
+ let failures = compilation_failures(&events)?;
144
+ let summary = if failures.is_empty() {
145
+ "failed".to_owned()
146
+ } else {
147
+ format!(
148
+ "{} error{}",
149
+ failures.len(),
150
+ if failures.len() == 1 { "" } else { "s" }
151
+ )
152
+ };
153
+ return Ok(result("dbt", "error", summary, failures, ctx));
154
+ };
155
+ let summary_info = info(summary)?;
156
+ let summary_data = data(summary)?;
157
+ let summary_message = summary_info
158
+ .get("msg")
159
+ .and_then(Value::as_str)
160
+ .ok_or("dbt summary message must be a string")?;
161
+ let count_re = Regex::new(r"([A-Za-z0-9_]+)=([0-9]+)").unwrap();
162
+ let mut counts = HashMap::new();
163
+ for m in count_re.captures_iter(summary_message) {
164
+ counts.insert(m[1].to_owned(), json!(m[2].parse::<f64>().unwrap_or(0.0)));
165
+ }
166
+ let zero = json!(0);
167
+ let count = |key: &str, fallback: &str| -> &Value {
168
+ counts
169
+ .get(key)
170
+ .or_else(|| summary_data.get(fallback).filter(|v| !v.is_null()))
171
+ .unwrap_or(&zero)
172
+ };
173
+ let num_errors = count("ERROR", "num_errors");
174
+ let num_warnings = count("WARN", "num_warnings");
175
+ let num_skipped = count("SKIP", "num_skipped");
176
+ let num_passed = counts.get("PASS").unwrap_or(&zero);
177
+ let elapsed = summary_data
178
+ .get("elapsed_time")
179
+ .filter(|v| !v.is_null())
180
+ .unwrap_or(&zero)
181
+ .as_f64()
182
+ .ok_or("dbt elapsed_time.toFixed is not a function")?;
183
+ let mut failures = Vec::new();
184
+ for (is_warning, events) in [(false, errors), (true, warnings)] {
185
+ for event in events {
186
+ let event_data = data(event)?;
187
+ let node = event_data.get("node_info").filter(|v| !v.is_null());
188
+ let name = node
189
+ .and_then(|v| v.get("node_name"))
190
+ .filter(|v| !v.is_null())
191
+ .cloned()
192
+ .unwrap_or_else(|| json!(failures.len().to_string()));
193
+ let message = event_data
194
+ .get("msg")
195
+ .filter(|v| !v.is_null())
196
+ .or_else(|| info(event).ok().and_then(|v| v.get("msg")));
197
+ let mut failure = Map::new();
198
+ failure.insert("id".to_owned(), name);
199
+ optional(&mut failure, "file", node.and_then(|v| v.get("node_path")));
200
+ if is_warning {
201
+ failure.insert(
202
+ "message".to_owned(),
203
+ json!(format!("[warn] {}", js_string(message))),
204
+ );
205
+ } else {
206
+ optional(&mut failure, "message", message);
207
+ }
208
+ failures.push(Value::Object(failure));
209
+ }
210
+ }
211
+ let mut parts = Vec::new();
212
+ if number(Some(num_errors)) > 0.0 {
213
+ parts.push(format!("{} failed", js_string(Some(num_errors))));
214
+ }
215
+ if number(Some(num_passed)) > 0.0 {
216
+ parts.push(format!("{} passed", js_string(Some(num_passed))));
217
+ }
218
+ if number(Some(num_warnings)) > 0.0 {
219
+ parts.push(format!(
220
+ "{} warning{}",
221
+ js_string(Some(num_warnings)),
222
+ if num_warnings.as_f64() == Some(1.0) {
223
+ ""
224
+ } else {
225
+ "s"
226
+ }
227
+ ));
228
+ }
229
+ if number(Some(num_skipped)) > 0.0 {
230
+ parts.push(format!("{} skipped", js_string(Some(num_skipped))));
231
+ }
232
+ Ok(result(
233
+ "dbt",
234
+ if number(Some(num_errors)) > 0.0 {
235
+ "fail"
236
+ } else {
237
+ "pass"
238
+ },
239
+ format!("{} in {}s", parts.join(", "), fixed_two(elapsed)),
240
+ failures,
241
+ ctx,
242
+ ))
243
+ }
@@ -0,0 +1,50 @@
1
+ use super::compiler_helpers::{errors, node_relative, number, regex, status, trim};
2
+ use crate::common::{read_file, result, Context};
3
+ use serde_json::{json, Value};
4
+ use std::collections::HashSet;
5
+
6
+ pub fn parse(ctx: &Context) -> Result<Value, String> {
7
+ let combined = read_file(&ctx.stdout_path)? + "\n" + &read_file(&ctx.stderr_path)?;
8
+ let issue = regex(r"^(.+?)\((\d+),(\d+)\): error (\w+): (.+?)(?:\s+\[.+\])?$");
9
+ let driver_issue = regex(r"^MSBUILD\s*:\s*error (\w+): (.+)$");
10
+ let mut seen = HashSet::new();
11
+ let mut failures = Vec::new();
12
+ for line in combined.split('\n') {
13
+ let line = trim(line);
14
+ if let Some(m) = driver_issue.captures(line) {
15
+ if seen.insert((
16
+ String::new(),
17
+ String::new(),
18
+ String::new(),
19
+ m[1].to_owned(),
20
+ m[2].to_owned(),
21
+ )) {
22
+ failures.push(json!({"id":&m[1],"rule":&m[1],"message":&m[2]}));
23
+ }
24
+ continue;
25
+ }
26
+ let Some(m) = issue.captures(line) else {
27
+ continue;
28
+ };
29
+ let file = node_relative(&ctx.cwd, &m[1])?;
30
+ let key = format!("{file}:{}:{}", &m[2], &m[4]);
31
+ if !seen.insert((
32
+ file.clone(),
33
+ m[2].to_owned(),
34
+ m[3].to_owned(),
35
+ m[4].to_owned(),
36
+ m[5].to_owned(),
37
+ )) {
38
+ continue;
39
+ }
40
+ failures
41
+ .push(json!({"id":key,"file":file,"line":number(&m[2]),"message":&m[5],"rule":&m[4]}));
42
+ }
43
+ Ok(result(
44
+ "dotnet build",
45
+ status(&failures),
46
+ errors(failures.len(), "build succeeded"),
47
+ failures,
48
+ ctx,
49
+ ))
50
+ }