File indexing completed on 2024-05-19 03:56:25

0001 /*
0002     This file is part of the KDE libraries
0003 
0004     SPDX-FileCopyrightText: 2003, 2007 Oswald Buddenhagen <ossi@kde.org>
0005 
0006     SPDX-License-Identifier: LGPL-2.0-or-later
0007 */
0008 
0009 #include "kshell.h"
0010 #include "kshell_p.h"
0011 #include "kuser.h"
0012 
0013 #include <QDir>
0014 
0015 QString KShell::homeDir(const QString &user)
0016 {
0017     if (user.isEmpty()) {
0018         return QDir::homePath();
0019     }
0020     return KUser(user).homeDir();
0021 }
0022 
0023 QString KShell::joinArgs(const QStringList &args)
0024 {
0025     QString ret;
0026     for (const auto &arg : args) {
0027         if (!ret.isEmpty()) {
0028             ret.append(QLatin1Char(' '));
0029         }
0030         ret += quoteArg(arg);
0031     }
0032     return ret;
0033 }
0034 
0035 #ifdef Q_OS_WIN
0036 #define ESCAPE '^'
0037 #else
0038 #define ESCAPE '\\'
0039 #endif
0040 
0041 QString KShell::tildeExpand(const QString &fname)
0042 {
0043     if (!fname.isEmpty() && fname[0] == QLatin1Char('~')) {
0044         int pos = fname.indexOf(QLatin1Char('/'));
0045         if (pos < 0) {
0046             return homeDir(fname.mid(1));
0047         }
0048         QString ret = homeDir(fname.mid(1, pos - 1));
0049         if (!ret.isNull()) {
0050             ret += QStringView(fname).mid(pos);
0051         }
0052         return ret;
0053     } else if (fname.length() > 1 && fname[0] == QLatin1Char(ESCAPE) && fname[1] == QLatin1Char('~')) {
0054         return fname.mid(1);
0055     }
0056     return fname;
0057 }
0058 
0059 QString KShell::tildeCollapse(const QString &path)
0060 {
0061     if (!path.isEmpty()) {
0062         const auto homePath = QDir::homePath();
0063         if (path.startsWith(homePath)) {
0064             auto newPath = path;
0065             newPath.replace(0, homePath.length(), QLatin1Char('~'));
0066             return newPath;
0067         }
0068     }
0069     return path;
0070 }