use crate::util::try_unescape;
use crate::{Error, Identifier, Result};
use serde::Deserialize;
use std::fmt;
use std::str::FromStr;
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub enum TemplateExpr {
QuotedString(String),
Heredoc(Heredoc),
}
impl TemplateExpr {
pub(crate) fn as_str(&self) -> &str {
match self {
TemplateExpr::QuotedString(s) => s,
TemplateExpr::Heredoc(heredoc) => &heredoc.template,
}
}
}
impl From<&str> for TemplateExpr {
fn from(s: &str) -> Self {
TemplateExpr::QuotedString(s.to_owned())
}
}
impl From<String> for TemplateExpr {
fn from(string: String) -> Self {
TemplateExpr::QuotedString(string)
}
}
impl From<Heredoc> for TemplateExpr {
fn from(heredoc: Heredoc) -> Self {
TemplateExpr::Heredoc(heredoc)
}
}
impl fmt::Display for TemplateExpr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(&try_unescape(self.as_str()))
}
}
#[derive(Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct Heredoc {
pub delimiter: Identifier,
pub template: String,
pub strip: HeredocStripMode,
}
impl Heredoc {
pub fn new<T>(delimiter: Identifier, template: T) -> Heredoc
where
T: Into<String>,
{
Heredoc {
delimiter,
template: template.into(),
strip: HeredocStripMode::default(),
}
}
pub fn with_strip_mode(mut self, strip: HeredocStripMode) -> Heredoc {
self.strip = strip;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HeredocStripMode {
None,
Indent,
}
impl HeredocStripMode {
pub fn as_str(&self) -> &'static str {
match self {
HeredocStripMode::None => "<<",
HeredocStripMode::Indent => "<<-",
}
}
}
impl Default for HeredocStripMode {
fn default() -> Self {
HeredocStripMode::None
}
}
impl FromStr for HeredocStripMode {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
match s {
"<<" => Ok(HeredocStripMode::None),
"<<-" => Ok(HeredocStripMode::Indent),
_ => Err(Error::new(format!("invalid heredoc strip mode: `{s}`"))),
}
}
}