|
| 1 | +// This is free and unencumbered software released into the public domain. |
| 2 | + |
| 3 | +use alloc::{borrow::Cow, format, string::String}; |
| 4 | +use asimov_core::Named; |
| 5 | +use camino::Utf8PathBuf; |
| 6 | +use derive_more::Display; |
| 7 | +use std::{ |
| 8 | + io::{Error, ErrorKind, Result}, |
| 9 | + path::Path, |
| 10 | +}; |
| 11 | + |
| 12 | +/// A configuration profile stored on a file system (e.g., `$HOME/.asimov/configs/default/`). |
| 13 | +#[derive(Debug, Display)] |
| 14 | +#[display("ConfigProfile({:?})", path)] |
| 15 | +pub struct ConfigProfile { |
| 16 | + path: Utf8PathBuf, |
| 17 | +} |
| 18 | + |
| 19 | +impl ConfigProfile { |
| 20 | + /// Opens a configuration profile from a file system path. |
| 21 | + pub fn open(path: impl AsRef<Path>) -> Result<Self> { |
| 22 | + let path = path.as_ref(); |
| 23 | + if !path.exists() { |
| 24 | + std::fs::create_dir_all(path)?; |
| 25 | + } |
| 26 | + let path = Utf8PathBuf::from_path_buf(path.to_path_buf()).map_err(|e| { |
| 27 | + Error::new( |
| 28 | + ErrorKind::InvalidFilename, |
| 29 | + format!("failed to open non-UTF-8 path: {}", e.display()), |
| 30 | + ) |
| 31 | + })?; |
| 32 | + Ok(ConfigProfile { path }) |
| 33 | + } |
| 34 | + |
| 35 | + /// The name of the configuration profile (e.g., "default"). |
| 36 | + fn name(&self) -> Cow<'_, str> { |
| 37 | + if let Some(name) = self.path.file_name() { |
| 38 | + return Cow::Borrowed(name); |
| 39 | + } |
| 40 | + self.path |
| 41 | + .canonicalize_utf8() |
| 42 | + .ok() |
| 43 | + .and_then(|p| p.file_name().map(String::from)) |
| 44 | + .map_or(Cow::default(), Cow::Owned) |
| 45 | + } |
| 46 | + |
| 47 | + pub fn as_str(&self) -> &str { |
| 48 | + self.path.as_str() |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +impl AsRef<str> for ConfigProfile { |
| 53 | + fn as_ref(&self) -> &str { |
| 54 | + self.path.as_str() |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +impl AsRef<Path> for ConfigProfile { |
| 59 | + fn as_ref(&self) -> &Path { |
| 60 | + self.path.as_std_path() |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +#[cfg(feature = "camino")] |
| 65 | +impl AsRef<Utf8Path> for ConfigProfile { |
| 66 | + fn as_ref(&self) -> &Utf8Path { |
| 67 | + self.path.as_path() |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +impl Named for ConfigProfile { |
| 72 | + fn name(&self) -> Cow<'_, str> { |
| 73 | + self.name() |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +impl crate::ConfigProfile for ConfigProfile { |
| 78 | + fn prompt(&self) -> Option<String> { |
| 79 | + None // TODO |
| 80 | + } |
| 81 | +} |
0 commit comments