use std::io::{Error, ErrorKind};
use std::path::PathBuf;
use crate::wire;
fn handler(cap: &str) -> Option<(&'static str, String, &'static str)> {
match cap {
"sse" => Some((
"Sse",
"\n @Sse('/events')\n events() {\n return (async function* () {\n yield { hello: 'world' };\n })();\n }\n".into(),
"'/events'",
)),
"stream" => Some((
"Stream",
"\n @Stream('/stream')\n stream() {\n return (async function* () {\n yield 'chunk';\n })();\n }\n".into(),
"'/stream'",
)),
"buffer" => Some((
"Get",
"\n @Get('/data')\n data() {\n return Buffer.from('hello');\n }\n".into(),
"'/data'",
)),
_ => None,
}
}
fn only_controller() -> std::io::Result<PathBuf> {
let dir = std::path::Path::new("src/controllers");
let mut hits: Vec<PathBuf> = std::fs::read_dir(dir)?
.filter_map(|e| e.ok().map(|e| e.path()))
.filter(|p| p.to_string_lossy().ends_with(".controller.ts"))
.collect();
match hits.len() {
1 => Ok(hits.pop().unwrap()),
0 => Err(Error::new(
ErrorKind::NotFound,
"no *.controller.ts in src/controllers",
)),
_ => Err(Error::other(
"multiple controllers; specify which (not yet supported)",
)),
}
}
fn class_name(src: &str) -> Option<String> {
let idx = src.find("export class ")? + "export class ".len();
let rest = &src[idx..];
let end = rest.find(|c: char| !c.is_alphanumeric() && c != '_')?;
Some(rest[..end].to_string())
}
pub fn run(cap: &str) -> std::io::Result<()> {
let (decorator, method, marker) = handler(cap)
.ok_or_else(|| Error::new(ErrorKind::InvalidInput, format!("unknown capability {cap}")))?;
let path = only_controller()?;
let src = std::fs::read_to_string(&path)?;
let class = class_name(&src).ok_or_else(|| Error::other("no exported class found"))?;
if src.contains(marker) {
println!("→ {cap} already present in {class}");
return Ok(());
}
let with_import = wire::add_import(&src, decorator, "@green-tea/core");
match wire::insert_method(&with_import, &class, &method) {
Some(out) => {
std::fs::write(&path, out)?;
println!("✓ added @{decorator} to {class}");
}
None => println!(
"→ could not edit {}; add @{decorator} handler manually",
path.display()
),
}
Ok(())
}