1use crate::*;
2
3pub(crate) fn set_global_state(state: Arc<AppState>) -> Result<(), EuvError> {
13 APP_STATE.set(state).map_err(|_: Arc<AppState>| {
14 EuvError::Message(String::from("Global state already initialized"))
15 })
16}
17
18pub(crate) fn get_global_state() -> Option<Arc<AppState>> {
24 APP_STATE.get().cloned()
25}
26
27pub(crate) async fn generate_html(config: &HtmlConfig) -> Result<String, EuvError> {
42 let template_content: String = if let Some(custom_path) = config.try_get_custom_index_html() {
43 let bytes: Vec<u8> =
44 read(custom_path)
45 .await
46 .map_err(|error: io::Error| EuvError::IoPath {
47 message: String::from("Failed to read custom index.html"),
48 path: custom_path.to_path_buf(),
49 error,
50 })?;
51 String::from_utf8(bytes).map_err(|error: std::string::FromUtf8Error| EuvError::Utf8 {
52 message: String::from("Custom index.html is not valid UTF-8"),
53 error,
54 })?
55 } else if config.get_is_release() {
56 INDEX_HTML_RELEASE.to_string()
57 } else {
58 INDEX_HTML_DEV.to_string()
59 };
60 let html: String = template_content
61 .replace(IMPORT_PATH_PLACEHOLDER, config.get_import_path())
62 .replace(RELOAD_ROUTE_PLACEHOLDER, RELOAD_ROUTE);
63 let index_path: PathBuf = config.get_serving_root().join(INDEX_HTML_FILE_NAME);
64 create_dir_all(config.get_serving_root())
65 .await
66 .map_err(|error: io::Error| EuvError::Io {
67 message: String::from("Failed to create static directory"),
68 error,
69 })?;
70 write(&index_path, &html)
71 .await
72 .map_err(|error: io::Error| EuvError::Io {
73 message: String::from("Failed to write index.html"),
74 error,
75 })?;
76 Ok(html)
77}
78
79pub async fn resolve_www_dir(www_dir: &Path) -> PathBuf {
89 if metadata(www_dir.join(INDEX_HTML_FILE_NAME)).await.is_ok() {
90 return www_dir.to_path_buf();
91 }
92 let parent_name: Option<&str> = www_dir
93 .file_name()
94 .and_then(|file_name_os_str: &ffi::OsStr| file_name_os_str.to_str());
95 if let Some(name) = parent_name {
96 let nested: PathBuf = www_dir.join(name);
97 if metadata(nested.join(INDEX_HTML_FILE_NAME)).await.is_ok() {
98 return nested;
99 }
100 }
101 www_dir.to_path_buf()
102}
103
104pub fn resolve_pkg_dir(args: &ModeArgs) -> PathBuf {
117 resolve_out_dir(args)
118}
119
120pub async fn resolve_file_in_base(base: &Path, path: &str) -> Option<PathBuf> {
134 let file_path: PathBuf = base.join(path);
135 let canonical_path: PathBuf = canonicalize(&file_path).await.ok()?;
136 let base_canonical: PathBuf = canonicalize(base).await.ok()?;
137 canonical_path
138 .starts_with(&base_canonical)
139 .then_some(file_path)
140}