1/*
2 This file is part of the KDE libraries
3
4 SPDX-FileCopyrightText: 2003, 2007 Oswald Buddenhagen <ossi@kde.org>
5
6 SPDX-License-Identifier: LGPL-2.0-or-later
7*/
8
9#include "kshell.h"
10#include "kshell_p.h"
11#include "kuser.h"
12
13#include <QDir>
14
15QString KShell::homeDir(const QString &user)
16{
17 if (user.isEmpty()) {
18 return QDir::homePath();
19 }
20 return KUser(user).homeDir();
21}
22
23QString KShell::joinArgs(const QStringList &args)
24{
25 QString ret;
26 for (const auto &arg : args) {
27 if (!ret.isEmpty()) {
28 ret.append(c: QLatin1Char(' '));
29 }
30 ret += quoteArg(arg);
31 }
32 return ret;
33}
34
35#ifdef Q_OS_WIN
36#define ESCAPE '^'
37#else
38#define ESCAPE '\\'
39#endif
40
41QString KShell::tildeExpand(const QString &fname)
42{
43 if (!fname.isEmpty() && fname[0] == QLatin1Char('~')) {
44 int pos = fname.indexOf(ch: QLatin1Char('/'));
45 if (pos < 0) {
46 const auto expandedValue = homeDir(user: fname.mid(position: 1));
47 if (expandedValue.isEmpty()) {
48 return fname;
49 }
50 return expandedValue;
51 }
52 QString ret = homeDir(user: fname.mid(position: 1, n: pos - 1));
53 if (!ret.isNull()) {
54 ret += QStringView(fname).mid(pos);
55 }
56 return ret;
57 } else if (fname.length() > 1 && fname[0] == QLatin1Char(ESCAPE) && fname[1] == QLatin1Char('~')) {
58 return fname.mid(position: 1);
59 }
60 return fname;
61}
62
63QString KShell::tildeCollapse(const QString &path)
64{
65 if (!path.isEmpty()) {
66 const auto homePath = QDir::homePath();
67 if (path.startsWith(s: homePath)) {
68 auto newPath = path;
69 newPath.replace(i: 0, len: homePath.length(), after: QLatin1Char('~'));
70 return newPath;
71 }
72 }
73 return path;
74}
75

source code of kcoreaddons/src/lib/util/kshell.cpp