fileutils.cpp 18.4 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8 9 10 11 12 13 14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15 16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17 18 19 20 21 22
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23
**
hjk's avatar
hjk committed
24 25
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
26 27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
29 30 31 32

#include "fileutils.h"
#include "savefile.h"

33
#include "hostosinfo.h"
34 35
#include "qtcassert.h"

36
#include <QDir>
37
#include <QDebug>
38 39
#include <QDateTime>
#include <QMessageBox>
40

Orgad Shaneh's avatar
Orgad Shaneh committed
41 42
#ifdef Q_OS_WIN
#include <qt_windows.h>
43
#include <shlobj.h>
Orgad Shaneh's avatar
Orgad Shaneh committed
44 45
#endif

46 47
namespace Utils {

48 49
/*! \class Utils::FileUtils

50 51
  \brief The FileUtils class contains file and directory related convenience
  functions.
52 53 54 55 56 57 58 59

*/

/*!
  Removes the directory \a filePath and its subdirectories recursively.

  \note The \a error parameter is optional.

Leena Miettinen's avatar
Leena Miettinen committed
60
  Returns whether the operation succeeded.
61
*/
62
bool FileUtils::removeRecursively(const FileName &filePath, QString *error)
63
{
64
    QFileInfo fileInfo = filePath.toFileInfo();
65
    if (!fileInfo.exists() && !fileInfo.isSymLink())
66
        return true;
67
    QFile::setPermissions(filePath.toString(), fileInfo.permissions() | QFile::WriteUser);
68
    if (fileInfo.isDir()) {
69
        QDir dir(filePath.toString());
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
        dir = dir.canonicalPath();
        if (dir.isRoot()) {
            if (error) {
                *error = QCoreApplication::translate("Utils::FileUtils",
                    "Refusing to remove root directory.");
            }
            return false;
        }
        if (dir.path() == QDir::home().canonicalPath()) {
            if (error) {
                *error = QCoreApplication::translate("Utils::FileUtils",
                    "Refusing to remove your home directory.");
            }
            return false;
        }

86 87 88
        QStringList fileNames = dir.entryList(QDir::Files | QDir::Hidden
                                              | QDir::System | QDir::Dirs | QDir::NoDotAndDotDot);
        foreach (const QString &fileName, fileNames) {
89
            if (!removeRecursively(FileName(filePath).appendPath(fileName), error))
90 91
                return false;
        }
92
        if (!QDir::root().rmdir(dir.path())) {
93 94
            if (error) {
                *error = QCoreApplication::translate("Utils::FileUtils", "Failed to remove directory '%1'.")
95
                        .arg(filePath.toUserOutput());
96 97 98 99
            }
            return false;
        }
    } else {
100
        if (!QFile::remove(filePath.toString())) {
101 102
            if (error) {
                *error = QCoreApplication::translate("Utils::FileUtils", "Failed to remove file '%1'.")
103
                        .arg(filePath.toUserOutput());
104 105 106 107 108 109 110
            }
            return false;
        }
    }
    return true;
}

111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
/*!
  Copies the directory specified by \a srcFilePath recursively to \a tgtFilePath. \a tgtFilePath will contain
  the target directory, which will be created. Example usage:

  \code
    QString error;
    book ok = Utils::FileUtils::copyRecursively("/foo/bar", "/foo/baz", &error);
    if (!ok)
      qDebug() << error;
  \endcode

  This will copy the contents of /foo/bar into to the baz directory under /foo, which will be created in the process.

  \note The \a error parameter is optional.

Leena Miettinen's avatar
Leena Miettinen committed
126
  Returns whether the operation succeeded.
127
*/
128 129
bool FileUtils::copyRecursively(const FileName &srcFilePath, const FileName &tgtFilePath,
                                QString *error)
130
{
131
    QFileInfo srcFileInfo = srcFilePath.toFileInfo();
132
    if (srcFileInfo.isDir()) {
133
        QDir targetDir(tgtFilePath.toString());
134
        targetDir.cdUp();
135
        if (!targetDir.mkdir(tgtFilePath.toFileInfo().fileName())) {
136 137
            if (error) {
                *error = QCoreApplication::translate("Utils::FileUtils", "Failed to create directory '%1'.")
138
                        .arg(tgtFilePath.toUserOutput());
139
            }
140
            return false;
141
        }
142 143 144
        QDir sourceDir(srcFilePath.toString());
        QStringList fileNames = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot
                                                    | QDir::Hidden | QDir::System);
145
        foreach (const QString &fileName, fileNames) {
146 147 148 149
            FileName newSrcFilePath = srcFilePath;
            newSrcFilePath.appendPath(fileName);
            FileName newTgtFilePath = tgtFilePath;
            newTgtFilePath.appendPath(fileName);
150 151 152 153
            if (!copyRecursively(newSrcFilePath, newTgtFilePath, error))
                return false;
        }
    } else {
154
        if (!QFile::copy(srcFilePath.toString(), tgtFilePath.toString())) {
155 156
            if (error) {
                *error = QCoreApplication::translate("Utils::FileUtils", "Could not copy file '%1' to '%2'.")
157
                        .arg(srcFilePath.toUserOutput(), tgtFilePath.toUserOutput());
158 159 160 161 162 163 164
            }
            return false;
        }
    }
    return true;
}

