fix https://github.com/nushell/nushell/issues/7380
This commit is contained in:
Maxim Zhiburt
2022-12-15 17:47:04 +03:00
committed by GitHub
parent b6683a3010
commit 33aea56ccd
16 changed files with 1006 additions and 609 deletions

View File

@ -11,7 +11,6 @@ version = "0.72.2"
nu-ansi-term = "0.46.0"
nu-protocol = { path = "../nu-protocol", version = "0.72.2" }
nu-utils = { path = "../nu-utils", version = "0.72.2" }
atty = "0.2.14"
tabled = { version = "0.10.0", features = ["color"], default-features = false }
json_to_table = { version = "0.2.0", features = ["color"] }
json_to_table = { version = "0.3.1", features = ["color"] }
serde_json = "1"

View File

@ -1,6 +1,4 @@
use nu_protocol::Config;
use nu_table::{Alignments, Table, TableTheme, TextStyle};
use std::collections::HashMap;
use nu_table::{Table, TableConfig, TableTheme, TextStyle};
use tabled::papergrid::records::{cell_info::CellInfo, tcell::TCell};
fn main() {
@ -19,30 +17,28 @@ fn main() {
// The mocked up table data
let (table_headers, row_data) = make_table_data();
// The table headers
let headers = vec_of_str_to_vec_of_styledstr(&table_headers, true);
// The table rows
let rows = vec_of_str_to_vec_of_styledstr(&row_data, false);
// The table itself
let count_cols = std::cmp::max(rows.len(), headers.len());
let mut rows = vec![rows; 3];
rows.insert(0, headers);
let table = Table::new(rows, (3, count_cols), width, true, false);
// FIXME: Config isn't available from here so just put these here to compile
let color_hm: HashMap<String, nu_ansi_term::Style> = HashMap::new();
// get the default config
let config = Config::default();
let theme = TableTheme::rounded();
let table_cfg = TableConfig::new(theme, true, false, false);
let table = Table::new(rows, (3, count_cols));
// Capture the table as a string
let output_table = table
.draw_table(
&config,
&color_hm,
Alignments::default(),
&TableTheme::rounded(),
width,
false,
)
.draw(table_cfg, width)
.unwrap_or_else(|| format!("Couldn't fit table into {} columns!", width));
// Draw the table
println!("{}", output_table)
}

View File

@ -2,54 +2,10 @@ mod nu_protocol_table;
mod table;
mod table_theme;
mod textstyle;
mod util;
pub use nu_protocol_table::NuTable;
pub use table::{Alignments, Table};
pub use table::{Alignments, Table, TableConfig};
pub use table_theme::TableTheme;
pub use textstyle::{Alignment, TextStyle};
use tabled::{Padding, Style, Width};
pub fn string_width(text: &str) -> usize {
tabled::papergrid::util::string_width_multiline_tab(text, 4)
}
pub fn wrap_string(text: &str, width: usize) -> String {
// well... it's not effitient to build a table to wrap a string,
// but ... it's better than a copy paste
tabled::builder::Builder::from_iter([[text]])
.build()
.with(Padding::zero())
.with(Style::empty())
.with(Width::wrap(width))
.to_string()
}
pub fn string_truncate(text: &str, width: usize) -> String {
// todo: change me...
match text.lines().next() {
Some(first_line) => tabled::builder::Builder::from_iter([[first_line]])
.build()
.with(tabled::Style::empty())
.with(tabled::Padding::zero())
.with(tabled::Width::truncate(width))
.to_string(),
None => String::new(),
}
}
pub fn string_wrap(text: &str, width: usize) -> String {
// todo: change me...
if text.is_empty() {
return String::new();
}
tabled::builder::Builder::from_iter([[text]])
.build()
.with(tabled::Style::empty())
.with(tabled::Padding::zero())
.with(tabled::Width::wrap(width))
.to_string()
}
pub use util::*;

View File

@ -1,9 +1,12 @@
use std::collections::HashMap;
use nu_protocol::{Config, Span, Value};
use tabled::{color::Color, papergrid::records::Records, Table};
use tabled::{
color::Color, formatting::AlignmentStrategy, object::Segment, papergrid::records::Records,
Alignment, Modify, Table,
};
use crate::{table::TrimStrategyModifier, TableTheme};
use crate::{table::TrimStrategyModifier, Alignments, TableTheme};
/// NuTable has a recursive table representation of nu_prorocol::Value.
///
@ -215,4 +218,10 @@ fn load_theme<R>(
table.with(color);
}
}
table.with(
Modify::new(Segment::all())
.with(Alignment::Horizontal(Alignments::default().data))
.with(AlignmentStrategy::PerLine),
);
}

View File

