File: path.h

package info (click to toggle)
kdevelop 4%3A22.12.2-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 70,096 kB
  • sloc: cpp: 284,635; javascript: 3,558; python: 3,422; sh: 1,319; ansic: 685; xml: 331; php: 95; lisp: 66; makefile: 39; sed: 12
file content (393 lines) | stat: -rw-r--r-- 11,361 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/*
    SPDX-FileCopyrightText: 2012 Milian Wolff <mail@milianw.de>

    SPDX-License-Identifier: LGPL-2.1-only OR LGPL-3.0-only OR LicenseRef-KDE-Accepted-LGPL
*/

#ifndef KDEVELOP_PATH_H
#define KDEVELOP_PATH_H

#include "utilexport.h"

#include <QMetaType>
#include <QString>
#include <QVector>
#include <QUrl>

#include <algorithm>

namespace KDevelop {

/**
 * @return Return a string representation of @p url, if possible as local file
 *
 * Convenience method for working around https://bugreports.qt.io/browse/QTBUG-41729
 */
QString KDEVPLATFORMUTIL_EXPORT toUrlOrLocalFile(const QUrl& url,
                                                 QUrl::FormattingOptions options = QUrl::FormattingOptions( QUrl::PrettyDecoded ));

/**
 * @brief Path data type optimized for memory consumption.
 *
 * This class holds data that represents a local or remote path.
 * In the project model e.g. we usually store whole trees such as
 *
 * /foo/
 * /foo/bar/
 * /foo/bar/asdf.txt
 *
 * Normal QString/QUrl/QUrl types would not share any memory for these paths
 * at all. This class though can share the segments of the paths and thus
 * consume far less total memory.
 *
 * Just like the URL types, the Path can point to a remote location.
 *
 * Example for how to leverage memory sharing for the above input data:
 *
 * @code
 * Path foo("/foo");
 * Path bar(foo, "bar");
 * Path asdf(foo, "asdf.txt");
 * @endcode
 *
 * @note Just as with QString e.g. you won't share any data implicitly when
 * you do something like this:
 *
 * @code
 * Path foo1("/foo");
 * Path foo2("/foo");
 * @endcode
 */
class KDEVPLATFORMUTIL_EXPORT Path
{
public:
    using List = QVector<Path>;

    /**
     * Construct an empty, invalid Path.
     */
    Path() = default;

    /**
     * Create a Path out of a string representation of a path or URL.
     *
     * @note Not every kind of remote URL is supported, rather only path-like
     * URLs without fragments, queries, sub-Paths and the like are supported.
     *
     * Empty paths or URLs containing one of the following are considered invalid:
     * - URL fragments (i.e. "...#fragment")
     * - URL queries (i.e. "...?query=")
     * - sub-URLs (i.e. "file:///tmp/kde.tgz#gzip:/#tar:/kdevelop")
     *
     * @sa isValid()
     */
    explicit Path(const QString& pathOrUrl);

    /**
     * Convert a QUrl to a Path.
     *
     * @note Not every kind of remote URL is supported, rather only path-like
     * URLs without fragments, queries, sub-Paths and the like are supported.
     *
     * Empty paths or URLs containing one of the following are considered invalid:
     * - URL fragments (i.e. "...#fragment")
     * - URL queries (i.e. "...?query=")
     * - sub-URLs (i.e. "file:///tmp/kde.tgz#gzip:/#tar:/kdevelop")
     *
     * @sa isValid()
     */
    explicit Path(const QUrl& url);

    /**
     * Create a copy of @p base and append a path segment @p subPath.
     *
     * This implicitly shares the data of @p base and thus is very efficient
     * memory wise compared to creating two Paths from separate strings.
     *
     * @p subPath A relative or absolute path. If this is an absolute path then
     * the path in @p base will be ignored and only the remote data copied. If
     * this is a relative path it will be combined with @p base.
     *
     * @sa addPath()
     */
    explicit Path(const Path& base, const QString& subPath);

    friend void swap(Path& a, Path& b) noexcept
    {
        a.m_data.swap(b.m_data);
    }

    /**
     * Equality comparison between @p other and this Path.
     *
     * @return true if @p other is equal to this Path.
     */
    inline bool operator==(const Path& other) const
    {
        if (other.m_data.data() == m_data.data())
            return true; // fast path when both containers point to the same shared data
        // The size check here is a bit faster than calling std::equal with 4 arguments.
        if (other.m_data.size() != m_data.size())
            return false;
        // Optimization: compare in reverse order as often the mismatch is at the end,
        // while the first few path segments are usually the same in different paths.
        return std::equal(m_data.rbegin(), m_data.rend(), other.m_data.rbegin());
    }

    /**
     * Inequality comparison between @p other and this Path.
     *
     * @return true if @p other is different from this Path.
     */
    inline bool operator!=(const Path& other) const
    {
        return !operator==(other);
    }

