cli/text_table: calculate correct column width for unicode characters

When printing unicode text, a glyph can take up more (or less) space than
a single column. To handle that, use the 'unicode-width' crate which
calculates the width by the unicode standard.

This makes the text tables correctly aligned when printing unicode
characters (e.g. in a datastore/user/syncjob comment).

'unicode-width' is used itself in the rust compiler to format errors
(see e.g. the Cargo.toml in /compiler/rustc_errors of the rust git)

Signed-off-by: Dominik Csapak <d.csapak@proxmox.com>
This commit is contained in:
Dominik Csapak 2021-09-27 14:02:50 +02:00 committed by Dietmar Maurer
parent 5a37cfd4c0
commit 5a88aaf074
2 changed files with 6 additions and 3 deletions

View File

@ -17,6 +17,7 @@ anyhow = "1.0"
lazy_static = "1.4"
libc = "0.2"
nix = "0.19.1"
unicode-width ="0.1.8"
# tools module:
base32 = { version = "0.4", optional = true }

View File

@ -2,6 +2,7 @@ use std::io::Write;
use anyhow::*;
use serde_json::Value;
use unicode_width::UnicodeWidthStr;
use crate::api::schema::*;
@ -472,7 +473,7 @@ fn format_table<W: Write>(
let lines: Vec<String> = text
.lines()
.map(|line| {
let width = line.chars().count();
let width = UnicodeWidthStr::width(line);
if width > max_width {
max_width = width;
}
@ -564,10 +565,11 @@ fn render_table<W: Write>(
text.push(' ');
}
let padding = column.width - UnicodeWidthStr::width(line.as_str());
if column.right_align {
text.push_str(&format!("{:>width$}", line, width = column.width));
text.push_str(&format!("{:>width$}{}", "", line, width = padding));
} else {
text.push_str(&format!("{:<width$}", line, width = column.width));
text.push_str(&format!("{}{:<width$}", line, "", width = padding));
}
if !options.noborder {