use std::path::PathBuf;
use serde::Serialize;
#[derive(Debug, Clone, Serialize)]
pub struct Skill {
pub name: String,
pub description: String,
pub allowed_tools: Vec<String>,
pub body: String,
pub dir: PathBuf,
}
impl Skill {
pub fn parse_md(content: &str, dir: PathBuf, fallback_name: &str) -> Skill {
let (front, body) = split_frontmatter(content);
let mut name = None;
let mut description = String::new();
let mut allowed_tools = Vec::new();
for line in front.lines() {
let Some((k, v)) = line.split_once(':') else {
continue;
};
let val = v.trim();
match k.trim() {
"name" if !val.is_empty() => name = Some(unquote(val)),
"description" => description = unquote(val),
"allowed-tools" | "allowed_tools" => allowed_tools = parse_list(val),
_ => {}
}
}
Skill {
name: name.unwrap_or_else(|| fallback_name.to_string()),
description,
allowed_tools,
body: body.trim().to_string(),
dir,
}
}
pub fn summary(&self) -> String {
format!("{}: {}", self.name, self.description)
}
}
fn split_frontmatter(content: &str) -> (String, String) {
let content = content.trim_start_matches('\u{feff}');
if content.trim_start().starts_with("---") {
let mut started = false;
let mut closed = false;
let mut front = String::new();
let mut body: Vec<&str> = Vec::new();
for line in content.lines() {
if !started {
if line.trim() == "---" {
started = true;
}
continue;
}
if !closed {
if line.trim() == "---" {
closed = true;
continue;
}
front.push_str(line);
front.push('\n');
} else {
body.push(line);
}
}
if closed {
return (front, body.join("\n"));
}
}
(String::new(), content.to_string())
}
fn unquote(s: &str) -> String {
let s = s.trim();
for q in ['"', '\''] {
if s.len() >= 2 && s.starts_with(q) && s.ends_with(q) {
return s[1..s.len() - 1].to_string();
}
}
s.to_string()
}
fn parse_list(s: &str) -> Vec<String> {
s.trim()
.trim_start_matches('[')
.trim_end_matches(']')
.split(',')
.map(|t| unquote(t.trim()))
.filter(|t| !t.is_empty())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_frontmatter_and_body() {
let md = "---\nname: pdf-forms\ndescription: Fill PDF forms\nallowed-tools: [read, write]\n---\n# Steps\n1. open the pdf\n";
let s = Skill::parse_md(md, PathBuf::from("/x"), "folder");
assert_eq!(s.name, "pdf-forms");
assert_eq!(s.description, "Fill PDF forms");
assert_eq!(s.allowed_tools, vec!["read", "write"]);
assert!(s.body.starts_with("# Steps"));
assert_eq!(s.summary(), "pdf-forms: Fill PDF forms");
}
#[test]
fn name_falls_back_to_folder() {
let s = Skill::parse_md(
"just a body, no frontmatter",
PathBuf::from("/x"),
"myskill",
);
assert_eq!(s.name, "myskill");
assert_eq!(s.body, "just a body, no frontmatter");
assert!(s.description.is_empty());
}
}