From b144d819797a50084a1e0403c59ff9d64d2442c3 Mon Sep 17 00:00:00 2001 From: Adriaan de Groot Date: Thu, 28 Jan 2021 01:02:46 +0100 Subject: [PATCH] [libcalamares] Fix up smart-string-truncation - off-by-one when source ends with a newline - lastNewLine was being calculated as a left-index into the string, then used as a count-from-right --- src/libcalamares/utils/String.cpp | 9 +++++---- src/libcalamares/utils/Tests.cpp | 6 ++++++ 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/libcalamares/utils/String.cpp b/src/libcalamares/utils/String.cpp index f032fa61b..c2a9f7bf7 100644 --- a/src/libcalamares/utils/String.cpp +++ b/src/libcalamares/utils/String.cpp @@ -15,6 +15,7 @@ */ #include "String.h" +#include "Logger.h" #include @@ -138,7 +139,7 @@ truncateMultiLine( const QString& string, CalamaresUtils::LinesStartEnd lines, C return string; } - QString shorter = string.simplified(); + QString shorter = string; QString front, back; if ( shorter.count( '\n' ) >= maxLines ) { @@ -154,17 +155,17 @@ truncateMultiLine( const QString& string, CalamaresUtils::LinesStartEnd lines, C } if ( from > 0 ) { - front = shorter.left( from ); + front = shorter.left( from + 1 ); } int lastNewLine = -1; - int lastCount = 0; + int lastCount = shorter.endsWith( '\n' ) ? -1 : 0; for ( auto i = shorter.rbegin(); i != shorter.rend() && lastCount < lines.atEnd; ++i ) { if ( *i == '\n' ) { ++lastCount; - lastNewLine = shorter.length() - int( i - shorter.rbegin() ); + lastNewLine = int( i - shorter.rbegin() ); } } if ( ( lastNewLine >= 0 ) && ( lastCount >= lines.atEnd ) ) diff --git a/src/libcalamares/utils/Tests.cpp b/src/libcalamares/utils/Tests.cpp index ffeec1078..84449bdb9 100644 --- a/src/libcalamares/utils/Tests.cpp +++ b/src/libcalamares/utils/Tests.cpp @@ -501,6 +501,8 @@ strings: [ aap, noot, mies ] void LibCalamaresTests::testStringTruncation() { + Logger::setupLogLevel( Logger::LOGDEBUG ); + using namespace CalamaresUtils; const QString longString( R"(--- @@ -546,14 +548,18 @@ LibCalamaresTests::testStringTruncation() // Lines at the start { auto s = truncateMultiLine( longString, LinesStartEnd { 4, 0 }, CharCount { sufficientLength } ); + QVERIFY( s.length() > 1 ); QVERIFY( longString.startsWith( s ) ); + cDebug() << "Result-line" << Logger::Quote << s; QCOMPARE( s.count( '\n' ), 4 ); } // Lines at the end { auto s = truncateMultiLine( longString, LinesStartEnd { 0, 4 }, CharCount { sufficientLength } ); + QVERIFY( s.length() > 1 ); QVERIFY( longString.endsWith( s ) ); + cDebug() << "Result-line" << Logger::Quote << s; QCOMPARE( s.count( '\n' ), 4 ); } }