From c12fc25a6f0ae2104531c8022c34cf0c822c3cfa Mon Sep 17 00:00:00 2001 From: Bionus Date: Sun, 24 Nov 2024 16:20:45 +0100 Subject: [PATCH] feat: add setExtension util function for file paths --- src/lib/src/functions.cpp | 12 ++++++++++++ src/lib/src/functions.h | 1 + src/lib/tests/src/functions-test.cpp | 5 +++++ 3 files changed, 18 insertions(+) diff --git a/src/lib/src/functions.cpp b/src/lib/src/functions.cpp index 30acdeb26..9ab0414ab 100644 --- a/src/lib/src/functions.cpp +++ b/src/lib/src/functions.cpp @@ -618,6 +618,18 @@ QString getExtension(const QUrl &url) return ext; } +QString setExtension(QString path, const QString &extension) +{ + const int lastSlash = path.lastIndexOf('/'); + const int lastDot = path.mid(lastSlash + 1).lastIndexOf('.'); + if (lastDot != -1) { + const QString suffix = extension.isEmpty() ? "" : "." + extension; + return path.left(lastDot + lastSlash + 1) + suffix; + } + + return path; +} + QUrl setExtension(QUrl url, const QString &extension) { QString path = url.path(); diff --git a/src/lib/src/functions.h b/src/lib/src/functions.h index 88b2e4496..37ecd43aa 100644 --- a/src/lib/src/functions.h +++ b/src/lib/src/functions.h @@ -48,6 +48,7 @@ QString getUnit(double *size); QString formatFilesize(double size); qint64 parseFileSize(const QString &str); QString getExtension(const QUrl &url); +QString setExtension(QString path, const QString &extension); QUrl setExtension(QUrl url, const QString &extension); bool isUrl(const QString &str); bool isVariantEmpty(const QVariant &value); diff --git a/src/lib/tests/src/functions-test.cpp b/src/lib/tests/src/functions-test.cpp index ff953483a..0ced2c8f8 100644 --- a/src/lib/tests/src/functions-test.cpp +++ b/src/lib/tests/src/functions-test.cpp @@ -233,6 +233,11 @@ TEST_CASE("Functions") } SECTION("SetExtension") { + REQUIRE(setExtension(QString(""), "png") == QString("")); + REQUIRE(setExtension(QString("file"), "png") == QString("file")); + REQUIRE(setExtension(QString("file.jpg"), "png") == QString("file.png")); + REQUIRE(setExtension(QString("file.jpg"), "") == QString("file")); + REQUIRE(setExtension(QUrl(""), "png") == QUrl("")); REQUIRE(setExtension(QUrl("https://test.com/file"), "png") == QUrl("https://test.com/file")); REQUIRE(setExtension(QUrl("https://test.com/file.jpg"), "png") == QUrl("https://test.com/file.png"));