165 166 167
/*!
  If \a filePath is a directory, the function will recursively check all files and return
  true if one of them is newer than \a timeStamp. If \a filePath is a single file, true will
Tobias Hunger's avatar
Tobias Hunger committed
168
  be returned if the file is newer than \a timeStamp.
169

Leena Miettinen's avatar
Leena Miettinen committed
170 171
  Returns whether at least one file in \a filePath has a newer date than
  \a timeStamp.
172
*/
173
bool FileUtils::isFileNewerThan(const FileName &filePath, const QDateTime &timeStamp)
174
{
175
    QFileInfo fileInfo = filePath.toFileInfo();
176 177 178
    if (!fileInfo.exists() || fileInfo.lastModified() >= timeStamp)
        return true;
    if (fileInfo.isDir()) {
179
        const QStringList dirContents = QDir(filePath.toString())
180 181
            .entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
        foreach (const QString &curFileName, dirContents) {
182
            if (isFileNewerThan(FileName(filePath).appendPath(curFileName), timeStamp))
183 184 185 186 187 188
                return true;
        }
    }
    return false;
}

189
/*!
Leena Miettinen's avatar
Leena Miettinen committed
190
  Recursively resolves possibly present symlinks in \a filePath.
191 192 193 194 195
  Unlike QFileInfo::canonicalFilePath(), this function will still return the expected target file
  even if the symlink is dangling.

  \note Maximum recursion depth == 16.

Leena Miettinen's avatar
Leena Miettinen committed
196
  Returns the symlink target file path.
197
*/
198
FileName FileUtils::resolveSymlinks(const FileName &path)
199
{
200
    QFileInfo f = path.toFileInfo();
201 202 203 204
    int links = 16;
    while (links-- && f.isSymLink())
        f.setFile(f.symLinkTarget());
    if (links <= 0)
205 206
        return FileName();
    return FileName::fromString(f.filePath());
207
}
208

209 210 211 212
/*!
  Like QDir::toNativeSeparators(), but use prefix '~' instead of $HOME on unix systems when an
  absolute path is given.

Leena Miettinen's avatar
Leena Miettinen committed
213
  Returns the possibly shortened path with native separators.
214 215 216 217 218 219 220 221 222 223 224 225 226
*/
QString FileUtils::shortNativePath(const FileName &path)
{
    if (HostOsInfo::isAnyUnixHost()) {
        const FileName home = FileName::fromString(QDir::cleanPath(QDir::homePath()));
        if (path.isChildOf(home)) {
            return QLatin1Char('~') + QDir::separator()
                + QDir::toNativeSeparators(path.relativeChildPath(home).toString());
        }
    }
    return path.toUserOutput();
}

227 228 229 230 231 232 233 234 235 236 237 238
QString FileUtils::fileSystemFriendlyName(const QString &name)
{
    QString result = name;
    result.replace(QRegExp(QLatin1String("\\W")), QLatin1String("_"));
    result.replace(QRegExp(QLatin1String("_+")), QLatin1String("_")); // compact _
    result.remove(QRegExp(QLatin1String("^_*"))); // remove leading _
    result.remove(QRegExp(QLatin1String("_+$"))); // remove trailing _
    if (result.isEmpty())
        result = QLatin1String("unknown");
    return result;
}

239 240 241 242 243 244
bool FileUtils::makeWritable(const FileName &path)
{
    const QString fileName = path.toString();
    return QFile::setPermissions(fileName, QFile::permissions(fileName) | QFile::WriteUser);
}

