Files
cull-gmail/src/utils.rs
Jeremiah Russell 65f8bf7fc5 feat(utils): implement string elision trait
- introduce `Elide` trait for string truncation
- add `elide` function to truncate strings longer than a specified length, adding " ..." at the end
2025-10-06 17:09:47 +01:00

55 lines
1.3 KiB
Rust

use std::{env, fs, io};
use crate::Error;
pub(crate) fn assure_config_dir_exists(dir: &str) -> Result<String, Error> {
let trdir = dir.trim();
if trdir.is_empty() {
return Err(Error::DirectoryUnset);
}
let expanded_config_dir = if trdir.as_bytes()[0] == b'~' {
match env::var("HOME")
.ok()
.or_else(|| env::var("UserProfile").ok())
{
None => {
return Err(Error::HomeExpansionFailed(trdir.to_string()));
}
Some(mut user) => {
user.push_str(&trdir[1..]);
user
}
}
} else {
trdir.to_string()
};
if let Err(err) = fs::create_dir(&expanded_config_dir) {
if err.kind() != io::ErrorKind::AlreadyExists {
return Err(Error::DirectoryCreationFailed((
expanded_config_dir,
Box::new(err),
)));
}
}
Ok(expanded_config_dir)
}
pub(crate) trait Elide {
fn elide(&mut self, to: usize) -> &mut Self;
}
impl Elide for String {
fn elide(&mut self, to: usize) -> &mut Self {
if self.len() <= to {
self
} else {
let range = to - 4;
self.replace_range(range.., " ...");
self
}
}
}