@ -1,6 +1,7 @@
use std::{collections::HashMap, fmt::Display};
use std::{cmp::min, collections::HashMap, fmt::Display};
use nu_protocol::{Config, FooterMode, TrimStrategy};
use nu_ansi_term::Style;
use nu_protocol::TrimStrategy;
use tabled::{
alignment::AlignmentHorizontal,
builder::Builder,
@ -12,8 +13,11 @@ use tabled::{
records::{
cell_info::CellInfo, tcell::TCell, vec_records::VecRecords, Records, RecordsMut,
},
util::string_width_multiline,
width::CfgWidthFunction,
Estimate,
},
peaker::Peaker,
Alignment, Modify, ModifyObject, TableOption, Width,
};
@ -23,9 +27,6 @@ use crate::{table_theme::TableTheme, TextStyle};
#[derive(Debug, Clone)]
pub struct Table {
data: Data,
is_empty: bool,
with_header: bool,
with_index: bool,
}
type Data = VecRecords<TCell<CellInfo<'static>, TextStyle>>;
@ -34,33 +35,22 @@ impl Table {
/// Creates a [Table] instance.
///
/// If `headers.is_empty` then no headers will be rendered.
pub fn new(
mut data: Vec<Vec<TCell<CellInfo<'static>, TextStyle>>>,
size: (usize, usize),
termwidth: usize,
with_header: bool,
with_index: bool,
) -> Table {
pub fn new(data: Vec<Vec<TCell<CellInfo<'static>, TextStyle>>>, size: (usize, usize)) -> Table {
// it's not guaranted that data will have all rows with the same number of columns.
// but VecRecords::with_hint require this constrain.
for row in &mut data {
if row.len() < size.1 {
row.extend(
std::iter::repeat(Self::create_cell(String::default(), TextStyle::default()))
.take(size.1 - row.len()),
);
}
}
//
// so we do a check to make it certainly true
let mut data = VecRecords::with_hint(data, size.1);
let is_empty = maybe_truncate_columns(&mut data, size.1, termwidth);
let mut data = data;
make_data_consistent(&mut data, size);
Table {
data,
is_empty,
with_header,
with_index,
}
let data = VecRecords::with_hint(data, size.1);
Table { data }
}
pub fn count_rows(&self) -> usize {
self.data.count_rows()
}
pub fn create_cell(
@ -70,29 +60,15 @@ impl Table {
TCell::new(CellInfo::new(text.into(), CfgWidthFunction::new(4)), style)
}
pub fn is_empty(&self) -> bool {
self.is_empty
}
pub fn size(&self) -> (usize, usize) {
(self.data.count_rows(), self.data.count_columns())
}
pub fn is_with_index(&self) -> bool {
self.with_index
}
pub fn truncate(&mut self, width: usize, theme: &TableTheme) -> bool {
let mut truncated = false;
while self.data.count_rows() > 0 && self.data.count_columns() > 0 {
let mut table = Builder::custom(self.data.clone()).build();
load_theme(&mut table, &HashMap::new(), theme, false, false);
let total = table.total_width();
// println!("{}", table);
// println!("width={:?} total={:?}", width, total);
drop(table);
let total;
{
let mut table = Builder::custom(self.data.clone()).build();
load_theme(&mut table, theme, false, false, None);
total = table.total_width();
}
if total > width {
truncated = true;
@ -117,19 +93,69 @@ impl Table {
false
}
/// Draws a trable on a String.
/// Converts a table to a String.
///
/// It returns None in case where table cannot be fit to a terminal width.
pub fn draw_table(
self,
config: &Config,
color_hm: &HashMap<String, nu_ansi_term::Style>,
alignments: Alignments,
theme: &TableTheme,
termwidth: usize,
expand: bool,
) -> Option<String> {
draw_table(self, config, color_hm, alignments, theme, termwidth, expand)
pub fn draw(self, config: TableConfig, termwidth: usize) -> Option<String> {
build_table(self.data, config, termwidth)
}
}
fn make_data_consistent(data: &mut Vec<Vec<TCell<CellInfo, TextStyle>>>, size: (usize, usize)) {
for row in data {
if row.len() < size.1 {
row.extend(
std::iter::repeat(Table::create_cell(String::default(), TextStyle::default()))
.take(size.1 - row.len()),
);
}
}
}
#[derive(Debug, Clone)]
pub struct TableConfig {
theme: TableTheme,
alignments: Alignments,
trim: TrimStrategy,
split_color: Option<Style>,
expand: bool,
with_index: bool,
with_header: bool,
with_footer: bool,
}
impl TableConfig {
pub fn new(
theme: TableTheme,
with_header: bool,
with_index: bool,
append_footer: bool,
) -> Self {
Self {
theme,
with_header,
with_index,
with_footer: append_footer,
expand: false,
alignments: Alignments::default(),
trim: TrimStrategy::truncate(None),
split_color: None,
}
}
pub fn expand(mut self) -> Self {
self.expand = true;
self
}
pub fn trim(mut self, strategy: TrimStrategy) -> Self {
self.trim = strategy;
self
}
pub fn splitline_style(mut self, color: Style) -> Self {
self.split_color = Some(color);
self
}
}
@ -150,65 +176,63 @@ impl Default for Alignments {
}
}
fn draw_table(
mut table: Table,
config: &Config,
color_hm: &HashMap<String, nu_ansi_term::Style>,
alignments: Alignments,
theme: &TableTheme,
termwidth: usize,
expand: bool,
) -> Option<String> {
if table.is_empty {
fn build_table(mut data: Data, cfg: TableConfig, termwidth: usize) -> Option<String> {
let priority = TruncationPriority::Content;
let is_empty = maybe_truncate_columns(&mut data, &cfg.theme, termwidth, priority);
if is_empty {
return None;
}
let with_header = table.with_header;
let with_footer = with_header && need_footer(config, (table.data).size().0 as u64);
let with_index = table.with_index;
if with_footer {
table.data.duplicate_row(0);
if cfg.with_footer {
data.duplicate_row(0);
}
let mut table = Builder::custom(table.data).build();
load_theme(&mut table, color_hm, theme, with_footer, with_header);
draw_table(
data,
&cfg.theme,
cfg.alignments,
cfg.with_index,
cfg.with_header,
cfg.with_footer,
cfg.expand,
cfg.split_color,
&cfg.trim,
termwidth,
)
}
#[allow(clippy::too_many_arguments)]
fn draw_table(
data: Data,
theme: &TableTheme,
alignments: Alignments,
with_index: bool,
with_header: bool,
with_footer: bool,
expand: bool,
split_color: Option<Style>,
trim_strategy: &TrimStrategy,
termwidth: usize,
) -> Option<String> {
let mut table = Builder::custom(data).build();
load_theme(&mut table, theme, with_footer, with_header, split_color);
align_table(&mut table, alignments, with_index, with_header, with_footer);
if expand {
table.with(Width::increase(termwidth));
}
table_trim_columns(&mut table, termwidth, &config.trim_strategy);
table_trim_columns(&mut table, termwidth, trim_strategy);
let table = print_table(table, config);
if table_width(&table) > termwidth {
let text = table.to_string();
if string_width_multiline(&text) > termwidth {
None
} else {
Some(table)
Some(text)
}
}
fn print_table(table: tabled::Table<Data>, config: &Config) -> String {
let output = table.to_string();
// the atty is for when people do ls from vim, there should be no coloring there
if !config.use_ansi_coloring || !atty::is(atty::Stream::Stdout) {
// Draw the table without ansi colors
nu_utils::strip_ansi_string_likely(output)
} else {
// Draw the table with ansi colors
output
}
}
fn table_width(table: &str) -> usize {
table
.lines()
.next()
.map_or(0, papergrid::util::string_width)
}
fn align_table(
table: &mut tabled::Table<Data>,
alignments: Alignments,
@ -268,10 +292,10 @@ fn override_alignments(
fn load_theme<R>(
table: &mut tabled::Table<R>,
color_hm: &HashMap<String, nu_ansi_term::Style>,
theme: &TableTheme,
with_footer: bool,
with_header: bool,
separator_color: Option<Style>,
) where
R: Records,
{
@ -282,7 +306,7 @@ fn load_theme<R>(
table.with(theme);
if let Some(color) = color_hm.get("separator") {
if let Some(color) = separator_color {
let color = color.paint(" ").to_string();
if let Ok(color) = Color::try_from(color) {
table.with(color);
@ -298,11 +322,6 @@ fn load_theme<R>(
}
}
fn need_footer(config: &Config, count_records: u64) -> bool {
matches!(config.footer_mode, FooterMode::RowCount(limit) if count_records > limit)
|| matches!(config.footer_mode, FooterMode::Always)
}
struct FooterStyle;
impl<R> TableOption<R> for FooterStyle
@ -352,7 +371,7 @@ where
fn change(&mut self, table: &mut tabled::Table<R>) {
match self.trim_strategy {
TrimStrategy::Wrap { try_to_keep_words } => {
let mut w = Width::wrap(self.termwidth).priority::<tabled::peaker::PriorityMax>();
let mut w = Width::wrap(self.termwidth).priority::<PriorityMax>();
if *try_to_keep_words {
w = w.keep_words();
}
@ -360,8 +379,7 @@ where
w.change(table)
}
TrimStrategy::Truncate { suffix } => {
let mut w =
Width::truncate(self.termwidth).priority::<tabled::peaker::PriorityMax>();
let mut w = Width::truncate(self.termwidth).priority::<PriorityMax>();
if let Some(suffix) = suffix {
w = w.suffix(suffix).suffix_try_color(true);
}
@ -372,20 +390,188 @@ where
}
}
fn maybe_truncate_columns(data: &mut Data, length: usize, termwidth: usize) -> bool {
// Make sure we have enough space for the columns we have
let max_num_of_columns = termwidth / 10;
if max_num_of_columns == 0 {
enum TruncationPriority {
// VERSION where we are showing AS LITTLE COLUMNS AS POSSIBLE but WITH AS MUCH CONTENT AS POSSIBLE.
Content,
// VERSION where we are showing AS MANY COLUMNS AS POSSIBLE but as a side affect they MIGHT CONTAIN AS LITTLE CONTENT AS POSSIBLE
//
// not used so far.
#[allow(dead_code)]
Columns,
}
fn maybe_truncate_columns(
data: &mut Data,
theme: &TableTheme,
termwidth: usize,
priority: TruncationPriority,
) -> bool {
if data.count_columns() == 0 {
return true;
}
// If we have too many columns, truncate the table
if max_num_of_columns < length {
data.truncate(max_num_of_columns);
data.push(Table::create_cell(
String::from("..."),
TextStyle::default(),
));
match priority {
TruncationPriority::Content => truncate_columns_by_content(data, theme, termwidth),
TruncationPriority::Columns => truncate_columns_by_columns(data, theme, termwidth),
}
}
// VERSION where we are showing AS LITTLE COLUMNS AS POSSIBLE but WITH AS MUCH CONTENT AS POSSIBLE.
fn truncate_columns_by_content(data: &mut Data, theme: &TableTheme, termwidth: usize) -> bool {
const MIN_ACCEPTABLE_WIDTH: usize = 3;
const TRAILING_COLUMN_WIDTH: usize = 5;
const TRAILING_COLUMN_STR: &str = "...";
let config;
let total;
{
let mut table = Builder::custom(&*data).build();
load_theme(&mut table, theme, false, false, None);
total = table.total_width();
config = table.get_config().clone();
}
if total <= termwidth {
return false;
}
let mut width_ctrl = tabled::papergrid::width::WidthEstimator::default();
width_ctrl.estimate(&*data, &config);
let widths = Vec::from(width_ctrl);
let borders = config.get_borders();
let vertical_border_i = borders.has_vertical() as usize;
let mut width = borders.has_left() as usize + borders.has_right() as usize;
let mut truncate_pos = 0;
for column_width in widths {
width += column_width;
width += vertical_border_i;
if width >= termwidth {
// check whether we CAN limit the column width
width -= column_width;
width += MIN_ACCEPTABLE_WIDTH;
if width <= termwidth {
truncate_pos += 1;
}
break;
}
truncate_pos += 1;
}
// we don't need any truncation then (is it possible?)
if truncate_pos + 1 == data.count_columns() {
return false;
}
if truncate_pos == 0 {
return true;
}
data.truncate(truncate_pos);
// Append columns with a trailing column
let min_width = borders.has_left() as usize
+ borders.has_right() as usize
+ data.count_columns() * MIN_ACCEPTABLE_WIDTH
+ (data.count_columns() - 1) * vertical_border_i;
let diff = termwidth - min_width;
let can_be_squeezed = diff > TRAILING_COLUMN_WIDTH + vertical_border_i;
if can_be_squeezed {
let cell = Table::create_cell(String::from(TRAILING_COLUMN_STR), TextStyle::default());
data.push(cell);
} else {
if data.count_columns() == 1 {
return true;
}
data.truncate(data.count_columns() - 1);
let cell = Table::create_cell(String::from(TRAILING_COLUMN_STR), TextStyle::default());
data.push(cell);
}
false
}
fn truncate_columns_by_columns(data: &mut Data, theme: &TableTheme, termwidth: usize) -> bool {
const MIN_ACCEPTABLE_WIDTH: usize = 3;
const TRAILING_COLUMN_WIDTH: usize = 3;
const TRAILING_COLUMN_PADDING: usize = 2;
const TRAILING_COLUMN_STR: &str = "...";
let config;
let total;
{
let mut table = Builder::custom(&*data).build();
load_theme(&mut table, theme, false, false, None);
total = table.total_width();
config = table.get_config().clone();
}
if total <= termwidth {
return false;
}
let mut width_ctrl = tabled::papergrid::width::WidthEstimator::default();
width_ctrl.estimate(&*data, &config);
let widths = Vec::from(width_ctrl);
let widths_total = widths.iter().sum::<usize>();
let min_widths = widths
.iter()
.map(|w| min(*w, MIN_ACCEPTABLE_WIDTH))
.sum::<usize>();
let mut min_total = total - widths_total + min_widths;
if min_total <= termwidth {
return false;
}
while data.count_columns() > 0 {
let column = data.count_columns() - 1;
data.truncate(column);
let width = widths[column];
let min_width = min(width, MIN_ACCEPTABLE_WIDTH);
min_total -= min_width;
if config.get_borders().has_vertical() {
min_total -= 1;
}
if min_total <= termwidth {
break;
}
}
if data.count_columns() == 0 {
return true;
}
// Append columns with a trailing column
let diff = termwidth - min_total;
if diff > TRAILING_COLUMN_WIDTH + TRAILING_COLUMN_PADDING {
let cell = Table::create_cell(String::from(TRAILING_COLUMN_STR), TextStyle::default());
data.push(cell);
} else {
if data.count_columns() == 1 {
return true;
}
data.truncate(data.count_columns() - 1);
let cell = Table::create_cell(String::from(TRAILING_COLUMN_STR), TextStyle::default());
data.push(cell);
}
false
@ -410,3 +596,27 @@ impl papergrid::Color for TextStyle {
Ok(())
}
}
/// The same as [`tabled::peaker::PriorityMax`] but prioritizes left columns first in case of equal width.
#[derive(Debug, Default, Clone)]
pub struct PriorityMax;
impl Peaker for PriorityMax {
fn create() -> Self {
Self
}
fn peak(&mut self, _: &[usize], widths: &[usize]) -> Option<usize> {
let col = (0..widths.len()).rev().max_by_key(|&i| widths[i]);
match col {
Some(col) => {
if widths[col] == 0 {
None
} else {
Some(col)
}
}
None => None,
}
}
}

View File

@ -0,0 +1,54 @@
use tabled::{builder::Builder, Padding, Style, Width};
pub fn string_width(text: &str) -> usize {
tabled::papergrid::util::string_width_multiline_tab(text, 4)
}
pub fn wrap_string(text: &str, width: usize) -> String {
// todo: change me...
//
// well... it's not effitient to build a table to wrap a string,
// but ... it's better than a copy paste (is it?)
if text.is_empty() {
return String::new();
}
Builder::from_iter([[text]])
.build()
.with(Padding::zero())
.with(Style::empty())
.with(Width::wrap(width))
.to_string()
}
pub fn string_truncate(text: &str, width: usize) -> String {
// todo: change me...
let line = match text.lines().next() {
Some(first_line) => first_line,
None => return String::new(),
};
Builder::from_iter([[line]])
.build()
.with(Style::empty())
.with(Padding::zero())
.with(Width::truncate(width))
.to_string()
}
pub fn string_wrap(text: &str, width: usize) -> String {
// todo: change me...
if text.is_empty() {
return String::new();
}
Builder::from_iter([[text]])
.build()
.with(Style::empty())
.with(Padding::zero())
.with(Width::wrap(width))
.to_string()
}

View File

@ -0,0 +1,68 @@
use nu_table::{string_width, Table, TableConfig, TextStyle};
use tabled::papergrid::records::{cell_info::CellInfo, tcell::TCell};
pub type VecCells = Vec<Vec<TCell<CellInfo<'static>, TextStyle>>>;
#[allow(dead_code)]
pub struct TestCase {
cfg: TableConfig,
termwidth: usize,
expected: Option<String>,
}
impl TestCase {
#[allow(dead_code)]
pub fn new(cfg: TableConfig, termwidth: usize, expected: Option<String>) -> Self {
Self {
cfg,
termwidth,
expected,
}
}
}
#[allow(dead_code)]
pub fn test_table<I>(data: VecCells, tests: I)
where
I: IntoIterator<Item = TestCase>,
{
for (i, test) in tests.into_iter().enumerate() {
let actual = create_table(data.clone(), test.cfg.clone(), test.termwidth);
assert_eq!(
actual, test.expected,
"\nfail i={:?} termwidth={}",
i, test.termwidth
);
if let Some(table) = actual {
assert!(string_width(&table) <= test.termwidth);
}
}
}
pub fn create_table(data: VecCells, config: TableConfig, termwidth: usize) -> Option<String> {
let mut size = (0, 0);
for row in &data {
size.0 += 1;
size.1 = std::cmp::max(size.1, row.len());
}
let table = Table::new(data, size);
table.draw(config, termwidth)
}
pub fn create_row(count_columns: usize) -> Vec<TCell<CellInfo<'static>, TextStyle>> {
let mut row = Vec::with_capacity(count_columns);
for i in 0..count_columns {
row.push(Table::create_cell(i.to_string(), TextStyle::default()));
}
row
}
#[allow(dead_code)]
pub fn styled_str(s: &str) -> TCell<CellInfo<'static>, TextStyle> {
Table::create_cell(s.to_string(), TextStyle::default())
}

View File

@ -1,211 +1,199 @@
use std::{collections::HashMap, usize};
mod common;
use nu_protocol::{Config, TrimStrategy};
use nu_table::{Alignments, Table, TableTheme as theme, TextStyle};
use tabled::papergrid::records::{cell_info::CellInfo, tcell::TCell};
use nu_protocol::TrimStrategy;
use nu_table::{Table, TableConfig, TableTheme as theme};
use common::{create_row, styled_str, test_table, TestCase, VecCells};
#[test]
fn data_and_header_has_different_size() {
let table = Table::new(
vec![row(3), row(5), row(5)],
(3, 5),
let table = Table::new(vec![create_row(3), create_row(5), create_row(5)], (3, 5));
let table = table.draw(
TableConfig::new(theme::heavy(), true, false, false),
usize::MAX,
true,
false,
);
let table = draw_table(table, usize::MAX, &Config::default());
let expected = "┏━━━┳━━━┳━━━┳━━━┳━━━┓\n\
┃ 0 ┃ 1 ┃ 2 ┃ ┃ ┃\n\
┣━━━╋━━━╋━━━╋━━━╋━━━┫\n\
┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ 4 ┃\n\
┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ 4 ┃\n\
┗━━━┻━━━┻━━━┻━━━┻━━━┛";
assert_eq!(table.as_deref(), Some(expected));
let table = Table::new(
vec![row(5), row(3), row(3)],
(3, 5),
usize::MAX,
true,
false,
assert_eq!(
table.as_deref(),
Some(
"┏━━━┳━━━┳━━━┳━━━┳━━━┓\n\
┃ 0 ┃ 1 ┃ 2 ┃ \n\
┣━━━╋━━━╋━━━╋━━━╋━━━┫\n\
┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ 4 ┃\n\
┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ 4 ┃\n\
┗━━━┻━━━┻━━━┻━━━┻━━━┛"
)
);
let table = draw_table(table, usize::MAX, &Config::default());
let expected = "┏━━━┳━━━┳━━━┳━━━┳━━━┓\n\
┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ 4 ┃\n\
┣━━━╋━━━╋━━━╋━━━╋━━━┫\n\
┃ 0 ┃ 1 ┃ 2 ┃ ┃ ┃\n\
┃ 0 ┃ 1 ┃ 2 ┃ ┃ ┃\n\
┗━━━┻━━━┻━━━┻━━━┻━━━┛";
let table = Table::new(vec![create_row(5), create_row(3), create_row(3)], (3, 5));
assert_eq!(table.as_deref(), Some(expected));
let table = table.draw(
TableConfig::new(theme::heavy(), true, false, false),
usize::MAX,
);
assert_eq!(
table.as_deref(),
Some(
"┏━━━┳━━━┳━━━┳━━━┳━━━┓\n\
┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ 4 ┃\n\
┣━━━╋━━━╋━━━╋━━━╋━━━┫\n\
┃ 0 ┃ 1 ┃ 2 ┃ ┃ ┃\n\
┃ 0 ┃ 1 ┃ 2 ┃ ┃ ┃\n\
┗━━━┻━━━┻━━━┻━━━┻━━━┛"
)
);
}
#[test]
fn termwidth_too_small() {
let cfg = Config::default();
for i in 0..10 {
let table = Table::new(vec![row(3), row(3), row(5)], (3, 5), i, true, false);
assert!(draw_table(table, i, &cfg).is_none());
}
let test_loop = |config: TableConfig| {
for i in 0..10 {
let table = Table::new(vec![create_row(3), create_row(3), create_row(5)], (3, 5));
let table = table.draw(config.clone(), i);
let table = Table::new(vec![row(3), row(3), row(5)], (3, 5), 11, true, false);
assert!(draw_table(table, 11, &cfg).is_some());
let cfg = Config {
trim_strategy: TrimStrategy::Truncate { suffix: None },
..Default::default()
assert!(table.is_none());
}
};
for i in 0..10 {
let table = Table::new(vec![row(3), row(3), row(5)], (3, 5), i, true, false);
assert!(draw_table(table, i, &cfg).is_none());
}
let base_config = TableConfig::new(theme::heavy(), true, false, false);
let table = Table::new(vec![row(3), row(3), row(5)], (3, 5), 11, true, false);
assert!(draw_table(table, 11, &cfg).is_some());
let config = base_config.clone();
test_loop(config);
let config = base_config.clone().trim(TrimStrategy::truncate(None));
test_loop(config);
let config = base_config
.clone()
.trim(TrimStrategy::truncate(Some(String::from("**"))));
test_loop(config);
let config = base_config
.clone()
.trim(TrimStrategy::truncate(Some(String::from(""))));
test_loop(config);
let config = base_config.clone().trim(TrimStrategy::wrap(false));
test_loop(config);
let config = base_config.trim(TrimStrategy::wrap(true));
test_loop(config);
}
#[test]
fn wrap_test() {
let cfg = Config {
trim_strategy: TrimStrategy::Wrap {
try_to_keep_words: false,
},
..Default::default()
};
let tests = [
(0, None),
(1, None),
(2, None),
(3, None),
(4, None),
(5, None),
(6, None),
(7, None),
(8, None),
(9, None),
(10, None),
(11, None),
(12, Some("┏━━━━┳━━━━━┓\n┃ 12 ┃ ... ┃\n┃ 3 ┃ ┃\n┃ 45 ┃ ┃\n┃ 67 ┃ ┃\n┃ 8 ┃ ┃\n┣━━━━╋━━━━━┫\n┃ 0 ┃ ... ┃\n┃ 0 ┃ ... ┃\n┗━━━━┻━━━━━┛")),
(13, Some("┏━━━━━┳━━━━━┓\n┃ 123 ┃ ... ┃\n┃ 45 ┃ ┃\n┃ 678 ┃ ┃\n┣━━━━━╋━━━━━┫\n┃ 0 ┃ ... ┃\n┃ 0 ┃ ... ┃\n┗━━━━━┻━━━━━┛")),
(21, Some("┏━━━━━━┳━━━━━━┳━━━━━┓\n┃ 123 ┃ qweq ┃ ... ┃\n┃ 4567 ┃ w eq ┃ ┃\n┃ 8 ┃ we ┃ ┃\n┣━━━━━━╋━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━┻━━━━━━┻━━━━━┛")),
(29, Some("┏━━━━━━━━━━┳━━━━━━━━━━┳━━━━━┓\n┃ 123 4567 ┃ qweqw eq ┃ ... ┃\n┃ 8 ┃ we ┃ ┃\n┣━━━━━━━━━━╋━━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━━━━━┻━━━━━━━━━━┻━━━━━┛")),
(49, Some("┏━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━┓\n┃ 123 45678 ┃ qweqw eqwe ┃ xxx xx xx x xx ┃ ... ┃\n┃ ┃ ┃ x xx xx ┃ ┃\n┣━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n┗━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━┻━━━━━┛")),
];
for i in 0..10 {
assert!(draw_table(table_with_data(i), i, &cfg).is_none());
}
assert_eq!(draw_table(table_with_data(10), 10, &cfg).unwrap(), "┏━━━━┳━━━┓\n┃ 12 ┃ . ┃\n┃ 3 ┃ . ┃\n┃ 45 ┃ . ┃\n┃ 67 ┃ ┃\n┃ 8 ┃ ┃\n┣━━━━╋━━━┫\n┃ 0 ┃ . ┃\n┃ ┃ . ┃\n┃ ┃ . ┃\n┃ 0 ┃ . ┃\n┃ ┃ . ┃\n┃ ┃ . ┃\n┗━━━━┻━━━┛");
assert_eq!(
draw_table(table_with_data(21), 21, &cfg).unwrap(),
"┏━━━━━━┳━━━━━━┳━━━━━┓\n┃ 123 ┃ qweq ┃ ... ┃\n┃ 4567 ┃ w eq ┃ ┃\n┃ 8 ┃ we ┃ ┃\n┣━━━━━━╋━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━┻━━━━━━┻━━━━━┛"
);
assert_eq!(
draw_table(table_with_data(29), 29, &cfg).unwrap(),
"┏━━━━━━━━━━┳━━━━━━━━━━┳━━━━━┓\n┃ 123 4567 ┃ qweqw eq ┃ ... ┃\n┃ 8 ┃ we ┃ ┃\n┣━━━━━━━━━━╋━━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━━━━━┻━━━━━━━━━━┻━━━━━┛"
);
assert_eq!(
draw_table(table_with_data(49), 49, &cfg).unwrap(),
"┏━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━┓\n┃ 123 4567 ┃ qweqw eq ┃ xxx xx ┃ qqq qqq ┃ ... ┃\n┃ 8 ┃ we ┃ xx x xx ┃ qqqq q ┃ ┃\n┃ ┃ ┃ x xx x ┃ qq qq ┃ ┃\n┃ ┃ ┃ x ┃ ┃ ┃\n┣━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━╋━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ ... ┃\n┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ ... ┃\n┗━━━━━━━━━━┻━━━━━━━━━━┻━━━━━━━━━┻━━━━━━━━━┻━━━━━┛"
);
test_trim(&tests, TrimStrategy::wrap(false));
}
#[test]
fn wrap_keep_words_test() {
let cfg = Config {
trim_strategy: TrimStrategy::Wrap {
try_to_keep_words: true,
},
..Default::default()
};
let tests = [
(0, None),
(1, None),
(2, None),
(3, None),
(4, None),
(5, None),
(6, None),
(7, None),
(8, None),
(9, None),
(10, None),
(11, None),
(12, Some("┏━━━━┳━━━━━┓\n┃ 12 ┃ ... ┃\n┃ 3 ┃ ┃\n┃ 45 ┃ ┃\n┃ 67 ┃ ┃\n┃ 8 ┃ ┃\n┣━━━━╋━━━━━┫\n┃ 0 ┃ ... ┃\n┃ 0 ┃ ... ┃\n┗━━━━┻━━━━━┛")),
(13, Some("┏━━━━━┳━━━━━┓\n┃ 123 ┃ ... ┃\n┃ ┃ ┃\n┃ 456 ┃ ┃\n┃ 78 ┃ ┃\n┣━━━━━╋━━━━━┫\n┃ 0 ┃ ... ┃\n┃ 0 ┃ ... ┃\n┗━━━━━┻━━━━━┛")),
(21, Some("┏━━━━━━┳━━━━━━┳━━━━━┓\n┃ 123 ┃ qweq ┃ ... ┃\n┃ 4567 ┃ w ┃ ┃\n┃ 8 ┃ eqwe ┃ ┃\n┣━━━━━━╋━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━┻━━━━━━┻━━━━━┛")),
(29, Some("┏━━━━━━━━━━┳━━━━━━━━━━┳━━━━━┓\n┃ 123 ┃ qweqw ┃ ... ┃\n┃ 45678 ┃ eqwe ┃ ┃\n┣━━━━━━━━━━╋━━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━━━━━┻━━━━━━━━━━┻━━━━━┛")),
(49, Some("┏━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━┓\n┃ 123 45678 ┃ qweqw eqwe ┃ xxx xx xx x xx ┃ ... ┃\n┃ ┃ ┃ x xx xx ┃ ┃\n┣━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n┗━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━┻━━━━━┛")),
];
for i in 0..10 {
assert!(draw_table(table_with_data(i), i, &cfg).is_none());
}
assert_eq!(draw_table(table_with_data(10), 10, &cfg).unwrap(), "┏━━━━┳━━━┓\n┃ 12 ┃ . ┃\n┃ 3 ┃ . ┃\n┃ 45 ┃ . ┃\n┃ 67 ┃ ┃\n┃ 8 ┃ ┃\n┣━━━━╋━━━┫\n┃ 0 ┃ . ┃\n┃ ┃ . ┃\n┃ ┃ . ┃\n┃ 0 ┃ . ┃\n┃ ┃ . ┃\n┃ ┃ . ┃\n┗━━━━┻━━━┛");
assert_eq!(
draw_table(table_with_data(21), 21, &cfg).unwrap(),
"┏━━━━━━┳━━━━━━┳━━━━━┓\n┃ 123 ┃ qweq ┃ ... ┃\n┃ 4567 ┃ w ┃ ┃\n┃ 8 ┃ eqwe ┃ ┃\n┣━━━━━━╋━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━┻━━━━━━┻━━━━━┛"
);
assert_eq!(
draw_table(table_with_data(29), 29, &cfg).unwrap(),
"┏━━━━━━━━━━┳━━━━━━━━━━┳━━━━━┓\n┃ 123 ┃ qweqw ┃ ... ┃\n┃ 45678 ┃ eqwe ┃ ┃\n┣━━━━━━━━━━╋━━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━━━━━┻━━━━━━━━━━┻━━━━━┛"
);
assert_eq!(
draw_table(table_with_data(49), 49, &cfg).unwrap(),
"┏━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━┓\n┃ 123 ┃ qweqw ┃ xxx xx ┃ qqq qqq ┃ ... ┃\n┃ 45678 ┃ eqwe ┃ xx x xx ┃ qqqq ┃ ┃\n┃ ┃ ┃ x xx ┃ qqq qq ┃ ┃\n┃ ┃ ┃ xx ┃ ┃ ┃\n┣━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━╋━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ ... ┃\n┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ ... ┃\n┗━━━━━━━━━━┻━━━━━━━━━━┻━━━━━━━━━┻━━━━━━━━━┻━━━━━┛"
);
test_trim(&tests, TrimStrategy::wrap(true));
}
#[test]
fn truncate_test() {
let cfg = Config {
trim_strategy: TrimStrategy::Truncate { suffix: None },
..Default::default()
};
let tests = [
(0, None),
(1, None),
(2, None),
(3, None),
(4, None),
(5, None),
(6, None),
(7, None),
(8, None),
(9, None),
(10, None),
(11, None),
(12, Some("┏━━━━┳━━━━━┓\n┃ 12 ┃ ... ┃\n┣━━━━╋━━━━━┫\n┃ 0 ┃ ... ┃\n┃ 0 ┃ ... ┃\n┗━━━━┻━━━━━┛")),
(13, Some("┏━━━━━┳━━━━━┓\n┃ 123 ┃ ... ┃\n┣━━━━━╋━━━━━┫\n┃ 0 ┃ ... ┃\n┃ 0 ┃ ... ┃\n┗━━━━━┻━━━━━┛")),
(21, Some("┏━━━━━━┳━━━━━━┳━━━━━┓\n┃ 123 ┃ qweq ┃ ... ┃\n┣━━━━━━╋━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━┻━━━━━━┻━━━━━┛")),
(29, Some("┏━━━━━━━━━━┳━━━━━━━━━━┳━━━━━┓\n┃ 123 4567 ┃ qweqw eq ┃ ... ┃\n┣━━━━━━━━━━╋━━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━━━━━┻━━━━━━━━━━┻━━━━━┛")),
(49, Some("┏━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━┓\n┃ 123 45678 ┃ qweqw eqwe ┃ xxx xx xx x xx ┃ ... ┃\n┣━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n┗━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━┻━━━━━┛")),
];
for i in 0..10 {
assert!(draw_table(table_with_data(i), i, &cfg).is_none());
}
assert_eq!(
draw_table(table_with_data(10), 10, &cfg).unwrap(),
"┏━━━━┳━━━┓\n┃ 12 ┃ . ┃\n┣━━━━╋━━━┫\n┃ 0 ┃ . ┃\n┃ 0 ┃ . ┃\n┗━━━━┻━━━┛"
);
assert_eq!(
draw_table(table_with_data(21), 21, &cfg).unwrap(),
"┏━━━━━━┳━━━━━━┳━━━━━┓\n┃ 123 ┃ qweq ┃ ... ┃\n┣━━━━━━╋━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━┻━━━━━━┻━━━━━┛"
);
assert_eq!(
draw_table(table_with_data(29), 29, &cfg).unwrap(),
"┏━━━━━━━━━━┳━━━━━━━━━━┳━━━━━┓\n┃ 123 4567 ┃ qweqw eq ┃ ... ┃\n┣━━━━━━━━━━╋━━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━━━━━┻━━━━━━━━━━┻━━━━━┛"
);
assert_eq!(
draw_table(table_with_data(49), 49, &cfg).unwrap(),
"┏━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━┓\n┃ 123 4567 ┃ qweqw eq ┃ xxx xx ┃ qqq qqq ┃ ... ┃\n┣━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━╋━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ ... ┃\n┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ ... ┃\n┗━━━━━━━━━━┻━━━━━━━━━━┻━━━━━━━━━┻━━━━━━━━━┻━━━━━┛"
);
test_trim(&tests, TrimStrategy::truncate(None));
}
#[test]
fn truncate_with_suffix_test() {
let cfg = Config {
trim_strategy: TrimStrategy::Truncate {
suffix: Some(String::from("...")),
},
..Default::default()
};
let tests = [
(0, None),
(1, None),
(2, None),
(3, None),
(4, None),
(5, None),
(6, None),
(7, None),
(8, None),
(9, None),
(10, None),
(11, None),
(12, Some("┏━━━━┳━━━━━┓\n┃ .. ┃ ... ┃\n┣━━━━╋━━━━━┫\n┃ 0 ┃ ... ┃\n┃ 0 ┃ ... ┃\n┗━━━━┻━━━━━┛")),
(13, Some("┏━━━━━┳━━━━━┓\n┃ ... ┃ ... ┃\n┣━━━━━╋━━━━━┫\n┃ 0 ┃ ... ┃\n┃ 0 ┃ ... ┃\n┗━━━━━┻━━━━━┛")),
(21, Some("┏━━━━━━┳━━━━━━┳━━━━━┓\n┃ 1... ┃ q... ┃ ... ┃\n┣━━━━━━╋━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━┻━━━━━━┻━━━━━┛")),
(29, Some("┏━━━━━━━━━━┳━━━━━━━━━━┳━━━━━┓\n┃ 123 4... ┃ qweqw... ┃ ... ┃\n┣━━━━━━━━━━╋━━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━━━━━┻━━━━━━━━━━┻━━━━━┛")),
(49, Some("┏━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━┳━━━━━┓\n┃ 123 45678 ┃ qweqw eqwe ┃ xxx xx xx x... ┃ ... ┃\n┣━━━━━━━━━━━╋━━━━━━━━━━━━╋━━━━━━━━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n┃ 0 ┃ 1 ┃ 2 ┃ ... ┃\n┗━━━━━━━━━━━┻━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━┻━━━━━┛")),
];
for i in 0..10 {
assert!(draw_table(table_with_data(i), i, &cfg).is_none());
}
assert_eq!(
draw_table(table_with_data(10), 10, &cfg).unwrap(),
"┏━━━━┳━━━┓\n┃ .. ┃ . ┃\n┣━━━━╋━━━┫\n┃ 0 ┃ . ┃\n┃ 0 ┃ . ┃\n┗━━━━┻━━━┛"
);
assert_eq!(
draw_table(table_with_data(21), 21, &cfg).unwrap(),
"┏━━━━━━┳━━━━━━┳━━━━━┓\n┃ 1... ┃ q... ┃ ... ┃\n┣━━━━━━╋━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━┻━━━━━━┻━━━━━┛"
);
assert_eq!(
draw_table(table_with_data(29), 29, &cfg).unwrap(),
"┏━━━━━━━━━━┳━━━━━━━━━━┳━━━━━┓\n┃ 123 4... ┃ qweqw... ┃ ... ┃\n┣━━━━━━━━━━╋━━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ ... ┃\n┃ 0 ┃ 1 ┃ ... ┃\n┗━━━━━━━━━━┻━━━━━━━━━━┻━━━━━┛"
);
assert_eq!(
draw_table(table_with_data(49), 49, &cfg).unwrap(),
"┏━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━┓\n┃ 123 4... ┃ qweqw... ┃ xxx ... ┃ qqq ... ┃ ... ┃\n┣━━━━━━━━━━╋━━━━━━━━━━╋━━━━━━━━━╋━━━━━━━━━╋━━━━━┫\n┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ ... ┃\n┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃ ... ┃\n┗━━━━━━━━━━┻━━━━━━━━━━┻━━━━━━━━━┻━━━━━━━━━┻━━━━━┛"
);
test_trim(&tests, TrimStrategy::truncate(Some(String::from("..."))));
}
fn draw_table(table: Table, limit: usize, cfg: &Config) -> Option<String> {
let styles = HashMap::default();
let alignments = Alignments::default();
table.draw_table(cfg, &styles, alignments, &theme::heavy(), limit, false)
fn test_trim(tests: &[(usize, Option<&str>)], trim: TrimStrategy) {
let config = TableConfig::new(nu_table::TableTheme::heavy(), true, false, false).trim(trim);
let tests = tests.iter().map(|&(termwidth, expected)| {
TestCase::new(config.clone(), termwidth, expected.map(|s| s.to_string()))
});
let data = create_test_table0();
test_table(data, tests);
}
fn row(count_columns: usize) -> Vec<TCell<CellInfo<'static>, TextStyle>> {
let mut row = Vec::with_capacity(count_columns);
for i in 0..count_columns {
row.push(Table::create_cell(i.to_string(), TextStyle::default()));
}
row
}
fn styled_str(s: &str) -> TCell<CellInfo<'static>, TextStyle> {
Table::create_cell(s.to_string(), TextStyle::default())
}
fn table_with_data(termwidth: usize) -> Table {
fn create_test_table0() -> VecCells {
let header = vec![
styled_str("123 45678"),
styled_str("qweqw eqwe"),
@ -213,7 +201,6 @@ fn table_with_data(termwidth: usize) -> Table {
styled_str("qqq qqq qqqq qqq qq"),
styled_str("qw"),
];
let data = vec![header, row(5), row(5)];
Table::new(data, (3, 5), termwidth, true, false)
vec![header, create_row(5), create_row(5)]
}

View File

@ -1,13 +1,18 @@
use std::collections::HashMap;
mod common;
use nu_protocol::Config;
use nu_table::{Alignments, Table, TableTheme as theme, TextStyle};
use tabled::papergrid::records::{cell_info::CellInfo, tcell::TCell};
use common::{create_row, create_table};
use nu_table::{TableConfig, TableTheme as theme};
#[test]
fn test_expand() {
let table = create_table(
vec![create_row(4); 3],
TableConfig::new(theme::rounded(), true, false, false).expand(),
50,
);
assert_eq!(
draw_table(vec![row(4); 3], 4, true, theme::rounded(), 50),
table.unwrap(),
"╭────────────┬───────────┬───────────┬───────────╮\n\
│ 0 │ 1 │ 2 │ 3 │\n\
├────────────┼───────────┼───────────┼───────────┤\n\
@ -16,31 +21,3 @@ fn test_expand() {
╰────────────┴───────────┴───────────┴───────────╯"
);
}
fn draw_table(
data: Vec<Vec<TCell<CellInfo<'static>, TextStyle>>>,
count_columns: usize,
with_header: bool,
theme: theme,
width: usize,
) -> String {
let size = (data.len(), count_columns);
let table = Table::new(data, size, width, with_header, false);
let cfg = Config::default();
let styles = HashMap::default();
let alignments = Alignments::default();
table
.draw_table(&cfg, &styles, alignments, &theme, width, true)
.expect("Unexpectdly got no table")
}
fn row(count_columns: usize) -> Vec<TCell<CellInfo<'static>, TextStyle>> {
let mut row = Vec::with_capacity(count_columns);
for i in 0..count_columns {
row.push(Table::create_cell(i.to_string(), TextStyle::default()));
}
row
}

View File

@ -1,13 +1,13 @@
use std::collections::HashMap;
mod common;
use nu_protocol::Config;
use nu_table::{Alignments, Table, TableTheme as theme, TextStyle};
use tabled::papergrid::records::{cell_info::CellInfo, tcell::TCell};
use nu_table::{TableConfig, TableTheme as theme};
use common::{create_row as row, VecCells};
#[test]
fn test_rounded() {
assert_eq!(
draw_table(vec![row(4); 3], 4, true, theme::rounded()),
create_table(vec![row(4); 3], true, theme::rounded()),
"╭───┬───┬───┬───╮\n\
│ 0 │ 1 │ 2 │ 3 │\n\
├───┼───┼───┼───┤\n\
@ -17,7 +17,7 @@ fn test_rounded() {
);
assert_eq!(
draw_table(vec![row(4); 2], 4, true, theme::rounded()),
create_table(vec![row(4); 2], true, theme::rounded()),
"╭───┬───┬───┬───╮\n\
│ 0 │ 1 │ 2 │ 3 │\n\
├───┼───┼───┼───┤\n\
@ -26,34 +26,37 @@ fn test_rounded() {
);
assert_eq!(
draw_table(vec![row(4); 1], 4, true, theme::rounded()),
create_table(vec![row(4); 1], true, theme::rounded()),
"╭───┬───┬───┬───╮\n\
│ 0 │ 1 │ 2 │ 3 │\n\
╰───┴───┴───┴───╯"
);
assert_eq!(
draw_table(vec![row(4); 1], 4, false, theme::rounded()),
create_table(vec![row(4); 1], false, theme::rounded()),
"╭───┬───┬───┬───╮\n\
│ 0 │ 1 │ 2 │ 3 │\n\
╰───┴───┴───┴───╯"
);
assert_eq!(
draw_table(vec![row(4); 2], 4, false, theme::rounded()),
create_table(vec![row(4); 2], false, theme::rounded()),
"╭───┬───┬───┬───╮\n\
│ 0 │ 1 │ 2 │ 3 │\n\
│ 0 │ 1 │ 2 │ 3 │\n\
╰───┴───┴───┴───╯"
);
assert_eq!(draw_table(vec![row(4); 0], 4, false, theme::rounded()), "");
assert_eq!(
create_table_with_size(vec![row(4); 0], (0, 4), true, theme::rounded()),
""
);
}
#[test]
fn test_basic() {
assert_eq!(
draw_table(vec![row(4); 3], 4, true, theme::basic()),
create_table(vec![row(4); 3], true, theme::basic()),
"+---+---+---+---+\n\
| 0 | 1 | 2 | 3 |\n\
+---+---+---+---+\n\
@ -64,7 +67,7 @@ fn test_basic() {
);
assert_eq!(
draw_table(vec![row(4); 2], 4, true, theme::basic()),
create_table(vec![row(4); 2], true, theme::basic()),
"+---+---+---+---+\n\
| 0 | 1 | 2 | 3 |\n\
+---+---+---+---+\n\
@ -73,21 +76,21 @@ fn test_basic() {
);
assert_eq!(
draw_table(vec![row(4); 1], 4, true, theme::basic()),
create_table(vec![row(4); 1], true, theme::basic()),
"+---+---+---+---+\n\
| 0 | 1 | 2 | 3 |\n\
+---+---+---+---+"
);
assert_eq!(
draw_table(vec![row(4); 1], 4, false, theme::basic()),
create_table(vec![row(4); 1], false, theme::basic()),
"+---+---+---+---+\n\
| 0 | 1 | 2 | 3 |\n\
+---+---+---+---+"
);
assert_eq!(
draw_table(vec![row(4); 2], 4, false, theme::basic()),
create_table(vec![row(4); 2], false, theme::basic()),
"+---+---+---+---+\n\
| 0 | 1 | 2 | 3 |\n\
+---+---+---+---+\n\
@ -95,13 +98,16 @@ fn test_basic() {
+---+---+---+---+"
);
assert_eq!(draw_table(vec![row(4); 0], 4, false, theme::basic()), "");
assert_eq!(
create_table_with_size(vec![row(4); 0], (0, 4), true, theme::basic()),
""
);
}
#[test]
fn test_reinforced() {
assert_eq!(
draw_table(vec![row(4); 3], 4, true, theme::reinforced()),
create_table(vec![row(4); 3], true, theme::reinforced()),
"┏───┬───┬───┬───┓\n\
│ 0 │ 1 │ 2 │ 3 │\n\
│ 0 │ 1 │ 2 │ 3 │\n\
@ -110,7 +116,7 @@ fn test_reinforced() {
);
assert_eq!(
draw_table(vec![row(4); 2], 4, true, theme::reinforced()),
create_table(vec![row(4); 2], true, theme::reinforced()),
"┏───┬───┬───┬───┓\n\
│ 0 │ 1 │ 2 │ 3 │\n\
│ 0 │ 1 │ 2 │ 3 │\n\
@ -118,21 +124,21 @@ fn test_reinforced() {
);
assert_eq!(
draw_table(vec![row(4); 1], 4, true, theme::reinforced()),
create_table(vec![row(4); 1], true, theme::reinforced()),
"┏───┬───┬───┬───┓\n\
│ 0 │ 1 │ 2 │ 3 │\n\
┗───┴───┴───┴───┛"
);
assert_eq!(
draw_table(vec![row(4); 1], 4, false, theme::reinforced()),
create_table(vec![row(4); 1], false, theme::reinforced()),
"┏───┬───┬───┬───┓\n\
│ 0 │ 1 │ 2 │ 3 │\n\
┗───┴───┴───┴───┛"
);
assert_eq!(
draw_table(vec![row(4); 2], 4, false, theme::reinforced()),
create_table(vec![row(4); 2], false, theme::reinforced()),
"┏───┬───┬───┬───┓\n\
│ 0 │ 1 │ 2 │ 3 │\n\
│ 0 │ 1 │ 2 │ 3 │\n\
@ -140,7 +146,7 @@ fn test_reinforced() {
);
assert_eq!(
draw_table(vec![row(4); 0], 2, false, theme::reinforced()),
create_table_with_size(vec![row(4); 0], (0, 4), true, theme::reinforced()),
""
);
}
@ -148,7 +154,7 @@ fn test_reinforced() {
#[test]
fn test_compact() {
assert_eq!(
draw_table(vec![row(4); 3], 4, true, theme::compact()),
create_table(vec![row(4); 3], true, theme::compact()),
concat!(
"───┬───┬───┬───\n",
" 0 │ 1 │ 2 │ 3 \n",
@ -160,7 +166,7 @@ fn test_compact() {
);
assert_eq!(
draw_table(vec![row(4); 2], 4, true, theme::compact()),
create_table(vec![row(4); 2], true, theme::compact()),
concat!(
"───┬───┬───┬───\n",
" 0 │ 1 │ 2 │ 3 \n",
@ -171,17 +177,17 @@ fn test_compact() {
);
assert_eq!(
draw_table(vec![row(4); 1], 4, true, theme::compact()),
create_table(vec![row(4); 1], true, theme::compact()),
concat!("───┬───┬───┬───\n", " 0 │ 1 │ 2 │ 3 \n", "───┴───┴───┴───",)
);
assert_eq!(
draw_table(vec![row(4); 1], 4, false, theme::compact()),
create_table(vec![row(4); 1], false, theme::compact()),
concat!("───┬───┬───┬───\n", " 0 │ 1 │ 2 │ 3 \n", "───┴───┴───┴───",)
);
assert_eq!(
draw_table(vec![row(4); 2], 4, false, theme::compact()),
create_table(vec![row(4); 2], false, theme::compact()),
concat!(
"───┬───┬───┬───\n",
" 0 │ 1 │ 2 │ 3 \n",
@ -190,13 +196,16 @@ fn test_compact() {
)
);
assert_eq!(draw_table(vec![row(4); 0], 4, false, theme::compact()), "");
assert_eq!(
create_table_with_size(vec![row(4); 0], (0, 4), true, theme::compact()),
""
);
}
#[test]
fn test_compact_double() {
assert_eq!(
draw_table(vec![row(4); 3], 4, true, theme::compact_double()),
create_table(vec![row(4); 3], true, theme::compact_double()),
concat!(
"═══╦═══╦═══╦═══\n",
" 0 ║ 1 ║ 2 ║ 3 \n",
@ -208,7 +217,7 @@ fn test_compact_double() {
);
assert_eq!(
draw_table(vec![row(4); 2], 4, true, theme::compact_double()),
create_table(vec![row(4); 2], true, theme::compact_double()),
concat!(
"═══╦═══╦═══╦═══\n",
" 0 ║ 1 ║ 2 ║ 3 \n",
@ -219,17 +228,17 @@ fn test_compact_double() {
);
assert_eq!(
draw_table(vec![row(4); 1], 4, true, theme::compact_double()),
create_table(vec![row(4); 1], true, theme::compact_double()),
concat!("═══╦═══╦═══╦═══\n", " 0 ║ 1 ║ 2 ║ 3 \n", "═══╩═══╩═══╩═══",)
);
assert_eq!(
draw_table(vec![row(4); 1], 4, false, theme::compact_double()),
create_table(vec![row(4); 1], false, theme::compact_double()),
concat!("═══╦═══╦═══╦═══\n", " 0 ║ 1 ║ 2 ║ 3 \n", "═══╩═══╩═══╩═══",)
);
assert_eq!(
draw_table(vec![row(4); 2], 4, false, theme::compact_double()),
create_table(vec![row(4); 2], false, theme::compact_double()),
concat!(
"═══╦═══╦═══╦═══\n",
" 0 ║ 1 ║ 2 ║ 3 \n",
@ -239,7 +248,7 @@ fn test_compact_double() {
);
assert_eq!(
draw_table(vec![row(4); 0], 4, false, theme::compact_double()),
create_table_with_size(vec![row(4); 0], (0, 4), true, theme::compact_double()),
""
);
}
@ -247,7 +256,7 @@ fn test_compact_double() {
#[test]
fn test_heavy() {
assert_eq!(
draw_table(vec![row(4); 3], 4, true, theme::heavy()),
create_table(vec![row(4); 3], true, theme::heavy()),
"┏━━━┳━━━┳━━━┳━━━┓\n\
┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\
┣━━━╋━━━╋━━━╋━━━┫\n\
@ -257,7 +266,7 @@ fn test_heavy() {
);
assert_eq!(
draw_table(vec![row(4); 2], 4, true, theme::heavy()),
create_table(vec![row(4); 2], true, theme::heavy()),
"┏━━━┳━━━┳━━━┳━━━┓\n\
┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\
┣━━━╋━━━╋━━━╋━━━┫\n\
@ -266,34 +275,37 @@ fn test_heavy() {
);
assert_eq!(
draw_table(vec![row(4); 1], 4, true, theme::heavy()),
create_table(vec![row(4); 1], true, theme::heavy()),
"┏━━━┳━━━┳━━━┳━━━┓\n\
┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\
┗━━━┻━━━┻━━━┻━━━┛"
);
assert_eq!(
draw_table(vec![row(4); 1], 4, false, theme::heavy()),
create_table(vec![row(4); 1], false, theme::heavy()),
"┏━━━┳━━━┳━━━┳━━━┓\n\
┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\
┗━━━┻━━━┻━━━┻━━━┛"
);
assert_eq!(
draw_table(vec![row(4); 2], 4, false, theme::heavy()),
create_table(vec![row(4); 2], false, theme::heavy()),
"┏━━━┳━━━┳━━━┳━━━┓\n\
┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\
┃ 0 ┃ 1 ┃ 2 ┃ 3 ┃\n\
┗━━━┻━━━┻━━━┻━━━┛"
);
assert_eq!(draw_table(vec![row(4); 0], 4, false, theme::heavy()), "");
assert_eq!(
create_table_with_size(vec![row(4); 0], (0, 4), true, theme::heavy()),
""
);
}
#[test]
fn test_light() {
assert_eq!(
draw_table(vec![row(4); 3], 4, true, theme::light()),
create_table(vec![row(4); 3], true, theme::light()),
concat!(
" 0 1 2 3 \n",
"───────────────\n",
@ -303,62 +315,68 @@ fn test_light() {
);
assert_eq!(
draw_table(vec![row(4); 2], 4, true, theme::light()),
create_table(vec![row(4); 2], true, theme::light()),
concat!(" 0 1 2 3 \n", "───────────────\n", " 0 1 2 3 ")
);
assert_eq!(
draw_table(vec![row(4); 1], 4, true, theme::light()),
create_table(vec![row(4); 1], true, theme::light()),
concat!(" 0 1 2 3 ")
);
assert_eq!(
draw_table(vec![row(4); 1], 4, false, theme::light()),
create_table(vec![row(4); 1], false, theme::light()),
concat!(" 0 1 2 3 ")
);
assert_eq!(
draw_table(vec![row(4); 2], 4, false, theme::light()),
create_table(vec![row(4); 2], false, theme::light()),
concat!(" 0 1 2 3 \n", " 0 1 2 3 ")
);
assert_eq!(draw_table(vec![row(4); 0], 4, true, theme::light()), "");
assert_eq!(
create_table_with_size(vec![row(4); 0], (0, 4), true, theme::light()),
""
);
}
#[test]
fn test_none() {
assert_eq!(
draw_table(vec![row(4); 3], 4, true, theme::none()),
create_table(vec![row(4); 3], true, theme::none()),
concat!(" 0 1 2 3 \n", " 0 1 2 3 \n", " 0 1 2 3 ")
);
assert_eq!(
draw_table(vec![row(4); 2], 4, true, theme::none()),
create_table(vec![row(4); 2], true, theme::none()),
concat!(" 0 1 2 3 \n", " 0 1 2 3 ")
);
assert_eq!(
draw_table(vec![row(4); 1], 4, true, theme::none()),
create_table(vec![row(4); 1], true, theme::none()),
concat!(" 0 1 2 3 ")
);
assert_eq!(
draw_table(vec![row(4); 1], 4, false, theme::none()),
create_table(vec![row(4); 1], false, theme::none()),
concat!(" 0 1 2 3 ")
);
assert_eq!(
draw_table(vec![row(4); 2], 4, true, theme::none()),
create_table(vec![row(4); 2], true, theme::none()),
concat!(" 0 1 2 3 \n", " 0 1 2 3 ")
);
assert_eq!(draw_table(vec![row(4); 0], 4, true, theme::none()), "");
assert_eq!(
create_table_with_size(vec![row(4); 0], (0, 4), true, theme::none()),
""
);
}
#[test]
fn test_thin() {
assert_eq!(
draw_table(vec![row(4); 3], 4, true, theme::thin()),
create_table(vec![row(4); 3], true, theme::thin()),
"┌───┬───┬───┬───┐\n\
│ 0 │ 1 │ 2 │ 3 │\n\
├───┼───┼───┼───┤\n\
@ -369,7 +387,7 @@ fn test_thin() {
);
assert_eq!(
draw_table(vec![row(4); 2], 4, true, theme::thin()),
create_table(vec![row(4); 2], true, theme::thin()),
"┌───┬───┬───┬───┐\n\
│ 0 │ 1 │ 2 │ 3 │\n\
├───┼───┼───┼───┤\n\
@ -378,21 +396,21 @@ fn test_thin() {
);
assert_eq!(
draw_table(vec![row(4); 1], 4, true, theme::thin()),
create_table(vec![row(4); 1], true, theme::thin()),
"┌───┬───┬───┬───┐\n\
│ 0 │ 1 │ 2 │ 3 │\n\
└───┴───┴───┴───┘"
);
assert_eq!(
draw_table(vec![row(4); 1], 4, false, theme::thin()),
create_table(vec![row(4); 1], false, theme::thin()),
"┌───┬───┬───┬───┐\n\
│ 0 │ 1 │ 2 │ 3 │\n\
└───┴───┴───┴───┘"
);
assert_eq!(
draw_table(vec![row(4); 2], 4, false, theme::thin()),
create_table(vec![row(4); 2], false, theme::thin()),
"┌───┬───┬───┬───┐\n\
│ 0 │ 1 │ 2 │ 3 │\n\
├───┼───┼───┼───┤\n\
@ -400,13 +418,16 @@ fn test_thin() {
└───┴───┴───┴───┘"
);
assert_eq!(draw_table(vec![row(4); 0], 4, true, theme::thin()), "");
assert_eq!(
create_table_with_size(vec![row(4); 0], (0, 4), true, theme::thin()),
""
);
}
#[test]
fn test_with_love() {
assert_eq!(
draw_table(vec![row(4); 3], 4, true, theme::with_love()),
create_table(vec![row(4); 3], true, theme::with_love()),
concat!(
"❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤\n",
" 0 ❤ 1 ❤ 2 ❤ 3 \n",
@ -418,7 +439,7 @@ fn test_with_love() {
);
assert_eq!(
draw_table(vec![row(4); 2], 4, true, theme::with_love()),
create_table(vec![row(4); 2], true, theme::with_love()),
concat!(
"❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤\n",
" 0 ❤ 1 ❤ 2 ❤ 3 \n",
@ -429,17 +450,17 @@ fn test_with_love() {
);
assert_eq!(
draw_table(vec![row(4); 1], 4, true, theme::with_love()),
create_table(vec![row(4); 1], true, theme::with_love()),
concat!("❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤\n", " 0 ❤ 1 ❤ 2 ❤ 3 \n", "❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤",)
);
assert_eq!(
draw_table(vec![row(4); 1], 4, false, theme::with_love()),
create_table(vec![row(4); 1], false, theme::with_love()),
concat!("❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤\n", " 0 ❤ 1 ❤ 2 ❤ 3 \n", "❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤",)
);
assert_eq!(
draw_table(vec![row(4); 2], 4, false, theme::with_love()),
create_table(vec![row(4); 2], false, theme::with_love()),
concat!(
"❤❤❤❤❤❤❤❤❤❤❤❤❤❤❤\n",
" 0 ❤ 1 ❤ 2 ❤ 3 \n",
@ -448,32 +469,30 @@ fn test_with_love() {
)
);
assert_eq!(draw_table(vec![row(4); 0], 4, true, theme::with_love()), "");
assert_eq!(
create_table_with_size(vec![row(4); 0], (0, 4), true, theme::with_love()),
""
);
}
fn draw_table(
data: Vec<Vec<TCell<CellInfo<'static>, TextStyle>>>,
count_columns: usize,
fn create_table(data: VecCells, with_header: bool, theme: theme) -> String {
let config = TableConfig::new(theme, with_header, false, false);
let out = common::create_table(data, config, usize::MAX);
out.expect("not expected to get None")
}
fn create_table_with_size(
data: VecCells,
size: (usize, usize),
with_header: bool,
theme: theme,
) -> String {
let size = (data.len(), count_columns);
let table = Table::new(data, size, usize::MAX, with_header, false);
let config = TableConfig::new(theme, with_header, false, false);
let table = nu_table::Table::new(data, size);
let cfg = Config::default();
let styles = HashMap::default();
let alignments = Alignments::default();
table
.draw_table(&cfg, &styles, alignments, &theme, std::usize::MAX, false)
.expect("Unexpectdly got no table")
}
fn row(count_columns: usize) -> Vec<TCell<CellInfo<'static>, TextStyle>> {
let mut row = Vec::with_capacity(count_columns);
for i in 0..count_columns {
row.push(Table::create_cell(i.to_string(), TextStyle::default()));
}
row
.draw(config, usize::MAX)
.expect("not expected to get None")
}