Orgad Shaneh's avatar
Orgad Shaneh committed
245 246 247 248 249
// makes sure that capitalization of directories is canonical on Windows.
// This mimics the logic in QDeclarative_isFileCaseCorrect
QString FileUtils::normalizePathName(const QString &name)
{
#ifdef Q_OS_WIN
250 251 252 253 254
    const QString nativeSeparatorName(QDir::toNativeSeparators(name));
    const LPCTSTR nameC = reinterpret_cast<LPCTSTR>(nativeSeparatorName.utf16()); // MinGW
    PIDLIST_ABSOLUTE file;
    HRESULT hr = SHParseDisplayName(nameC, NULL, &file, 0, NULL);
    if (FAILED(hr))
Orgad Shaneh's avatar
Orgad Shaneh committed
255
        return name;
256 257
    TCHAR buffer[MAX_PATH];
    if (!SHGetPathFromIDList(file, buffer))
Orgad Shaneh's avatar
Orgad Shaneh committed
258
        return name;
259
    return QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const ushort *>(buffer)));
Orgad Shaneh's avatar
Orgad Shaneh committed
260 261 262 263 264
#else // Filesystem is case-insensitive only on Windows
    return name;
#endif
}

265 266
QByteArray FileReader::fetchQrc(const QString &fileName)
{
267
    QTC_ASSERT(fileName.startsWith(QLatin1Char(':')), return QByteArray());
268 269
    QFile file(fileName);
    bool ok = file.open(QIODevice::ReadOnly);
270
    QTC_ASSERT(ok, qWarning() << fileName << "not there!"; return QByteArray());
271 272 273 274 275
    return file.readAll();
}

bool FileReader::fetch(const QString &fileName, QIODevice::OpenMode mode)
{
276
    QTC_ASSERT(!(mode & ~(QIODevice::ReadOnly | QIODevice::Text)), return false);
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

    QFile file(fileName);
    if (!file.open(QIODevice::ReadOnly | mode)) {
        m_errorString = tr("Cannot open %1 for reading: %2").arg(
                QDir::toNativeSeparators(fileName), file.errorString());
        return false;
    }
    m_data = file.readAll();
    if (file.error() != QFile::NoError) {
        m_errorString = tr("Cannot read %1: %2").arg(
                QDir::toNativeSeparators(fileName), file.errorString());
        return false;
    }
    return true;
}

bool FileReader::fetch(const QString &fileName, QIODevice::OpenMode mode, QString *errorString)
{
    if (fetch(fileName, mode))
        return true;
    if (errorString)
        *errorString = m_errorString;
    return false;
}

bool FileReader::fetch(const QString &fileName, QIODevice::OpenMode mode, QWidget *parent)
{
    if (fetch(fileName, mode))
        return true;
    if (parent)
        QMessageBox::critical(parent, tr("File Error"), m_errorString);
    return false;
}


FileSaverBase::FileSaverBase()
    : m_hasError(false)
{
}

FileSaverBase::~FileSaverBase()
{
    delete m_file;
}

bool FileSaverBase::finalize()
{
    m_file->close();
    setResult(m_file->error() == QFile::NoError);
    // We delete the object, so it is really closed even if it is a QTemporaryFile.
    delete m_file;
    m_file = 0;
    return !m_hasError;
}

bool FileSaverBase::finalize(QString *errStr)
{
    if (finalize())
        return true;
    if (errStr)
        *errStr = errorString();
    return false;
}

bool FileSaverBase::finalize(QWidget *parent)
{
    if (finalize())
        return true;
    QMessageBox::critical(parent, tr("File Error"), errorString());
    return false;
}

bool FileSaverBase::write(const char *data, int len)
{
    if (m_hasError)
        return false;
    return setResult(m_file->write(data, len) == len);
}

bool FileSaverBase::write(const QByteArray &bytes)
{
    if (m_hasError)
        return false;
    return setResult(m_file->write(bytes) == bytes.count());
}

bool FileSaverBase::setResult(bool ok)
{
    if (!ok && !m_hasError) {
        m_errorString = tr("Cannot write file %1. Disk full?").arg(
                QDir::toNativeSeparators(m_fileName));
        m_hasError = true;
    }
    return ok;
}

bool FileSaverBase::setResult(QTextStream *stream)
{
    stream->flush();
    return setResult(stream->status() == QTextStream::Ok);
}

