use std::path::PathBuf;
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[cfg_attr(
feature = "serde",
derive(serde::Deserialize, serde::Serialize),
serde(default, rename_all = "lowercase")
)]
pub struct Scope {
pub(crate) context: Option<String>,
pub(crate) workdir: String,
}
impl Scope {
pub(crate) const DEFAULT_WORKDIR: &'static str = "dist";
pub fn new(workdir: impl ToString) -> Self {
Self {
context: None,
workdir: workdir.to_string(),
}
}
pub fn context(&self) -> Option<&str> {
self.context.as_deref()
}
pub fn workdir(&self) -> &str {
self.workdir.as_str()
}
pub fn as_path(&self) -> PathBuf {
let mut path = PathBuf::new();
if let Some(context) = self.context() {
path.push(context)
}
path.push(self.workdir());
debug_assert!(path.is_dir());
path
}
pub fn as_path_str(&self) -> String {
self.as_path().display().to_string()
}
pub fn set_cwd(&self) {
std::env::set_current_dir(self.as_path()).unwrap();
}
pub fn set_context<T: ToString>(&mut self, context: T) -> &mut Self {
self.context = Some(context.to_string());
self
}
pub fn with_context(self, context: impl ToString) -> Self {
Self {
context: Some(context.to_string()),
..self
}
}
pub fn set_workdir<T: ToString>(&mut self, workdir: T) -> &mut Self {
self.workdir = workdir.to_string();
self
}
pub fn with_workdir(self, workdir: impl ToString) -> Self {
Self {
workdir: workdir.to_string(),
..self
}
}
pub fn set_some_context<C: ToString>(&mut self, rhs: Option<C>) {
rhs.map(|data| self.set_context(data));
}
pub fn set_some_workdir(&mut self, rhs: Option<impl ToString>) {
rhs.map(|data| self.set_workdir(data));
}
}
impl Default for Scope {
fn default() -> Self {
Self {
context: None,
workdir: Scope::DEFAULT_WORKDIR.into(),
}
}
}
impl core::fmt::Display for Scope {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{path}", path = self.as_path().display())
}
}
impl core::str::FromStr for Scope {
type Err = crate::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self::new(s))
}
}