use std::fs;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use crate::paths::NetweftPaths;
use crate::plan::env::ResolvedEnvPlan;
pub fn render_env(plan: &ResolvedEnvPlan, paths: &NetweftPaths) -> Result<PathBuf> {
let location_root = paths.generated_dir.join(&plan.location);
let output = location_root.join("hosts").join(&plan.host);
fs::create_dir_all(&output)?;
write(&output.join("compose.env"), &dotenv(plan))?;
write(&output.join("shell.sh"), &posix(plan))?;
write(&output.join("shell.fish"), &fish(plan))?;
write(&output.join("shell.ps1"), &pwsh(plan))?;
update_current_link(paths, &location_root)?;
Ok(output)
}
fn dotenv(plan: &ResolvedEnvPlan) -> String {
let mut output = String::from("# Generated by Netweft. Do not edit.\n");
for (key, value) in &plan.variables {
output.push_str(&format!("{key}={}\n", dotenv_quote(value)));
}
output
}
fn posix(plan: &ResolvedEnvPlan) -> String {
let mut output = String::from("# Generated by Netweft. Do not edit.\n");
for (key, value) in &plan.variables {
output.push_str(&format!("export {key}={}\n", shell_quote(value)));
}
output
}
fn fish(plan: &ResolvedEnvPlan) -> String {
let mut output = String::from("# Generated by Netweft. Do not edit.\n");
for (key, value) in &plan.variables {
output.push_str(&format!("set -gx {key} {};\n", shell_quote(value)));
}
output
}
fn pwsh(plan: &ResolvedEnvPlan) -> String {
let mut output = String::from("# Generated by Netweft. Do not edit.\n");
for (key, value) in &plan.variables {
output.push_str(&format!("$env:{key} = {}\n", shell_quote(value)));
}
output
}
fn dotenv_quote(value: &str) -> String {
if value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || b"_./:-,".contains(&byte))
{
value.to_owned()
} else {
format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
}
}
fn shell_quote(value: &str) -> String {
format!("'{}'", value.replace('\'', "'\\''"))
}
fn write(path: &Path, contents: &str) -> Result<()> {
fs::write(path, contents).with_context(|| format!("failed to write {}", path.display()))
}
fn update_current_link(paths: &NetweftPaths, target: &Path) -> Result<()> {
let current = paths
.generated_dir
.parent()
.context("generated directory has no parent")?
.join("current");
if current.symlink_metadata().is_ok() {
if current.is_dir() && !current.is_symlink() {
fs::remove_dir_all(¤t)?;
} else {
fs::remove_file(¤t)?;
}
}
#[cfg(unix)]
std::os::unix::fs::symlink(target, ¤t)?;
#[cfg(not(unix))]
fs::write(current.with_extension("txt"), target.display().to_string())?;
Ok(())
}