bool FileSaverBase::setResult(QDataStream *stream)
{
381
    return setResult(stream->status() == QDataStream::Ok);
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
}

bool FileSaverBase::setResult(QXmlStreamWriter *stream)
{
    return setResult(!stream->hasError());
}


FileSaver::FileSaver(const QString &filename, QIODevice::OpenMode mode)
{
    m_fileName = filename;
    if (mode & (QIODevice::ReadOnly | QIODevice::Append)) {
        m_file = new QFile(filename);
        m_isSafe = false;
    } else {
        m_file = new SaveFile(filename);
        m_isSafe = true;
    }
    if (!m_file->open(QIODevice::WriteOnly | mode)) {
        QString err = QFile::exists(filename) ?
                tr("Cannot overwrite file %1: %2") : tr("Cannot create file %1: %2");
        m_errorString = err.arg(QDir::toNativeSeparators(filename), m_file->errorString());
        m_hasError = true;
    }
}

bool FileSaver::finalize()
{
    if (!m_isSafe)
        return FileSaverBase::finalize();

    SaveFile *sf = static_cast<SaveFile *>(m_file);
414 415 416 417
    if (m_hasError) {
        if (sf->isOpen())
            sf->rollback();
    } else {
418
        setResult(sf->commit());
419
    }
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449
    delete sf;
    m_file = 0;
    return !m_hasError;
}

TempFileSaver::TempFileSaver(const QString &templ)
    : m_autoRemove(true)
{
    QTemporaryFile *tempFile = new QTemporaryFile();
    if (!templ.isEmpty())
        tempFile->setFileTemplate(templ);
    tempFile->setAutoRemove(false);
    if (!tempFile->open()) {
        m_errorString = tr("Cannot create temporary file in %1: %2").arg(
                QDir::toNativeSeparators(QFileInfo(tempFile->fileTemplate()).absolutePath()),
                tempFile->errorString());
        m_hasError = true;
    }
    m_file = tempFile;
    m_fileName = tempFile->fileName();
}

TempFileSaver::~TempFileSaver()
{
    delete m_file;
    m_file = 0;
    if (m_autoRemove)
        QFile::remove(m_fileName);
}

450 451
/*! \class Utils::FileName

452
    \brief The FileName class is a light-weight convenience class for filenames.
453 454 455 456

    On windows filenames are compared case insensitively.
*/

Daniel Teske's avatar
Daniel Teske committed
457 458 459 460 461 462
FileName::FileName()
    : QString()
{

}

463
/// Constructs a FileName from \a info
Daniel Teske's avatar
Daniel Teske committed
464 465 466 467 468
FileName::FileName(const QFileInfo &info)
    : QString(info.absoluteFilePath())
{
}

469 470 471 472 473 474 475
/// \returns a QFileInfo
QFileInfo FileName::toFileInfo() const
{
    return QFileInfo(*this);
}

/// \returns a QString for passing on to QString based APIs
Daniel Teske's avatar
Daniel Teske committed
476 477 478 479 480
QString FileName::toString() const
{
    return QString(*this);
}

481 482 483 484 485 486 487
/// \returns a QString to display to the user
/// Converts the separators to the native format
QString FileName::toUserOutput() const
{
    return QDir::toNativeSeparators(toString());
}

488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509
/// Find the parent directory of a given directory.

/// Returns an empty FileName if the current dirctory is already
/// a root level directory.

/// \returns \a FileName with the last segment removed.
FileName FileName::parentDir() const
{
    const QString basePath = toString();
    if (basePath.isEmpty())
        return FileName();

    const QDir base(basePath);
    if (base.isRoot())
        return FileName();

    const QString path = basePath + QLatin1String("/..");
    const QString parent = QDir::cleanPath(path);

    return FileName::fromString(parent);
}

510 511
/// Constructs a FileName from \a fileName
/// \a fileName is not checked for validity.
Daniel Teske's avatar
Daniel Teske committed
512 513 514 515 516
FileName FileName::fromString(const QString &filename)
{
    return FileName(filename);
}

517 518 519 520
/// Constructs a FileName from \a fileName
/// \a fileName is only passed through QDir::cleanPath
FileName FileName::fromUserInput(const QString &filename)
{
521 522
    QString clean = QDir::cleanPath(filename);
    if (clean.startsWith(QLatin1String("~/")))
Eike Ziller's avatar
Eike Ziller committed
523
        clean = QDir::homePath() + clean.mid(1);
524
    return FileName(clean);
525 526
}

