Skip to content

Commit

Permalink
feat: add setExtension util function for file paths
Browse files Browse the repository at this point in the history
  • Loading branch information
Bionus committed Nov 24, 2024
1 parent ffbd707 commit c12fc25
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/lib/src/functions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
1 change: 1 addition & 0 deletions src/lib/src/functions.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
5 changes: 5 additions & 0 deletions src/lib/tests/src/functions-test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"));
Expand Down

0 comments on commit c12fc25

Please sign in to comment.