use crate::params::Params;
use color_eyre::eyre::{self, ContextCompat};
use serde::{Deserialize, Serialize};
use std::{fmt::Display, path::PathBuf};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Role {
Endpoint,
Cron,
Worker,
}
impl Display for Role {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let str = match self {
Role::Endpoint => "endpoint",
Role::Cron => "cron",
Role::Worker => "worker",
};
write!(f, "{}", str)
}
}
#[derive(Debug, Clone)]
pub struct ParsedFunction {
pub rust_function_name: String,
pub relative_path: PathBuf,
pub pkg_name: String,
pub pkg_rel_path: PathBuf,
pub role: Role,
pub params: Params,
}
impl Display for ParsedFunction {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
self.pkg_rel_path
.join(&self.relative_path)
.to_string_lossy()
)
}
}
impl ParsedFunction {
pub fn to_local_name(paths: &[&str]) -> String {
paths
.iter()
.flat_map(|path| {
path.split(&['.', '/'])
.filter(|s| !s.eq(&"rs"))
.map(|s| match s.chars().next() {
Some(first) => first.to_uppercase().collect::<String>() + &s[1..],
None => String::new(),
})
})
.collect::<String>()
}
pub fn func_name(&self, is_local: bool) -> eyre::Result<String> {
let rust_name = &self.rust_function_name;
let default_func_name = Self::to_local_name(&[
&self.pkg_name,
self.relative_path
.strip_prefix("src")?
.to_str()
.wrap_err_with(|| {
format!(
"Failed converting func path to str: `{:?}`",
self.relative_path
)
})?,
rust_name,
]);
let name = self.params.name().unwrap_or(&default_func_name);
if name.len() > 64 {
Err(eyre::eyre!(
"Function name is longer than 64 chars: {}",
name
))
} else {
Ok(format!("{}{}", name, if is_local { "Local" } else { "" }))
}
}
}