use serde_json::{Value, json};
pub(super) const MAX_CONTEXT_CHARS: usize = 1500;
const ELLIPSIS: char = '…';
pub(super) fn reply(event: &str, text: String) -> Value {
json!({
"hookSpecificOutput": {
"hookEventName": event,
"additionalContext": text,
}
})
}
pub(super) fn one_line(text: &str) -> String {
text.split_whitespace().collect::<Vec<_>>().join(" ")
}
pub(super) fn fit(room: usize, lines: &[(String, String)]) -> Vec<Option<String>> {
let mut order: Vec<usize> = (0..lines.len()).collect();
order.sort_by_key(|&i| lines[i].0.chars().count() + lines[i].1.chars().count());
let mut left = room;
let mut fitted = vec![None; lines.len()];
for (n, &i) in order.iter().enumerate() {
let (prefix, body) = &lines[i];
let share = left / (lines.len() - n);
let line = cut(prefix, body, share.saturating_sub(1));
if let Some(line) = &line {
left -= line.chars().count() + 1;
}
fitted[i] = line;
}
fitted
}
fn cut(prefix: &str, body: &str, room: usize) -> Option<String> {
let fixed = prefix.chars().count();
if fixed + body.chars().count() <= room {
return Some(format!("{prefix}{body}"));
}
let keep = room.checked_sub(fixed + 1).filter(|&keep| keep > 0)?;
let kept: String = body.chars().take(keep).collect();
Some(format!("{prefix}{}{ELLIPSIS}", kept.trim_end()))
}
#[cfg(test)]
mod tests {
use super::*;
fn line(prefix: &str, body: &str) -> (String, String) {
(prefix.to_string(), body.to_string())
}
#[test]
fn short_lines_are_kept_whole() {
let lines = [line("- ", "one"), line("- ", "two")];
assert_eq!(
fit(100, &lines),
[Some("- one".to_string()), Some("- two".to_string())]
);
}
#[test]
fn long_bodies_share_the_room_and_end_in_an_ellipsis() {
let lines = [line("- ", &"a".repeat(100)), line("- ", &"b".repeat(100))];
let fitted = fit(40, &lines);
let used: usize = fitted.iter().flatten().map(|l| l.chars().count() + 1).sum();
assert!(used <= 40, "{fitted:?}");
assert_eq!(
fitted[0].as_deref(),
Some(&*format!("- {}…", "a".repeat(16)))
);
assert_eq!(
fitted[1].as_deref(),
Some(&*format!("- {}…", "b".repeat(16)))
);
}
#[test]
fn a_line_without_room_for_its_body_is_dropped_and_its_share_passes_on() {
let lines = [line(&"p".repeat(30), "body"), line("- ", &"b".repeat(100))];
let fitted = fit(40, &lines);
assert_eq!(fitted[0], None);
assert_eq!(
fitted[1].as_deref(),
Some(&*format!("- {}…", "b".repeat(36)))
);
}
#[test]
fn room_short_lines_leave_goes_to_a_long_one_before_them() {
let lines = [
line("- ", &"a".repeat(1200)),
line("- ", &"b".repeat(50)),
line("- ", &"c".repeat(50)),
];
let fitted = fit(1350, &lines);
assert_eq!(
fitted,
[
Some(format!("- {}", "a".repeat(1200))),
Some(format!("- {}", "b".repeat(50))),
Some(format!("- {}", "c".repeat(50))),
]
);
}
#[test]
fn whitespace_collapses_to_single_spaces() {
assert_eq!(one_line(" a\n\tb c \n"), "a b c");
}
}