|
| 1 | +use std::{ |
| 2 | + ops::Deref, |
| 3 | + path::{ |
| 4 | + Component as PathComponent, |
| 5 | + PathBuf, |
| 6 | + }, |
| 7 | + str::FromStr, |
| 8 | +}; |
| 9 | + |
| 10 | +use anyhow::Context; |
| 11 | +use sync_types::path::check_valid_path_component; |
| 12 | + |
| 13 | +// Path relative to a project's `convex/` directory for each component |
| 14 | +// definition's folder. This path is project-level and originates from |
| 15 | +// a developer's source code. |
| 16 | +pub struct ComponentDefinitionPath { |
| 17 | + path: PathBuf, |
| 18 | +} |
| 19 | + |
| 20 | +impl FromStr for ComponentDefinitionPath { |
| 21 | + type Err = anyhow::Error; |
| 22 | + |
| 23 | + fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 24 | + let path = PathBuf::from(s); |
| 25 | + for component in path.components() { |
| 26 | + match component { |
| 27 | + PathComponent::Normal(c) => { |
| 28 | + let s = c |
| 29 | + .to_str() |
| 30 | + .context("Path {s} has an invalid Unicode character")?; |
| 31 | + check_valid_path_component(s)?; |
| 32 | + }, |
| 33 | + // Component paths are allowed to have `..` (since they're relative from the root |
| 34 | + // component's source directory). |
| 35 | + PathComponent::ParentDir => (), |
| 36 | + PathComponent::RootDir => { |
| 37 | + anyhow::bail!("Component paths must be relative ({s} is absolute).") |
| 38 | + }, |
| 39 | + c => anyhow::bail!("Invalid path component {c:?} in {s}."), |
| 40 | + } |
| 41 | + } |
| 42 | + path.as_os_str() |
| 43 | + .to_str() |
| 44 | + .context("Path {s} has an invalid Unicode character")?; |
| 45 | + Ok(ComponentDefinitionPath { path }) |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +impl Deref for ComponentDefinitionPath { |
| 50 | + type Target = str; |
| 51 | + |
| 52 | + fn deref(&self) -> &Self::Target { |
| 53 | + self.path |
| 54 | + .as_os_str() |
| 55 | + .to_str() |
| 56 | + .expect("Invalid Unicode in ComponentDefinitionPath") |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +impl From<ComponentDefinitionPath> for String { |
| 61 | + fn from(value: ComponentDefinitionPath) -> Self { |
| 62 | + value |
| 63 | + .path |
| 64 | + .into_os_string() |
| 65 | + .into_string() |
| 66 | + .expect("Invalid Unicode in ComponentDefinitionPath?") |
| 67 | + } |
| 68 | +} |
0 commit comments