    /**
     * Compares *this with @p other and returns an integer less than, equal to,
     * or greater than zero if *this is less than, equal to, or greater than @p other.
     *
     * If @p cs is Qt::CaseSensitive, the comparison is case sensitive;
     * otherwise the comparison is case insensitive.
    */
    int compare(const Path& other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const;

    /**
     * Less-than path comparison between @p other and this Path.
     *
     * @return true if this Path is less than @p other.
     */
    bool operator<(const Path& other) const
    {
        return compare(other, Qt::CaseSensitive) < 0;
    }

    /**
     * Greater-than path comparison between @p other and this Path.
     *
     * @return true if this Path is greater than @p other.
     */
    inline bool operator>(const Path& other) const
    {
        return other < *this;
    }

    /**
     * Less-than-equal path comparison between @p other and this Path.
     *
     * @return true if this Path is less than @p other or equal.
     */
    inline bool operator<=(const Path& other) const
    {
        return !(other < *this);
    }

    /**
     * Greater-than-equal path comparison between @p other and this Path.
     *
     * @return true if this Path is greater than @p other or equal.
     */
    inline bool operator>=(const Path& other) const
    {
        return !(*this < other);
    }

    /**
     * Check whether this Path is valid.
     *
     * @return true if the Path is valid, i.e. contains data, false otherwise.
     */
    inline bool isValid() const
    {
        return !m_data.isEmpty();
    }

    /**
     * Check whether this Path is empty.
     *
     * @return true if the Path is empty, false otherwise, i.e. if it contains data.
     */
    inline bool isEmpty() const
    {
        return m_data.isEmpty();
    }

    /**
     * Convert the Path to a string, yielding either the plain path for local
     * paths or the stringified URL for remote Paths.
     *
     * @return a string representation of this Path.
     * @sa path()
     */
    QString pathOrUrl() const;

    /**
     * Return the path segment of this Path. This is the same for local paths
     * as calling pathOrUrl(). The difference is only for remote paths which
     * would return the protocol, host etc. data in pathOrUrl but not here.
     *
     * @return the path segment of this Path.
     *
     * @sa pathOrUrl()
     */
    QString path() const;

    /**
     * Return the path for local path and an empty string for remote paths.
     */
    QString toLocalFile() const;

    /**
     * @return the relative path from this path to @p path.
     *
     * Examples:
     * @code
     * Path p1("/foo/bar");
     * Path p2("/foo/bar/asdf/test.txt");
     * p1.relativePath(p2); // returns: asdf/test.txt
     * Path p3("/foo/asdf/lala");
     * p3.relativePath(p1); // returns: ../../bar
     * @endcode
     *
     * @sa QUrl::relativePath
     */
    QString relativePath(const Path& path) const;

    /**
     * @return True if this path is the parent of @p path.
     *
     * For instance, ftp://host/dir/ is a parent of ftp://host/dir/subdir/blub,
     * or /foo is a parent of /foo/bar.
     *
     * NOTE: Contrary to QUrl::isParentOf this returns false if the path equals this one.
     */
    bool isParentOf(const Path& path) const;

    /**
     * @return True if this path is the direct parent of @p path.
     *
     * For instance, ftp://host/dir/ is the direct parent of ftp://host/dir/subdir,
     * but ftp.//host/ is a parent but not the direct parent.
     *
     * This is more efficient than @code path.parent() == *this @endcode since
     * it does not require any temporary allocations as for the parent() call.
     */
    bool isDirectParentOf(const Path& path) const;

    /**
     * @return the prefix of a remote URL containing protocol, host, port etc. pp.
     *         If this path is not remote, this returns an empty string.
     */
    QString remotePrefix() const;

    /**
     * @return a const reference to the internal data.
     *
     * @note Returning a reference to rather than a copy of QVector can substantially
     * improve performance of a tight loop that calls this function.
     *
     * TODO: return std::span once we can rely on C++20.
     */
    inline const QVector<QString>& segments() const
    {
        return m_data;
    }

    /**
     * @return the Path converted to a QUrl.
     */
    QUrl toUrl() const;

    /**
     * @return true when this Path points to a local file, false otherwise.
     */
    bool isLocalFile() const;

    /**
     * @return true when this Path points to a remote file, false otherwise.
     */
    bool isRemote() const;

    /**
     * @return the last element of the path.
     *
     * This will never return the remote URL prefix.
     */
    QString lastPathSegment() const;

    /**
     * Set the file name of this Path, i.e. the last element of the path.
     *
     * This will never overwrite the remote URL prefix.
     */
    void setLastPathSegment(const QString& name);

    /**
     * Append @p path to this Path.
     *
     * NOTE: If @p path starts with a slash, this function ignores it.
     *       I.e. you cannot set the path this way. @sa QUrl::addPath
     */
    void addPath(const QString& path);

    /**
     * @return the path pointing to the parent folder of this path.
     *
     * @sa KIO::upUrl()
     */
    Path parent() const;

    /**
     * @return true when this path has a parent and false if this is a root or invalid path.
     */
    bool hasParent() const;

    /**
     * Change directory by relative path @p dir.
     *
     * NOTE: This is expensive.
     *
     * @sa QUrl::cd
     */
    Path cd(const QString& dir) const;

private:
    // for remote urls the first element contains the a Path prefix
    // containing the protocol, user, port etc. pp.
    QVector<QString> m_data;
};

KDEVPLATFORMUTIL_EXPORT uint qHash(const Path& path);

/**
 * Convert the @p list of QUrls to a list of Paths.
 */
KDEVPLATFORMUTIL_EXPORT Path::List toPathList(const QList<QUrl>& list);

/**
 * Convert the @p list of QStrings to a list of Paths.
 */
KDEVPLATFORMUTIL_EXPORT Path::List toPathList(const QList<QString>& list);
}

/**
 * qDebug() stream operator.  Writes the string to the debug output.
 */
KDEVPLATFORMUTIL_EXPORT QDebug operator<<(QDebug s, const KDevelop::Path& string);

namespace QTest {

template<typename T> char* toString(const T&);
/**
 * QTestLib integration to have nice output in e.g. QCOMPARE failures.
 */
template<>
KDEVPLATFORMUTIL_EXPORT char* toString(const KDevelop::Path& path);
}

Q_DECLARE_TYPEINFO(KDevelop::Path, Q_MOVABLE_TYPE);
Q_DECLARE_METATYPE(KDevelop::Path)
Q_DECLARE_TYPEINFO(KDevelop::Path::List, Q_MOVABLE_TYPE);

#endif // KDEVELOP_PATH_H