Daniel Teske's avatar
Daniel Teske committed
527 528 529 530 531
FileName::FileName(const QString &string)
    : QString(string)
{

}
532

Daniel Teske's avatar
Daniel Teske committed
533 534
bool FileName::operator==(const FileName &other) const
{
535
    return QString::compare(*this, other, HostOsInfo::fileNameCaseSensitivity()) == 0;
Daniel Teske's avatar
Daniel Teske committed
536 537
}

538 539 540 541 542
bool FileName::operator!=(const FileName &other) const
{
    return !(*this == other);
}

Daniel Teske's avatar
Daniel Teske committed
543 544
bool FileName::operator<(const FileName &other) const
{
545
    return QString::compare(*this, other, HostOsInfo::fileNameCaseSensitivity()) < 0;
Daniel Teske's avatar
Daniel Teske committed
546 547 548 549
}

bool FileName::operator<=(const FileName &other) const
{
550
    return QString::compare(*this, other, HostOsInfo::fileNameCaseSensitivity()) <= 0;
Daniel Teske's avatar
Daniel Teske committed
551 552 553 554 555 556 557 558 559 560 561 562
}

bool FileName::operator>(const FileName &other) const
{
    return other < *this;
}

bool FileName::operator>=(const FileName &other) const
{
    return other <= *this;
}

563 564
/// \returns whether FileName is a child of \a s
bool FileName::isChildOf(const FileName &s) const
Daniel Teske's avatar
Daniel Teske committed
565
{
566 567
    if (s.isEmpty())
        return false;
568
    if (!QString::startsWith(s, HostOsInfo::fileNameCaseSensitivity()))
569 570 571
        return false;
    if (size() <= s.size())
        return false;
572 573 574 575
    // s is root, '/' was already tested in startsWith
    if (s.QString::endsWith(QLatin1Char('/')))
        return true;
    // s is a directory, next character should be '/' (/tmpdir is NOT a child of /tmp)
576
    return at(s.size()) == QLatin1Char('/');
Daniel Teske's avatar
Daniel Teske committed
577 578
}

579 580 581 582 583 584
/// \overload
bool FileName::isChildOf(const QDir &dir) const
{
    return isChildOf(Utils::FileName::fromString(dir.absolutePath()));
}

585
/// \returns whether FileName endsWith \a s
Daniel Teske's avatar
Daniel Teske committed
586 587
bool FileName::endsWith(const QString &s) const
{
588
    return QString::endsWith(s, HostOsInfo::fileNameCaseSensitivity());
Daniel Teske's avatar
Daniel Teske committed
589 590
}

591 592 593 594
/// \returns the relativeChildPath of FileName to parent if FileName is a child of parent
/// \note returns a empty FileName if FileName is not a child of parent
/// That is, this never returns a path starting with "../"
FileName FileName::relativeChildPath(const FileName &parent) const
Daniel Teske's avatar
Daniel Teske committed
595
{
596 597 598
    if (!isChildOf(parent))
        return Utils::FileName();
    return FileName(QString::mid(parent.size() + 1, -1));
Daniel Teske's avatar
Daniel Teske committed
599 600
}

601
/// Appends \a s, ensuring a / between the parts
602
FileName &FileName::appendPath(const QString &s)
Daniel Teske's avatar
Daniel Teske committed
603
{
604
    if (!isEmpty() && !QString::endsWith(QLatin1Char('/')))
605 606
        appendString(QLatin1Char('/'));
    appendString(s);
607 608 609
    return *this;
}

610
FileName &FileName::appendString(const QString &str)
611 612 613 614 615
{
    QString::append(str);
    return *this;
}

616
FileName &FileName::appendString(QChar str)
617 618 619
{
    QString::append(str);
    return *this;
Daniel Teske's avatar
Daniel Teske committed
620 621
}

622
} // namespace Utils
Daniel Teske's avatar
Daniel Teske committed
623

624
QT_BEGIN_NAMESPACE
Daniel Teske's avatar
Daniel Teske committed
625 626
uint qHash(const Utils::FileName &a)
{
627 628
    if (Utils::HostOsInfo::isWindowsHost())
        return qHash(a.toString().toUpper());
Daniel Teske's avatar
Daniel Teske committed
629 630
    return qHash(a.toString());
}
631
QT_END_NAMESPACE