pzzld_server/config/kinds/
scope.rs1use std::path::PathBuf;
6
7fn _default_context() -> Option<String> {
8 Some(".".to_string())
9}
10
11fn _default_workdir() -> String {
12 crate::DEFAULT_WORKDIR.to_string()
13}
14
15#[derive(
17 Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, serde::Deserialize, serde::Serialize,
18)]
19#[serde(default)]
20pub struct Scope {
21 pub(crate) context: Option<String>,
23 #[serde(default = "_default_workdir")]
25 pub(crate) workdir: String,
26}
27
28impl Scope {
29 pub fn new(workdir: impl ToString) -> Self {
30 Self {
31 context: None,
32 workdir: workdir.to_string(),
33 }
34 }
35
36 get!(context: Option<String>, workdir: String);
37
38 setwith!(workdir: String);
39 pub fn as_path(&self) -> PathBuf {
41 let mut path = PathBuf::new();
43 self.context().clone().map(|context| path.push(context));
45 path.push(self.workdir());
47 debug_assert!(path.is_dir());
49 path
51 }
52 pub fn as_path_str(&self) -> String {
54 self.as_path().display().to_string()
55 }
56 pub fn set_cwd(&self) {
58 std::env::set_current_dir(self.as_path()).unwrap();
59 }
60 pub fn set_context(&mut self, context: impl ToString) {
62 self.context = Some(context.to_string());
63 }
64 pub fn with_context(self, context: impl ToString) -> Self {
66 Self {
67 context: Some(context.to_string()),
68 ..self
69 }
70 }
71 pub fn set_some_context(&mut self, rhs: Option<impl ToString>) {
73 rhs.map(|data| self.set_context(data));
74 }
75
76 pub fn set_some_workdir(&mut self, rhs: Option<impl ToString>) {
77 rhs.map(|data| self.set_workdir(data));
78 }
79}
80
81impl Default for Scope {
82 fn default() -> Self {
83 Self {
84 context: None,
85 workdir: "dist".into(),
86 }
87 }
88}
89
90impl core::fmt::Display for Scope {
91 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
92 write!(f, "{path}", path = self.as_path().display())
93 }
94}
95
96impl core::str::FromStr for Scope {
97 type Err = std::io::Error;
98
99 fn from_str(s: &str) -> Result<Self, Self::Err> {
100 Ok(Self::new(s))
101 }
102}