diff --git a/autotests/kshelltest.cpp b/autotests/kshelltest.cpp --- a/autotests/kshelltest.cpp +++ b/autotests/kshelltest.cpp @@ -33,6 +33,7 @@ private Q_SLOTS: void tildeExpand(); + void tildeCollapse(); void quoteArg(); void joinArgs(); void splitJoin(); @@ -66,6 +67,14 @@ #endif } +void +KShellTest::tildeCollapse() +{ + QCOMPARE(KShell::tildeCollapse(QDir::homePath()), QStringLiteral("~")); + QCOMPARE(KShell::tildeCollapse(QDir::homePath() + QStringLiteral("/Documents")), QStringLiteral("~/Documents")); + QCOMPARE(KShell::tildeCollapse(QStringLiteral("/test/") + QDir::homePath()), QStringLiteral("/test/") + QDir::homePath()); +} + void KShellTest::quoteArg() { diff --git a/src/lib/util/kshell.h b/src/lib/util/kshell.h --- a/src/lib/util/kshell.h +++ b/src/lib/util/kshell.h @@ -192,6 +192,16 @@ * @return the expanded path */ KCOREADDONS_EXPORT QString tildeExpand(const QString &path); + +/** + * Performs tilde collapse on @p path. If path did not start by the user + * homedir returns path unchanged. + * + * @param path the path to tilde-collpase + * @return the collapsed path + * @since 5.66 + */ +KCOREADDONS_EXPORT QString tildeCollapse(const QString &path); } Q_DECLARE_OPERATORS_FOR_FLAGS(KShell::Options) diff --git a/src/lib/util/kshell.cpp b/src/lib/util/kshell.cpp --- a/src/lib/util/kshell.cpp +++ b/src/lib/util/kshell.cpp @@ -68,3 +68,16 @@ } return fname; } + +QString KShell::tildeCollapse(const QString &path) +{ + if (!path.isEmpty()) { + const auto homePath = QDir::homePath(); + if (path.startsWith(homePath)) { + auto newPath = path; + newPath.replace(0, homePath.length(), QLatin1Char('~')); + return newPath; + } + } + return path; +}