Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Account for alignment when truncating #402

Merged
merged 1 commit into from Mar 17, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
48 changes: 44 additions & 4 deletions src/style.rs
Expand Up @@ -319,6 +319,12 @@ impl ProgressStyle {
}
};

if buf == "\x00" {
// Don't expand for wide elements
cur.push_str(&buf);
continue;
}

match width {
Some(width) => {
let padded = PaddedStringDisplay {
Expand Down Expand Up @@ -625,11 +631,20 @@ struct PaddedStringDisplay<'a> {
impl<'a> fmt::Display for PaddedStringDisplay<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let cols = measure_text_width(self.str);
if cols >= self.width {
return match self.truncate {
true => f.write_str(self.str.get(..self.width).unwrap_or(self.str)),
false => f.write_str(self.str),
let excess = cols.saturating_sub(self.width);
if excess > 0 && !self.truncate {
return f.write_str(self.str);
} else if excess > 0 {
let (start, end) = match self.align {
Alignment::Left => (0, self.str.len() - excess),
Alignment::Right => (excess, self.str.len()),
Alignment::Center => (
excess / 2,
self.str.len() - excess.saturating_sub(excess / 2),
),
};

return f.write_str(self.str.get(start..end).unwrap_or(self.str));
}

let diff = self.width.saturating_sub(cols);
Expand Down Expand Up @@ -716,4 +731,29 @@ mod tests {
style.format_state(&state, &mut buf, WIDTH);
assert_eq!(&buf[0], "\u{1b}[31m\u{1b}[44m XXX \u{1b}[0m");
}

#[test]
fn align_truncation() {
const WIDTH: u16 = 10;
let pos = Arc::new(AtomicPosition::default());
let state = ProgressState::new(10, pos);
let mut buf = Vec::new();

let mut style = ProgressStyle::with_template("{wide_msg}").unwrap();
style.message = "abcdefghijklmnopqrst".into();
style.format_state(&state, &mut buf, WIDTH);
assert_eq!(&buf[0], "abcdefghij");

buf.clear();
let mut style = ProgressStyle::with_template("{wide_msg:>}").unwrap();
style.message = "abcdefghijklmnopqrst".into();
style.format_state(&state, &mut buf, WIDTH);
assert_eq!(&buf[0], "klmnopqrst");

buf.clear();
let mut style = ProgressStyle::with_template("{wide_msg:^}").unwrap();
style.message = "abcdefghijklmnopqrst".into();
style.format_state(&state, &mut buf, WIDTH);
assert_eq!(&buf[0], "fghijklmno");
}
}