use std::fmt::Write as _;
use crate::config::Config;
use crate::value::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum HostFormat {
Env,
Wrangler,
Compose,
}
impl HostFormat {
pub fn name(self) -> &'static str {
match self {
HostFormat::Env => "env",
HostFormat::Wrangler => "wrangler",
HostFormat::Compose => "compose",
}
}
pub fn parse(name: &str) -> Option<HostFormat> {
match name {
"env" => Some(HostFormat::Env),
"wrangler" => Some(HostFormat::Wrangler),
"compose" => Some(HostFormat::Compose),
_ => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Var {
pub name: String,
pub value: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostSupplied {
pub name: String,
pub origin: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Skipped {
pub key: String,
pub reason: &'static str,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Projection {
pub vars: Vec<Var>,
pub supplied: Vec<HostSupplied>,
pub skipped: Vec<Skipped>,
}
impl Config {
pub fn project(&self) -> Projection {
let mut p = Projection::default();
for def in self.schema().values() {
let Some(name) = def.env.as_deref() else {
p.skipped.push(Skipped {
key: def.key.clone(),
reason: "no `env` name in the schema",
});
continue;
};
if !valid_name(name) {
p.skipped.push(Skipped {
key: def.key.clone(),
reason: "its `env` name is not a valid variable name",
});
continue;
}
if def.secret {
p.supplied.push(HostSupplied {
name: name.to_owned(),
origin: def.source.clone(),
});
continue;
}
match self.value(&def.key) {
None => p.skipped.push(Skipped {
key: def.key.clone(),
reason: "not set",
}),
Some(v) => match text_of(v) {
Some(value) => p.vars.push(Var {
name: name.to_owned(),
value,
}),
None => p.skipped.push(Skipped {
key: def.key.clone(),
reason: "a table or map: file-only",
}),
},
}
}
p
}
}
fn valid_name(name: &str) -> bool {
let mut chars = name.chars();
chars
.next()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
&& chars.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
fn text_of(v: &Value) -> Option<String> {
Some(match v {
Value::String(s) | Value::Enum(s) => s.clone(),
Value::Path(p) => p.display().to_string(),
Value::Int(i) => i.to_string(),
Value::Float(f) => f.to_string(),
Value::Bool(b) => b.to_string(),
Value::List(items) => items
.iter()
.map(|i| i.replace('\\', "\\\\").replace(',', "\\,"))
.collect::<Vec<_>>()
.join(","),
Value::Rows(_) | Value::Map(_) => return None,
})
}
fn quoted(s: &str) -> String {
let mut out = String::from("\"");
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c.is_control() => {
let _ = write!(out, "\\u{:04X}", c as u32);
}
c => out.push(c),
}
}
out.push('"');
out
}
fn comment(s: &str) -> String {
s.chars()
.map(|c| if c.is_control() { ' ' } else { c })
.collect()
}
impl Projection {
pub fn render(&self, format: HostFormat) -> String {
let mut out = String::new();
match format {
HostFormat::Env => {
for v in &self.vars {
let _ = writeln!(out, "{}={}", v.name, quoted(&v.value));
}
for s in &self.supplied {
let _ = writeln!(out, "# secret {}{}", s.name, origin_note(s));
}
}
HostFormat::Wrangler => {
out.push_str("[vars]\n");
for v in &self.vars {
let _ = writeln!(out, "{} = {}", v.name, quoted(&v.value));
}
for s in &self.supplied {
let _ = writeln!(
out,
"# secret {}: set with `wrangler secret put {}`{}",
s.name,
s.name,
origin_note(s)
);
}
}
HostFormat::Compose => {
out.push_str("environment:\n");
for v in &self.vars {
let _ = writeln!(out, " {}: {}", v.name, quoted(&v.value.replace('$', "$$")));
}
for s in &self.supplied {
let _ = writeln!(
out,
" {}: ${{{}:?set {} in the host environment}}{}",
s.name,
s.name,
s.name,
origin_note_comment(s)
);
}
}
}
for k in &self.skipped {
let _ = writeln!(out, "# skipped {}: {}", comment(&k.key), k.reason);
}
out
}
}
fn origin_note(s: &HostSupplied) -> String {
match &s.origin {
Some(src) => format!(" (source {})", comment(src)),
None => String::new(),
}
}
fn origin_note_comment(s: &HostSupplied) -> String {
match &s.origin {
Some(src) => format!(" # source {}", comment(src)),
None => String::new(),
}
}