use std::{borrow::Cow, cmp::Ordering, num::NonZeroUsize, path::Path};
use super::{session_root, Session, SessionListing, SessionSummary};
pub(crate) const DEFAULT_PAGE_SIZE: NonZeroUsize = NonZeroUsize::new(100).unwrap();
const PREVIEW_CHARS: usize = 80;
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct CatalogPage {
pub(crate) sessions: Vec<SessionSummary>,
pub(crate) next_cursor: Option<String>,
}
#[derive(Debug, thiserror::Error)]
pub(crate) enum CatalogError {
#[error("cwd must be an absolute path")]
RelativeCwd,
#[error("unknown session list cursor '{0}'")]
UnknownCursor(String),
#[error(transparent)]
Store(anyhow::Error),
}
pub(crate) fn list(
cwd: Option<&Path>,
cursor: Option<&str>,
limit: NonZeroUsize,
) -> Result<CatalogPage, CatalogError> {
let root = session_root().map_err(CatalogError::Store)?;
list_in_root(&root, cwd, cursor, limit)
}
fn list_in_root(
root: &Path,
cwd: Option<&Path>,
cursor: Option<&str>,
limit: NonZeroUsize,
) -> Result<CatalogPage, CatalogError> {
if cwd.is_some_and(|cwd| !cwd.is_absolute()) {
return Err(CatalogError::RelativeCwd);
}
let after = cursor
.map(|cursor| {
Cursor::parse(cursor).ok_or_else(|| CatalogError::UnknownCursor(cursor.into()))
})
.transpose()?;
let summaries = match cwd {
Some(cwd) => match crate::paths::canonicalize(cwd) {
Ok(cwd) if cwd.is_dir() => {
Session::list_in_root(root, &cwd, SessionListing::PersonFacing)
}
Ok(_) | Err(_) => Ok(Vec::new()),
},
None => Session::list_all_in_root(root, SessionListing::PersonFacing),
}
.map_err(CatalogError::Store)?;
Ok(page(summaries, after.as_ref(), limit))
}
fn page(
mut summaries: Vec<SessionSummary>,
after: Option<&Cursor<'_>>,
limit: NonZeroUsize,
) -> CatalogPage {
let limit = limit.get();
summaries.retain(|summary| {
summary.has_messages()
&& summary.cwd.is_dir()
&& after.is_none_or(|after| after.precedes(summary))
});
summaries.sort_by(|left, right| Cursor::at(left).cmp_list_order(&Cursor::at(right)));
let next_cursor = summaries
.get(limit)
.map(|_| Cursor::at(&summaries[limit - 1]).encode());
summaries.truncate(limit);
for summary in &mut summaries {
summary.added_dirs.retain(|dir| dir.is_dir());
}
CatalogPage {
sessions: summaries,
next_cursor,
}
}
pub(crate) fn preview(message: &str) -> Option<String> {
let line = message.split_whitespace().collect::<Vec<_>>().join(" ");
if line.is_empty() {
return None;
}
if line.chars().count() <= PREVIEW_CHARS {
return Some(line);
}
let mut cut = line.chars().take(PREVIEW_CHARS - 1).collect::<String>();
cut.push('…');
Some(cut)
}
#[derive(Debug, PartialEq, Eq)]
struct Cursor<'a> {
updated_at: u64,
id: Cow<'a, str>,
cwd: Cow<'a, str>,
}
impl<'a> Cursor<'a> {
fn at(summary: &'a SessionSummary) -> Self {
Self {
updated_at: summary.updated_at,
id: Cow::Borrowed(&summary.id),
cwd: summary.cwd.to_string_lossy(),
}
}
fn encode(&self) -> String {
serde_json::json!([self.updated_at, self.id, self.cwd]).to_string()
}
fn parse(cursor: &str) -> Option<Cursor<'static>> {
serde_json::from_str::<(u64, String, String)>(cursor)
.ok()
.map(|(updated_at, id, cwd)| Cursor {
updated_at,
id: Cow::Owned(id),
cwd: Cow::Owned(cwd),
})
}
fn cmp_list_order(&self, other: &Cursor<'_>) -> Ordering {
other
.updated_at
.cmp(&self.updated_at)
.then_with(|| self.id.cmp(&other.id))
.then_with(|| self.cwd.cmp(&other.cwd))
}
fn precedes(&self, summary: &SessionSummary) -> bool {
self.cmp_list_order(&Cursor::at(summary)) == Ordering::Less
}
}
#[cfg(test)]
#[path = "catalog_tests.rs"]
mod tests;