[pbs-devel] [PATCH proxmox] cli/text_table: calculate correct column width for unicode characters
Dominik Csapak
d.csapak at proxmox.com
Mon Sep 27 14:02:50 CEST 2021
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 at proxmox.com>
---
not strictly necessary, but was easy enough to do, makes printing with unicode
characters nicer and only needs one dependency which must be available anyway...
proxmox/Cargo.toml | 1 +
proxmox/src/api/cli/text_table.rs | 8 +++++---
2 files changed, 6 insertions(+), 3 deletions(-)
diff --git a/proxmox/Cargo.toml b/proxmox/Cargo.toml
index b901969..73da51c 100644
--- a/proxmox/Cargo.toml
+++ b/proxmox/Cargo.toml
@@ -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 }
diff --git a/proxmox/src/api/cli/text_table.rs b/proxmox/src/api/cli/text_table.rs
index 84d9f34..d136629 100644
--- a/proxmox/src/api/cli/text_table.rs
+++ b/proxmox/src/api/cli/text_table.rs
@@ -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 {
--
2.30.2
More information about the pbs-devel
mailing list