use std::borrow::Cow;
use askama::Template;
use crate::ContainerPath;
#[derive(Template)]
#[template(path = "tool_path.sh", escape = "none")]
struct PathTemplate<'a> {
bin_dir: Cow<'a, str>,
exports: Vec<(&'a str, Cow<'a, str>)>,
script: &'a str,
}
#[derive(Template)]
#[template(path = "managed_shell.sh", escape = "none")]
struct ShellTemplate<'a> {
shell: Cow<'a, str>,
arguments: String,
}
fn with_path(
bin_dir: &str,
exports: &[(String, String)],
script: &str,
) -> Result<String, askama::Error> {
PathTemplate {
bin_dir: shell_words::quote(bin_dir),
exports: exports
.iter()
.map(|(name, value)| (name.as_str(), shell_words::quote(value)))
.collect(),
script,
}
.render()
}
#[must_use]
pub fn shell_arguments(script: &str) -> Vec<String> {
["--noprofile", "--norc", "-c", script]
.map(Into::into)
.into()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostLaunch {
shell: std::sync::Arc<str>,
}
impl HostLaunch {
#[must_use]
pub fn new(shell: impl Into<std::sync::Arc<str>>) -> Self {
Self {
shell: shell.into(),
}
}
#[must_use]
pub const fn shell(&self) -> &std::sync::Arc<str> {
&self.shell
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ContainerLaunch {
bin_dir: ContainerPath,
shell: ContainerPath,
}
impl ContainerLaunch {
#[must_use]
pub const fn new(bin_dir: ContainerPath, shell: ContainerPath) -> Self {
Self { bin_dir, shell }
}
#[must_use]
pub const fn bin_dir(&self) -> &ContainerPath {
&self.bin_dir
}
pub fn wrap_script(&self, script: &str) -> Result<String, askama::Error> {
with_path(self.bin_dir.as_str(), &[], script)
}
pub fn shell_command(&self, script: &str) -> Result<String, askama::Error> {
ShellTemplate {
shell: shell_words::quote(self.shell.as_str()),
arguments: shell_words::join(shell_arguments(script)),
}
.render()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteLaunch {
bin_dir: String,
shell: String,
exports: Vec<(String, String)>,
writable_dir: Option<String>,
}
impl RemoteLaunch {
#[must_use]
pub fn new(bin_dir: impl Into<String>, shell: impl Into<String>) -> Self {
Self {
bin_dir: bin_dir.into(),
shell: shell.into(),
exports: Vec::new(),
writable_dir: None,
}
}
#[must_use]
pub fn with_exports(mut self, exports: impl IntoIterator<Item = (String, String)>) -> Self {
self.exports.extend(exports);
self
}
#[must_use]
pub fn with_writable_dir(mut self, dir: impl Into<String>) -> Self {
self.writable_dir = Some(dir.into());
self
}
#[must_use]
pub fn bin_dir(&self) -> &str {
&self.bin_dir
}
#[must_use]
pub fn shell(&self) -> &str {
&self.shell
}
#[must_use]
pub fn writable_dir(&self) -> Option<&str> {
self.writable_dir.as_deref()
}
pub fn wrap_script(&self, script: &str) -> Result<String, askama::Error> {
with_path(&self.bin_dir, &self.exports, script)
}
}