From 027622c8c36bd6a13d543e86c7c2c6587b639cc9 Mon Sep 17 00:00:00 2001 From: Isla Waters Date: Wed, 5 Mar 2025 09:30:15 -0500 Subject: [PATCH] Fix removal of trailing tab / whitespace in tabular table Previously the final table output was trimmed with the intention of removing the last newline. This had an unintended side effect of removing the tab characters from empty columns in the specific case where the last row had one or more empty columns at the end of the row. This makes sure we are only removing the newline character as intended. Add a new unit test to verify this behavior as well. --- lib/cli/table/Tabular.php | 3 +-- tests/Test_Table.php | 22 ++++++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/lib/cli/table/Tabular.php b/lib/cli/table/Tabular.php index c7c2a1f..5132e55 100644 --- a/lib/cli/table/Tabular.php +++ b/lib/cli/table/Tabular.php @@ -45,7 +45,6 @@ public function row( array $row ) { foreach ( $rows as $r ) { $output .= implode( "\t", array_values( $r ) ) . PHP_EOL; } - - return trim( $output ); + return rtrim( $output, PHP_EOL ); } } diff --git a/tests/Test_Table.php b/tests/Test_Table.php index 538a4a4..964ec2e 100644 --- a/tests/Test_Table.php +++ b/tests/Test_Table.php @@ -245,4 +245,26 @@ public function test_ascii_pre_colorized_widths() { $this->assertSame( 56, strlen( $out[6] ) ); } + public function test_preserve_trailing_tabs() { + $table = new cli\Table(); + $renderer = new cli\Table\Tabular(); + $table->setRenderer( $renderer ); + + $table->setHeaders( array( 'Field', 'Type', 'Null', 'Key', 'Default', 'Extra' ) ); + + // Add row with missing values at the end + $table->addRow( array( 'date', 'date', 'NO', 'PRI', '', '' ) ); + $table->addRow( array( 'awesome_stuff', 'text', 'YES', '', '', '' ) ); + + $out = $table->getDisplayLines(); + + $expected = [ + "Field\tType\tNull\tKey\tDefault\tExtra", + "date\tdate\tNO\tPRI\t\t", + "awesome_stuff\ttext\tYES\t\t\t", + ]; + + $this->assertSame( $expected, $out, 'Trailing tabs should be preserved in table output.' ); + } + }