From 3a36b10e3a4eb9aa6608d86c18af284a6caf58b3 Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Thu, 28 Mar 2024 20:19:04 +0100 Subject: [PATCH] Truncate commit messages in blame tooltip (#9937) This truncates git commit messages to 15 lines. Before: ![screenshot-2024-03-28-20 10 17@2x](https://github.com/zed-industries/zed/assets/1185253/03bea6bb-2ead-4bf6-bb12-22338c8745fd) After: ![screenshot-2024-03-28-20 10 02@2x](https://github.com/zed-industries/zed/assets/1185253/0bd655ee-57ce-424f-b471-b7ce01e5fbf7) Release Notes: - N/A --- crates/editor/src/element.rs | 7 ++----- crates/util/src/util.rs | 40 ++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/crates/editor/src/element.rs b/crates/editor/src/element.rs index 79cd78fe89..b3b3d3013d 100644 --- a/crates/editor/src/element.rs +++ b/crates/editor/src/element.rs @@ -3011,11 +3011,8 @@ impl Render for BlameEntryTooltip { }; let message = match &self.commit_message { - Some(message) => message.clone(), - None => { - println!("can't find commit message"); - self.blame_entry.summary.clone().unwrap_or_default() - } + Some(message) => util::truncate_lines_and_trailoff(message, 15), + None => self.blame_entry.summary.clone().unwrap_or_default(), }; let pretty_commit_id = format!("{}", self.blame_entry.sha); diff --git a/crates/util/src/util.rs b/crates/util/src/util.rs index 573ef512ab..30ca1b9b71 100644 --- a/crates/util/src/util.rs +++ b/crates/util/src/util.rs @@ -90,6 +90,19 @@ pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String { } } +/// Takes only `max_lines` from the string and, if there were more than `max_lines-1`, appends a +/// a newline and "..." to the string, so that `max_lines` are returned. +/// Returns string unchanged if its length is smaller than max_lines. +pub fn truncate_lines_and_trailoff(s: &str, max_lines: usize) -> String { + let mut lines = s.lines().take(max_lines).collect::>(); + if lines.len() > max_lines - 1 { + lines.pop(); + lines.join("\n") + "\n…" + } else { + lines.join("\n") + } +} + pub fn post_inc + AddAssign + Copy>(value: &mut T) -> T { let prev = *value; *value += T::from(1); @@ -614,4 +627,31 @@ mod tests { assert_eq!(word_consists_of_emojis(text), expected_result); } } + + #[test] + fn test_truncate_lines_and_trailoff() { + let text = r#"Line 1 +Line 2 +Line 3"#; + + assert_eq!( + truncate_lines_and_trailoff(text, 2), + r#"Line 1 +…"# + ); + + assert_eq!( + truncate_lines_and_trailoff(text, 3), + r#"Line 1 +Line 2 +…"# + ); + + assert_eq!( + truncate_lines_and_trailoff(text, 4), + r#"Line 1 +Line 2 +Line 3"# + ); + } }