pub fn strip_fences(input: &str) -> String {
let mut text = input.trim();
for fence in ["```", "~~~"] {
if let Some(rest) = text.strip_prefix(fence) {
let after_tag = rest.trim_start_matches(|c: char| c.is_alphanumeric() || c == '_');
text = after_tag.strip_prefix('\n').unwrap_or(after_tag);
break;
}
}
for fence in ["```", "~~~"] {
if let Some(stripped) = text.trim_end().strip_suffix(fence) {
text = stripped;
break;
}
}
text.trim().to_string()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn no_fences_passthrough() {
assert_eq!(strip_fences("{\"a\": 1}"), "{\"a\": 1}");
}
#[test]
fn strips_lower_json_tag() {
let s = "```json\n{\"a\": 1}\n```";
assert_eq!(strip_fences(s), "{\"a\": 1}");
}
#[test]
fn strips_upper_json_tag() {
let s = "```JSON\n{\"a\": 1}\n```";
assert_eq!(strip_fences(s), "{\"a\": 1}");
}
#[test]
fn strips_no_tag() {
let s = "```\n{\"a\": 1}\n```";
assert_eq!(strip_fences(s), "{\"a\": 1}");
}
#[test]
fn strips_tilde_fence() {
let s = "~~~\n{\"a\": 1}\n~~~";
assert_eq!(strip_fences(s), "{\"a\": 1}");
}
#[test]
fn strips_dangling_opener() {
let s = "```json\n{\"a\": 1}";
assert_eq!(strip_fences(s), "{\"a\": 1}");
}
#[test]
fn strips_surrounding_whitespace() {
let s = " \n```json\n{\"a\": 1}\n```\n ";
assert_eq!(strip_fences(s), "{\"a\": 1}");
}
#[test]
fn does_not_break_inline_code() {
let s = "the code `foo` is fine";
assert_eq!(strip_fences(s), "the code `foo` is fine");
}
}