use crate::types::TemplateLanguage;
use anyhow::Result;
use regex::Regex;
#[derive(Debug)]
pub struct ResponseParser {
markdown_block_start: Regex,
markdown_block_end: Regex,
}
impl ResponseParser {
pub fn new() -> Self {
Self {
markdown_block_start: Regex::new(r"```[\w]*\n?").unwrap(),
markdown_block_end: Regex::new(r"\n?```\s*$").unwrap(),
}
}
pub fn parse(&self, response: &str, language: TemplateLanguage) -> Result<String> {
tracing::debug!(
"Parsing response ({} chars) for {:?}",
response.len(),
language
);
tracing::trace!("Raw response: {}", response);
let cleaned = self.remove_markdown_blocks(response);
tracing::debug!("After markdown removal: {} chars", cleaned.len());
let cleaned = self.extract_code_only(&cleaned, language);
tracing::debug!("After code extraction: {} chars", cleaned.len());
tracing::trace!("Extracted code: {}", cleaned);
self.validate_basic_structure(&cleaned, language)?;
let result = cleaned.trim().to_string();
tracing::info!("Successfully parsed template: {} chars", result.len());
Ok(result)
}
fn remove_markdown_blocks(&self, text: &str) -> String {
let text = self.markdown_block_start.replace_all(text, "");
let text = self.markdown_block_end.replace_all(&text, "");
text.to_string()
}
fn extract_code_only(&self, text: &str, language: TemplateLanguage) -> String {
match language {
TemplateLanguage::Python => self.extract_python_code(text),
TemplateLanguage::JavaScript => self.extract_javascript_code(text),
TemplateLanguage::Yaml => self.extract_yaml_code(text),
TemplateLanguage::Rust => self.extract_rust_code(text),
TemplateLanguage::C => self.extract_c_code(text),
TemplateLanguage::Cpp => self.extract_cpp_code(text),
TemplateLanguage::Java => self.extract_java_code(text),
TemplateLanguage::Go => self.extract_go_code(text),
TemplateLanguage::Ruby => self.extract_ruby_code(text),
TemplateLanguage::Perl => self.extract_perl_code(text),
TemplateLanguage::Php => self.extract_php_code(text),
TemplateLanguage::Shell => self.extract_shell_code(text),
}
}
fn extract_python_code(&self, text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let start = lines
.iter()
.position(|line| {
let trimmed = line.trim();
trimmed.starts_with("#!/usr/bin/env python")
|| trimmed.starts_with("#!/usr/bin/python")
|| trimmed.starts_with("import ")
|| trimmed.starts_with("from ")
|| trimmed.starts_with("class ")
|| trimmed.starts_with("def ")
|| trimmed.starts_with("\"\"\"") })
.unwrap_or(0);
let mut end = lines.len();
for i in (start..lines.len()).rev() {
let trimmed = lines[i].trim();
if trimmed.is_empty() {
continue;
}
let prose_indicators = [
"Please note",
"Note that",
"This code",
"This template",
"This script",
"Remember to",
"Make sure",
"Don't forget",
"You can",
"To use this",
"To run this",
"For more information",
"Example usage:",
"Usage:",
"Output:",
];
let is_prose = prose_indicators
.iter()
.any(|&indicator| trimmed.starts_with(indicator));
if is_prose {
end = i;
continue;
}
let looks_like_code = trimmed.starts_with("def ") ||
trimmed.starts_with("class ") ||
trimmed.starts_with("import ") ||
trimmed.starts_with("from ") ||
trimmed.starts_with("if ") ||
trimmed.starts_with("return ") ||
trimmed.starts_with("print(") ||
trimmed.ends_with(":") ||
trimmed.ends_with(")") ||
trimmed.ends_with("}") ||
trimmed.ends_with("]") ||
trimmed.starts_with("#") || trimmed.starts_with(" ") || trimmed.contains("=");
if looks_like_code {
end = i + 1;
break;
}
}
lines[start..end].join("\n")
}
fn extract_javascript_code(&self, text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let start = lines
.iter()
.position(|line| {
let trimmed = line.trim();
trimmed.starts_with("#!/usr/bin/env node")
|| trimmed.starts_with("#!/usr/bin/node")
|| trimmed.starts_with("const ")
|| trimmed.starts_with("let ")
|| trimmed.starts_with("var ")
|| trimmed.starts_with("import ")
|| trimmed.starts_with("require(")
|| trimmed.starts_with("function ")
})
.unwrap_or(0);
let mut end = lines.len();
let mut empty_count = 0;
for (i, line) in lines[start..].iter().enumerate() {
let trimmed = line.trim();
if trimmed.is_empty() {
empty_count += 1;
if empty_count >= 2 {
end = start + i - 1;
break;
}
} else {
empty_count = 0;
let prose_starters = ["This ", "The ", "Here", "Note:", "Important:", "Example:"];
if prose_starters
.iter()
.any(|&starter| trimmed.starts_with(starter))
{
end = start + i;
break;
}
}
}
lines[start..end].join("\n")
}
fn extract_yaml_code(&self, text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let start = lines
.iter()
.position(|line| line.trim().starts_with("id:"))
.unwrap_or(0);
let mut end = lines.len();
let mut empty_count = 0;
for (i, line) in lines[start..].iter().enumerate() {
let trimmed = line.trim();
if trimmed.is_empty() {
empty_count += 1;
if empty_count >= 2 {
end = start + i - 1;
break;
}
} else {
empty_count = 0;
let prose_starters = ["This ", "The ", "Here", "Note:", "Important:", "Example:"];
if prose_starters
.iter()
.any(|&starter| trimmed.starts_with(starter))
{
end = start + i;
break;
}
}
}
lines[start..end].join("\n")
}
fn extract_rust_code(&self, text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let start = lines
.iter()
.position(|line| {
let trimmed = line.trim();
trimmed.starts_with("use ")
|| trimmed.starts_with("extern ")
|| trimmed.starts_with("fn main")
|| trimmed.starts_with("pub fn")
|| trimmed.starts_with("fn ")
})
.unwrap_or(0);
lines[start..].join("\n")
}
fn extract_c_code(&self, text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let start = lines
.iter()
.position(|line| {
let trimmed = line.trim();
trimmed.starts_with("#include") || trimmed.starts_with("int main")
})
.unwrap_or(0);
lines[start..].join("\n")
}
fn extract_cpp_code(&self, text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let start = lines
.iter()
.position(|line| {
let trimmed = line.trim();
trimmed.starts_with("#include")
|| trimmed.starts_with("using namespace")
|| trimmed.starts_with("int main")
})
.unwrap_or(0);
lines[start..].join("\n")
}
fn extract_java_code(&self, text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let start = lines
.iter()
.position(|line| {
let trimmed = line.trim();
trimmed.starts_with("package ")
|| trimmed.starts_with("import ")
|| trimmed.starts_with("public class")
|| trimmed.starts_with("class ")
})
.unwrap_or(0);
lines[start..].join("\n")
}
fn extract_go_code(&self, text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let start = lines
.iter()
.position(|line| {
let trimmed = line.trim();
trimmed.starts_with("package ") || trimmed.starts_with("import ")
})
.unwrap_or(0);
lines[start..].join("\n")
}
fn extract_ruby_code(&self, text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let start = lines
.iter()
.position(|line| {
let trimmed = line.trim();
trimmed.starts_with("#!/usr/bin/env ruby")
|| trimmed.starts_with("#!/usr/bin/ruby")
|| trimmed.starts_with("require ")
|| trimmed.starts_with("class ")
|| trimmed.starts_with("module ")
|| trimmed.starts_with("def ")
})
.unwrap_or(0);
lines[start..].join("\n")
}
fn extract_perl_code(&self, text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let start = lines
.iter()
.position(|line| {
let trimmed = line.trim();
trimmed.starts_with("#!/usr/bin/env perl")
|| trimmed.starts_with("#!/usr/bin/perl")
|| trimmed.starts_with("use strict")
|| trimmed.starts_with("use warnings")
|| trimmed.starts_with("use ")
|| trimmed.starts_with("sub ")
})
.unwrap_or(0);
lines[start..].join("\n")
}
fn extract_php_code(&self, text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let start = lines
.iter()
.position(|line| {
let trimmed = line.trim();
trimmed.starts_with("<?php")
|| trimmed.starts_with("#!/usr/bin/env php")
|| trimmed.starts_with("#!/usr/bin/php")
})
.unwrap_or(0);
lines[start..].join("\n")
}
fn extract_shell_code(&self, text: &str) -> String {
let lines: Vec<&str> = text.lines().collect();
let start = lines
.iter()
.position(|line| {
let trimmed = line.trim();
trimmed.starts_with("#!/bin/bash")
|| trimmed.starts_with("#!/usr/bin/env bash")
|| trimmed.starts_with("#!/bin/sh")
})
.unwrap_or(0);
lines[start..].join("\n")
}
fn validate_basic_structure(&self, code: &str, language: TemplateLanguage) -> Result<()> {
if code.trim().is_empty() {
anyhow::bail!("Extracted template is empty");
}
match language {
TemplateLanguage::Python => self.validate_python_structure(code),
TemplateLanguage::JavaScript => self.validate_javascript_structure(code),
TemplateLanguage::Yaml => self.validate_yaml_structure(code),
TemplateLanguage::Rust => self.validate_rust_structure(code),
TemplateLanguage::C => self.validate_c_structure(code),
TemplateLanguage::Cpp => self.validate_cpp_structure(code),
TemplateLanguage::Java => self.validate_java_structure(code),
TemplateLanguage::Go => self.validate_go_structure(code),
TemplateLanguage::Ruby => self.validate_ruby_structure(code),
TemplateLanguage::Perl => self.validate_perl_structure(code),
TemplateLanguage::Php => self.validate_php_structure(code),
TemplateLanguage::Shell => self.validate_shell_structure(code),
}
}
fn validate_python_structure(&self, code: &str) -> Result<()> {
if !code.contains("def ") && !code.contains("class ") {
tracing::error!("Python validation failed - no def/class found");
tracing::error!(
"Code preview (first 500 chars): {}",
&code.chars().take(500).collect::<String>()
);
anyhow::bail!("Python template missing function or class definitions");
}
if !code.contains("json") {
tracing::warn!("Python template missing JSON module - this is recommended");
}
if !code.contains("os.environ") && !code.contains("os.getenv") {
tracing::warn!("Python template may not read environment variables properly");
}
Ok(())
}
fn validate_javascript_structure(&self, code: &str) -> Result<()> {
if !code.contains("function") && !code.contains("const ") && !code.contains("let ") {
anyhow::bail!("JavaScript template missing function/variable definitions");
}
if !code.contains("JSON.stringify") {
anyhow::bail!("JavaScript template missing JSON.stringify for output");
}
if !code.contains("process.env") {
tracing::warn!("JavaScript template may not read environment variables properly");
}
Ok(())
}
fn validate_yaml_structure(&self, code: &str) -> Result<()> {
if !code.contains("id:") {
anyhow::bail!("YAML template missing required 'id' field");
}
if !code.contains("info:") {
anyhow::bail!("YAML template missing required 'info' section");
}
if !code.contains("protocol:") {
anyhow::bail!("YAML template missing required 'protocol' field");
}
if !code.contains("matchers") && !code.contains("requests") {
anyhow::bail!("YAML template missing 'matchers' or 'requests' section");
}
Ok(())
}
fn validate_rust_structure(&self, code: &str) -> Result<()> {
if !code.contains("fn main") && !code.contains("fn ") {
anyhow::bail!("Rust template missing function definitions");
}
Ok(())
}
fn validate_c_structure(&self, code: &str) -> Result<()> {
if !code.contains("#include") {
anyhow::bail!("C template missing #include directives");
}
if !code.contains("int main") {
anyhow::bail!("C template missing main() function");
}
Ok(())
}
fn validate_cpp_structure(&self, code: &str) -> Result<()> {
if !code.contains("#include") {
anyhow::bail!("C++ template missing #include directives");
}
if !code.contains("int main") {
anyhow::bail!("C++ template missing main() function");
}
Ok(())
}
fn validate_java_structure(&self, code: &str) -> Result<()> {
if !code.contains("class ") {
anyhow::bail!("Java template missing class definition");
}
if !code.contains("public static void main") {
anyhow::bail!("Java template missing main() method");
}
Ok(())
}
fn validate_go_structure(&self, code: &str) -> Result<()> {
if !code.contains("package ") {
anyhow::bail!("Go template missing package declaration");
}
if !code.contains("func main") {
anyhow::bail!("Go template missing main() function");
}
Ok(())
}
fn validate_ruby_structure(&self, code: &str) -> Result<()> {
if code.lines().count() < 5 {
anyhow::bail!("Ruby template seems too short");
}
Ok(())
}
fn validate_perl_structure(&self, code: &str) -> Result<()> {
if !code.contains("use strict") && !code.contains("use warnings") {
tracing::warn!("Perl template missing strict/warnings pragmas");
}
Ok(())
}
fn validate_php_structure(&self, code: &str) -> Result<()> {
if !code.contains("<?php") {
anyhow::bail!("PHP template missing <?php opening tag");
}
Ok(())
}
fn validate_shell_structure(&self, code: &str) -> Result<()> {
if !code.contains("#!/") {
tracing::warn!("Shell template missing shebang");
}
Ok(())
}
}
impl Default for ResponseParser {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parser_creation() {
let parser = ResponseParser::new();
assert!(parser.markdown_block_start.is_match("```python\n"));
assert!(parser.markdown_block_end.is_match("\n```"));
}
#[test]
fn test_remove_markdown_blocks() {
let parser = ResponseParser::new();
let input = "```python\nprint('hello')\n```";
let result = parser.remove_markdown_blocks(input);
assert_eq!(result.trim(), "print('hello')");
let input = "Some text\n```yaml\nid: test\n```\nMore text";
let result = parser.remove_markdown_blocks(input);
assert!(!result.contains("```"));
}
#[test]
fn test_extract_python_code() {
let parser = ResponseParser::new();
let input =
"Here's a Python template:\n\n#!/usr/bin/env python3\nimport json\nprint('test')";
let result = parser.extract_python_code(input);
assert!(result.starts_with("#!/usr/bin/env python3"));
let input = "Explanation text\nimport sys\nimport json\n\ndef main():\n pass";
let result = parser.extract_python_code(input);
assert!(result.starts_with("import sys"));
}
#[test]
fn test_extract_yaml_code() {
let parser = ResponseParser::new();
let input = "Here's the YAML template:\n\nid: test-template\ninfo:\n name: Test";
let result = parser.extract_yaml_code(input);
assert!(result.starts_with("id: test-template"));
}
#[test]
fn test_validate_python_structure() {
let parser = ResponseParser::new();
let valid =
"import json\nimport os\n\ndef main():\n data = json.dumps({})\n print(data)";
assert!(parser.validate_python_structure(valid).is_ok());
let valid_no_json = "def main():\n print('test')";
assert!(parser.validate_python_structure(valid_no_json).is_ok());
let invalid = "import json\nprint('test')";
assert!(parser.validate_python_structure(invalid).is_err());
}
#[test]
fn test_validate_yaml_structure() {
let parser = ResponseParser::new();
let valid = "id: test\ninfo:\n name: Test\nprotocol: tcp\nmatchers:\n - type: word";
assert!(parser.validate_yaml_structure(valid).is_ok());
let invalid = "info:\n name: Test\nprotocol: tcp";
assert!(parser.validate_yaml_structure(invalid).is_err());
let invalid = "id: test\ninfo:\n name: Test";
assert!(parser.validate_yaml_structure(invalid).is_err());
}
#[test]
fn test_full_parse_python() {
let parser = ResponseParser::new();
let llm_response = r#"Here's a Python template for Redis detection:
```python
#!/usr/bin/env python3
import json
import os
def check_redis():
host = os.getenv('CERT_X_GEN_TARGET_HOST')
return json.dumps([])
if __name__ == '__main__':
check_redis()
```
This template checks for Redis.
"#;
let result = parser.parse(llm_response, TemplateLanguage::Python);
assert!(result.is_ok());
let code = result.unwrap();
assert!(code.starts_with("#!/usr/bin/env python3"));
assert!(code.contains("import json"));
assert!(!code.contains("```"));
assert!(!code.contains("This template checks"));
}
#[test]
fn test_full_parse_yaml() {
let parser = ResponseParser::new();
let llm_response = r#"Here's your YAML template:
```yaml
id: redis-unauth
info:
name: Redis Unauthenticated
severity: high
protocol: tcp
port: 6379
matchers:
- type: word
words:
- "redis_version"
```
This detects Redis servers."#;
let result = parser.parse(llm_response, TemplateLanguage::Yaml);
assert!(result.is_ok());
let code = result.unwrap();
assert!(code.starts_with("id: redis-unauth"));
assert!(!code.contains("```"));
assert!(!code.contains("This detects"));
}
}