#![cfg_attr(test, allow(clippy::expect_used, clippy::unwrap_used))]
use std::path::Path;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SessionId(String);
impl SessionId {
pub fn new() -> Self {
Self(ulid::Ulid::new().to_string())
}
pub fn from_string(s: String) -> Self {
Self(s)
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn into_string(self) -> String {
self.0
}
}
impl Default for SessionId {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Display for SessionId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
pub fn encode_cwd(cwd: &Path) -> String {
let s = cwd.to_string_lossy();
let stripped = s.trim_start_matches(['/', '\\']);
let replaced: String = stripped
.chars()
.map(|c| match c {
'/' | '\\' | ':' => '-',
other => other,
})
.collect();
format!("--{replaced}--")
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
#[test]
fn encode_cwd_matches_pi_examples() {
assert_eq!(
encode_cwd(&PathBuf::from("/Users/wade/proj/capo")),
"--Users-wade-proj-capo--"
);
}
#[test]
fn encode_cwd_handles_windows_drive() {
assert_eq!(
encode_cwd(&PathBuf::from("C:\\Users\\wade\\proj")),
"--C--Users-wade-proj--"
);
}
#[test]
fn encode_cwd_handles_root() {
assert_eq!(encode_cwd(&PathBuf::from("/")), "----");
}
#[test]
fn session_id_new_is_26_chars_and_unique() {
let a = SessionId::new();
let b = SessionId::new();
assert_eq!(a.as_str().len(), 26);
assert_eq!(b.as_str().len(), 26);
assert_ne!(a, b);
}
}