csync: apply strict QString handling
authorHannah von Reth <hannah.vonreth@owncloud.com>
Mon, 27 Jul 2020 08:44:51 +0000 (10:44 +0200)
committerKevin Ottens <kevin.ottens@nextcloud.com>
Tue, 15 Dec 2020 09:59:16 +0000 (10:59 +0100)
19 files changed:
src/common/filesystembase.cpp
src/common/filesystembase.h
src/common/ownsql.cpp
src/common/ownsql.h
src/common/plugin.cpp
src/common/remotepermissions.cpp
src/common/remotepermissions.h
src/common/syncfilestatus.cpp
src/common/syncjournaldb.cpp
src/common/utility.cpp
src/common/utility_win.cpp
src/common/vfs.cpp
src/csync/CMakeLists.txt
src/csync/csync_exclude.cpp
src/csync/csync_exclude.h
src/csync/vio/csync_vio_local_unix.cpp
src/csync/vio/csync_vio_local_win.cpp
test/csync/encoding_tests/check_encoding.cpp
test/csync/vio_tests/check_vio_ext.cpp

index 594817135355bd89d3d0eb81730ca9ef55c92e39..f41b3a617b7b9d63c89cfef646a20f503dd18526 100644 (file)
@@ -261,7 +261,7 @@ bool FileSystem::openAndSeekFileSharedRead(QFile *file, QString *errorOrNull, qi
     // the fd the handle will be closed too.
     int fd = _open_osfhandle((intptr_t)fileHandle, _O_RDONLY);
     if (fd == -1) {
-        error = "could not make fd from handle";
+        error = QStringLiteral("could not make fd from handle");
         CloseHandle(fileHandle);
         return false;
     }
@@ -333,9 +333,9 @@ QString FileSystem::fileSystemForPath(const QString &path)
 {
     // See also QStorageInfo (Qt >=5.4) and GetVolumeInformationByHandleW (>= Vista)
     QString drive = path.left(2);
-    if (!drive.endsWith(":"))
+    if (!drive.endsWith(QLatin1Char(':')))
         return QString();
-    drive.append('\\');
+    drive.append(QLatin1Char('\\'));
 
     const size_t fileSystemBufferSize = 4096;
     TCHAR fileSystemBuffer[fileSystemBufferSize];
@@ -376,13 +376,13 @@ bool FileSystem::moveToTrash(const QString &fileName, QString *errorString)
     QString trashPath, trashFilePath, trashInfoPath;
     QString xdgDataHome = QFile::decodeName(qgetenv("XDG_DATA_HOME"));
     if (xdgDataHome.isEmpty()) {
-        trashPath = QDir::homePath() + "/.local/share/Trash/"; // trash path that should exist
+        trashPath = QDir::homePath() + QStringLiteral("/.local/share/Trash/"); // trash path that should exist
     } else {
-        trashPath = xdgDataHome + "/Trash/";
+        trashPath = xdgDataHome + QStringLiteral("/Trash/");
     }
 
-    trashFilePath = trashPath + "files/"; // trash file path contain delete files
-    trashInfoPath = trashPath + "info/"; // trash info path contain delete files information
+    trashFilePath = trashPath + QStringLiteral("files/"); // trash file path contain delete files
+    trashInfoPath = trashPath + QStringLiteral("info/"); // trash info path contain delete files information
 
     if (!(QDir().mkpath(trashFilePath) && QDir().mkpath(trashInfoPath))) {
         *errorString = QCoreApplication::translate("FileSystem", "Could not make directories in trash");
@@ -394,7 +394,7 @@ bool FileSystem::moveToTrash(const QString &fileName, QString *errorString)
     QDir file;
     int suffix_number = 1;
     if (file.exists(trashFilePath + f.fileName())) { //file in trash already exists, move to "filename.1"
-        QString path = trashFilePath + f.fileName() + ".";
+        QString path = trashFilePath + f.fileName() + QLatin1Char('.');
         while (file.exists(path + QString::number(suffix_number))) { //or to "filename.2" if "filename.1" exists, etc
             suffix_number++;
         }
@@ -413,11 +413,11 @@ bool FileSystem::moveToTrash(const QString &fileName, QString *errorString)
 
     // create file format for trash info file----- START
     QFile infoFile;
-    if (file.exists(trashInfoPath + f.fileName() + ".trashinfo")) { //TrashInfo file already exists, create "filename.1.trashinfo"
-        QString filename = trashInfoPath + f.fileName() + "." + QString::number(suffix_number) + ".trashinfo";
+    if (file.exists(trashInfoPath + f.fileName() + QStringLiteral(".trashinfo"))) { //TrashInfo file already exists, create "filename.1.trashinfo"
+        QString filename = trashInfoPath + f.fileName() + QLatin1Char('.') + QString::number(suffix_number) + QStringLiteral(".trashinfo");
         infoFile.setFileName(filename); //filename+.trashinfo //  create file information file in /.local/share/Trash/info/ folder
     } else {
-        QString filename = trashInfoPath + f.fileName() + ".trashinfo";
+        QString filename = trashInfoPath + f.fileName() + QStringLiteral(".trashinfo");
         infoFile.setFileName(filename); //filename+.trashinfo //  create file information file in /.local/share/Trash/info/ folder
     }
 
@@ -425,16 +425,13 @@ bool FileSystem::moveToTrash(const QString &fileName, QString *errorString)
 
     QTextStream stream(&infoFile); // for write data on open file
 
-    QByteArray info = "[Trash Info]\n";
-    info += "Path=";
-    info += QUrl::toPercentEncoding(f.absoluteFilePath(), "~_-./");
-    info += '\n';
-    info += "DeletionDate=";
-    info += QDateTime::currentDateTime().toString(Qt::ISODate).toLatin1();
-    info += '\n';
-
-    stream << info;
-
+    stream << "[Trash Info]\n"
+           << "Path="
+           << QUrl::toPercentEncoding(f.absoluteFilePath(), "~_-./")
+           << "\n"
+           << "DeletionDate="
+           << QDateTime::currentDateTime().toString(Qt::ISODate)
+           << '\n';
     infoFile.close();
 
     // create info file format of trash file----- END
@@ -479,7 +476,7 @@ bool FileSystem::isFileLocked(const QString &fileName)
 
 bool FileSystem::isLnkFile(const QString &filename)
 {
-    return filename.endsWith(".lnk");
+    return filename.endsWith(QLatin1String(".lnk"));
 }
 
 bool FileSystem::isJunction(const QString &filename)
@@ -500,4 +497,33 @@ bool FileSystem::isJunction(const QString &filename)
 #endif
 }
 
+QString FileSystem::pathtoUNC(const QString &str)
+{
+    int len = 0;
+    QString longStr;
+
+    len = str.length();
+    longStr.reserve(len + 4);
+
+    // prepend \\?\ and convert '/' => '\' to support long names
+    if (str[0] == QLatin1Char('/') || str[0] == QLatin1Char('\\')) {
+        // Don't prepend if already UNC
+        if (!(len > 1 && (str[1] == QLatin1Char('/') || str[1] == QLatin1Char('\\')))) {
+            longStr.append(QStringLiteral("\\\\?"));
+        }
+    } else {
+        longStr.append(QStringLiteral("\\\\?\\")); // prepend string by this four magic chars.
+    }
+    longStr += str;
+
+    /* replace all occurences of / with the windows native \ */
+
+    for (auto it = longStr.begin(); it != longStr.end(); ++it) {
+        if (*it == QLatin1Char('/')) {
+            *it = QLatin1Char('\\');
+        }
+    }
+    return longStr;
+}
+
 } // namespace OCC
index 4c7b8e99913f4c0c2d16bafcc4f6ff760eedca63..4e35730588a67d6c4290540896c33fa72dbf2771 100644 (file)
@@ -156,35 +156,7 @@ namespace FileSystem {
      *  - A conversion is only done if the path len is larger than 245. Otherwise
      *    the windows API functions work with the normal "unixoid" representation too.
      */
-    template<typename S>
-    S pathtoUNC(const S &str)
-    {
-        int len = 0;
-        S longStr;
-
-        len = str.length();
-        longStr.reserve(len+4);
-
-        // prepend \\?\ and convert '/' => '\' to support long names
-        if( str[0] == '/' || str[0] == '\\' ) {
-            // Don't prepend if already UNC
-            if( !(len > 1 && (str[1] == '/' || str[1] == '\\')) ) {
-                longStr.append(R"(\\?)");
-            }
-        } else {
-            longStr.append(R"(\\?\)"); // prepend string by this four magic chars.
-        }
-        longStr += str;
-
-        /* replace all occurences of / with the windows native \ */
-        
-        for (auto it = longStr.begin(); it != longStr.end(); ++it) {
-            if(*it == '/') {
-                *it = '\\';
-            }
-        }
-        return longStr;
-    }
+    QString OCSYNC_EXPORT pathtoUNC(const QString &str);
 }
 
 /** @} */
index 4c0165eee3d0836d168954c8cf52fbe743c82c18..e0db3ae05fa5e70d04764414867a0fd6e83dbfc1 100644 (file)
@@ -108,7 +108,7 @@ SqlDatabase::CheckDbResult SqlDatabase::checkDb()
 
     quick_check.next();
     QString result = quick_check.stringValue(0);
-    if (result != "ok") {
+    if (result != QLatin1String("ok")) {
         qCWarning(lcSql) << "quick_check returned failure:" << result;
         return CheckDbResult::NotOk;
     }
@@ -384,14 +384,14 @@ void SqlQuery::bindValueInternal(int pos, const QVariant &value)
         break;
     case QVariant::DateTime: {
         const QDateTime dateTime = value.toDateTime();
-        const QString str = dateTime.toString(QLatin1String("yyyy-MM-ddThh:mm:ss.zzz"));
+        const QString str = dateTime.toString(QStringLiteral("yyyy-MM-ddThh:mm:ss.zzz"));
         res = sqlite3_bind_text16(_stmt, pos, str.utf16(),
             str.size() * static_cast<int>(sizeof(ushort)), SQLITE_TRANSIENT);
         break;
     }
     case QVariant::Time: {
         const QTime time = value.toTime();
-        const QString str = time.toString(QLatin1String("hh:mm:ss.zzz"));
+        const QString str = time.toString(QStringLiteral("hh:mm:ss.zzz"));
         res = sqlite3_bind_text16(_stmt, pos, str.utf16(),
             str.size() * static_cast<int>(sizeof(ushort)), SQLITE_TRANSIENT);
         break;
@@ -462,7 +462,7 @@ int SqlQuery::errorId() const
     return _errId;
 }
 
-QString SqlQuery::lastQuery() const
+const QByteArray &SqlQuery::lastQuery() const
 {
     return _sql;
 }
index 3eb530ce4d4867a6e56ecac979041f267563bfec..894bef85bd780f86a1f6d734e4084e7fe7d473b1 100644 (file)
@@ -152,7 +152,7 @@ public:
         bindValueInternal(pos, value);
     }
 
-    QString lastQuery() const;
+    const QByteArray &lastQuery() const;
     int numRowsAffected();
     void reset_and_clear_bindings();
     void finish();
index eb705822f33e51ab3e511406128cabcb5d4e5d6d..7e705d94e7486801027ec44424ef3b6cc2162424 100644 (file)
@@ -26,8 +26,8 @@ PluginFactory::~PluginFactory() = default;
 
 QString pluginFileName(const QString &type, const QString &name)
 {
-    return QString(QLatin1String("%1sync_%2_%3"))
-            .arg(APPLICATION_EXECUTABLE, type, name);
+    return QStringLiteral("%1sync_%2_%3")
+        .arg(QStringLiteral(APPLICATION_EXECUTABLE), type, name);
 }
 
 }
index ad777b36e103c27c4fdf4e5ae3b1afe08a854d83..f714277edfdd6a604982e5ab57ce44936879d1f4 100644 (file)
@@ -54,9 +54,9 @@ QByteArray RemotePermissions::toDbValue() const
     return result;
 }
 
-QByteArray RemotePermissions::toString() const
+QString RemotePermissions::toString() const
 {
-    return toDbValue();
+    return QString::fromUtf8(toDbValue());
 }
 
 RemotePermissions RemotePermissions::fromDbValue(const QByteArray &value)
index 4f62cca3cc07ab1e5b8182626129b8f3c83f2225..6e9550783891adaa635ace4b5cb39b0ddbade848 100644 (file)
@@ -66,7 +66,7 @@ public:
     QByteArray toDbValue() const;
 
     /// output for display purposes, no defined format (same as toDbValue in practice)
-    QByteArray toString() const;
+    QString toString() const;
 
     /// read value that was written with toDbValue()
     static RemotePermissions fromDbValue(const QByteArray &);
index f9b0f3b6b9ef2225d79e41c8c46f2591fde46733..849d212bfddc4525500806c9f09c648bdd27f4a7 100644 (file)
@@ -49,25 +49,25 @@ QString SyncFileStatus::toSocketAPIString() const
 
     switch (_tag) {
     case StatusNone:
-        statusString = QLatin1String("NOP");
+        statusString = QStringLiteral("NOP");
         canBeShared = false;
         break;
     case StatusSync:
-        statusString = QLatin1String("SYNC");
+        statusString = QStringLiteral("SYNC");
         break;
     case StatusWarning:
         // The protocol says IGNORE, but all implementations show a yellow warning sign.
-        statusString = QLatin1String("IGNORE");
+        statusString = QStringLiteral("IGNORE");
         break;
     case StatusUpToDate:
-        statusString = QLatin1String("OK");
+        statusString = QStringLiteral("OK");
         break;
     case StatusError:
-        statusString = QLatin1String("ERROR");
+        statusString = QStringLiteral("ERROR");
         break;
     case StatusExcluded:
         // The protocol says IGNORE, but all implementations show a yellow warning sign.
-        statusString = QLatin1String("IGNORE");
+        statusString = QStringLiteral("IGNORE");
         break;
     }
     if (canBeShared && _shared) {
index 4ed9732dc3e13125cb5966e9c0f2fd16597fdaa2..8dcecae70cc8cb9aa851f0576ece6819f4567b16 100644 (file)
@@ -74,7 +74,7 @@ static QByteArray defaultJournalMode(const QString &dbPath)
     // WAL journaling mode. They work fine with DELETE.
     QString fileSystem = FileSystem::fileSystemForPath(dbPath);
     qCInfo(lcDb) << "Detected filesystem" << fileSystem << "for" << dbPath;
-    if (fileSystem.contains("FAT")) {
+    if (fileSystem.contains(QLatin1String("FAT"))) {
         qCInfo(lcDb) << "Filesystem contains FAT - using DELETE journal mode";
         return "DELETE";
     }
@@ -109,13 +109,12 @@ QString SyncJournalDb::makeDbName(const QString &localPath,
     const QString &remotePath,
     const QString &user)
 {
-    QString journalPath = QLatin1String(".sync_");
+    QString journalPath = QStringLiteral(".sync_");
 
-    QString key = QString::fromUtf8("%1@%2:%3").arg(user, remoteUrl.toString(), remotePath);
+    QString key = QStringLiteral("%1@%2:%3").arg(user, remoteUrl.toString(), remotePath);
 
     QByteArray ba = QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Md5);
-    journalPath.append(ba.left(6).toHex());
-    journalPath.append(".db");
+    journalPath += QString::fromLatin1(ba.left(6).toHex()) + QStringLiteral(".db");
 
     // If it exists already, the path is clearly usable
     QFile file(QDir(localPath).filePath(journalPath));
@@ -142,12 +141,12 @@ bool SyncJournalDb::maybeMigrateDb(const QString &localPath, const QString &abso
     if (!FileSystem::fileExists(oldDbName)) {
         return true;
     }
-    const QString oldDbNameShm = oldDbName + "-shm";
-    const QString oldDbNameWal = oldDbName + "-wal";
+    const QString oldDbNameShm = oldDbName + QStringLiteral("-shm");
+    const QString oldDbNameWal = oldDbName + QStringLiteral("-wal");
 
     const QString newDbName = absoluteJournalPath;
-    const QString newDbNameShm = newDbName + "-shm";
-    const QString newDbNameWal = newDbName + "-wal";
+    const QString newDbNameShm = newDbName + QStringLiteral("-shm");
+    const QString newDbNameWal = newDbName + QStringLiteral("-wal");
 
     // Whenever there is an old db file, migrate it to the new db path.
     // This is done to make switching from older versions to newer versions
@@ -178,17 +177,17 @@ bool SyncJournalDb::maybeMigrateDb(const QString &localPath, const QString &abso
     }
 
     if (!FileSystem::rename(oldDbName, newDbName, &error)) {
-        qCWarning(lcDb) << "Database migration: could not rename " << oldDbName
+        qCWarning(lcDb) << "Database migration: could not rename" << oldDbName
                         << "to" << newDbName << ":" << error;
         return false;
     }
     if (!FileSystem::rename(oldDbNameWal, newDbNameWal, &error)) {
-        qCWarning(lcDb) << "Database migration: could not rename " << oldDbNameWal
+        qCWarning(lcDb) << "Database migration: could not rename" << oldDbNameWal
                         << "to" << newDbNameWal << ":" << error;
         return false;
     }
     if (!FileSystem::rename(oldDbNameShm, newDbNameShm, &error)) {
-        qCWarning(lcDb) << "Database migration: could not rename " << oldDbNameShm
+        qCWarning(lcDb) << "Database migration: could not rename" << oldDbNameShm
                         << "to" << newDbNameShm << ":" << error;
         return false;
     }
@@ -226,7 +225,7 @@ void SyncJournalDb::startTransaction()
 {
     if (_transaction == 0) {
         if (!_db.transaction()) {
-            qCWarning(lcDb) << "ERROR starting transaction: " << _db.error();
+            qCWarning(lcDb) << "ERROR starting transaction:" << _db.error();
             return;
         }
         _transaction = 1;
@@ -239,7 +238,7 @@ void SyncJournalDb::commitTransaction()
 {
     if (_transaction == 1) {
         if (!_db.commit()) {
-            qCWarning(lcDb) << "ERROR committing to the database: " << _db.error();
+            qCWarning(lcDb) << "ERROR committing to the database:" << _db.error();
             return;
         }
         _transaction = 0;
@@ -270,7 +269,7 @@ bool SyncJournalDb::checkConnect()
         // Unfortunately the sqlite isOpen check can return true even when the underlying storage
         // has become unavailable - and then some operations may cause crashes. See #6049
         if (!QFile::exists(_dbFile)) {
-            qCWarning(lcDb) << "Database open, but file " + _dbFile + " does not exist";
+            qCWarning(lcDb) << "Database open, but file" << _dbFile << "does not exist";
             close();
             return false;
         }
@@ -278,26 +277,26 @@ bool SyncJournalDb::checkConnect()
     }
 
     if (_dbFile.isEmpty()) {
-        qCWarning(lcDb) << "Database filename" + _dbFile + " is empty";
+        qCWarning(lcDb) << "Database filename" << _dbFile << "is empty";
         return false;
     }
 
     // The database file is created by this call (SQLITE_OPEN_CREATE)
     if (!_db.openOrCreateReadWrite(_dbFile)) {
         QString error = _db.error();
-        qCWarning(lcDb) << "Error opening the db: " << error;
+        qCWarning(lcDb) << "Error opening the db:" << error;
         return false;
     }
 
     if (!QFile::exists(_dbFile)) {
-        qCWarning(lcDb) << "Database file" + _dbFile + " does not exist";
+        qCWarning(lcDb) << "Database file" << _dbFile << "does not exist";
         return false;
     }
 
     SqlQuery pragma1(_db);
     pragma1.prepare("SELECT sqlite_version();");
     if (!pragma1.exec()) {
-        return sqlFail("SELECT sqlite_version()", pragma1);
+        return sqlFail(QStringLiteral("SELECT sqlite_version()"), pragma1);
     } else {
         pragma1.next();
         qCInfo(lcDb) << "sqlite3 version" << pragma1.stringValue(0);
@@ -309,7 +308,7 @@ bool SyncJournalDb::checkConnect()
         locking_mode_env = "EXCLUSIVE";
     pragma1.prepare("PRAGMA locking_mode=" + locking_mode_env + ";");
     if (!pragma1.exec()) {
-        return sqlFail("Set PRAGMA locking_mode", pragma1);
+        return sqlFail(QStringLiteral("Set PRAGMA locking_mode"), pragma1);
     } else {
         pragma1.next();
         qCInfo(lcDb) << "sqlite3 locking_mode=" << pragma1.stringValue(0);
@@ -317,7 +316,7 @@ bool SyncJournalDb::checkConnect()
 
     pragma1.prepare("PRAGMA journal_mode=" + _journalMode + ";");
     if (!pragma1.exec()) {
-        return sqlFail("Set PRAGMA journal_mode", pragma1);
+        return sqlFail(QStringLiteral("Set PRAGMA journal_mode"), pragma1);
     } else {
         pragma1.next();
         qCInfo(lcDb) << "sqlite3 journal_mode=" << pragma1.stringValue(0);
@@ -328,7 +327,7 @@ bool SyncJournalDb::checkConnect()
     if (!env_temp_store.isEmpty()) {
         pragma1.prepare("PRAGMA temp_store = " + env_temp_store + ";");
         if (!pragma1.exec()) {
-            return sqlFail("Set PRAGMA temp_store", pragma1);
+            return sqlFail(QStringLiteral("Set PRAGMA temp_store"), pragma1);
         }
         qCInfo(lcDb) << "sqlite3 with temp_store =" << env_temp_store;
     }
@@ -340,14 +339,14 @@ bool SyncJournalDb::checkConnect()
         synchronousMode = "NORMAL";
     pragma1.prepare("PRAGMA synchronous = " + synchronousMode + ";");
     if (!pragma1.exec()) {
-        return sqlFail("Set PRAGMA synchronous", pragma1);
+        return sqlFail(QStringLiteral("Set PRAGMA synchronous"), pragma1);
     } else {
         qCInfo(lcDb) << "sqlite3 synchronous=" << synchronousMode;
     }
 
     pragma1.prepare("PRAGMA case_sensitive_like = ON;");
     if (!pragma1.exec()) {
-        return sqlFail("Set PRAGMA case_sensitivity", pragma1);
+        return sqlFail(QStringLiteral("Set PRAGMA case_sensitivity"), pragma1);
     }
 
     sqlite3_create_function(_db.sqliteDb(), "parent_hash", 1, SQLITE_UTF8 | SQLITE_DETERMINISTIC, nullptr,
@@ -406,7 +405,7 @@ bool SyncJournalDb::checkConnect()
             return checkConnect();
         }
 
-        return sqlFail("Create table metadata", createQuery);
+        return sqlFail(QStringLiteral("Create table metadata"), createQuery);
     }
 
     createQuery.prepare("CREATE TABLE IF NOT EXISTS downloadinfo("
@@ -418,7 +417,7 @@ bool SyncJournalDb::checkConnect()
                         ");");
 
     if (!createQuery.exec()) {
-        return sqlFail("Create table downloadinfo", createQuery);
+        return sqlFail(QStringLiteral("Create table downloadinfo"), createQuery);
     }
 
     createQuery.prepare("CREATE TABLE IF NOT EXISTS uploadinfo("
@@ -433,7 +432,7 @@ bool SyncJournalDb::checkConnect()
                         ");");
 
     if (!createQuery.exec()) {
-        return sqlFail("Create table uploadinfo", createQuery);
+        return sqlFail(QStringLiteral("Create table uploadinfo"), createQuery);
     }
 
     // create the blacklist table.
@@ -447,7 +446,7 @@ bool SyncJournalDb::checkConnect()
                         ");");
 
     if (!createQuery.exec()) {
-        return sqlFail("Create table blacklist", createQuery);
+        return sqlFail(QStringLiteral("Create table blacklist"), createQuery);
     }
 
     createQuery.prepare("CREATE TABLE IF NOT EXISTS async_poll("
@@ -456,7 +455,7 @@ bool SyncJournalDb::checkConnect()
                         "filesize BIGINT,"
                         "pollpath VARCHAR(4096));");
     if (!createQuery.exec()) {
-        return sqlFail("Create table async_poll", createQuery);
+        return sqlFail(QStringLiteral("Create table async_poll"), createQuery);
     }
 
     // create the selectivesync table.
@@ -466,7 +465,7 @@ bool SyncJournalDb::checkConnect()
                         ");");
 
     if (!createQuery.exec()) {
-        return sqlFail("Create table selectivesync", createQuery);
+        return sqlFail(QStringLiteral("Create table selectivesync"), createQuery);
     }
 
     // create the checksumtype table.
@@ -475,7 +474,7 @@ bool SyncJournalDb::checkConnect()
                         "name TEXT UNIQUE"
                         ");");
     if (!createQuery.exec()) {
-        return sqlFail("Create table version", createQuery);
+        return sqlFail(QStringLiteral("Create table version"), createQuery);
     }
 
     // create the datafingerprint table.
@@ -483,7 +482,7 @@ bool SyncJournalDb::checkConnect()
                         "fingerprint TEXT UNIQUE"
                         ");");
     if (!createQuery.exec()) {
-        return sqlFail("Create table datafingerprint", createQuery);
+        return sqlFail(QStringLiteral("Create table datafingerprint"), createQuery);
     }
 
     // create the flags table.
@@ -492,7 +491,7 @@ bool SyncJournalDb::checkConnect()
                         "pinState INTEGER"
                         ");");
     if (!createQuery.exec()) {
-        return sqlFail("Create table flags", createQuery);
+        return sqlFail(QStringLiteral("Create table flags"), createQuery);
     }
 
     // create the conflicts table.
@@ -503,7 +502,7 @@ bool SyncJournalDb::checkConnect()
                         "baseModtime INTEGER"
                         ");");
     if (!createQuery.exec()) {
-        return sqlFail("Create table conflicts", createQuery);
+        return sqlFail(QStringLiteral("Create table conflicts"), createQuery);
     }
 
     createQuery.prepare("CREATE TABLE IF NOT EXISTS version("
@@ -513,7 +512,7 @@ bool SyncJournalDb::checkConnect()
                         "custom VARCHAR(256)"
                         ");");
     if (!createQuery.exec()) {
-        return sqlFail("Create table version", createQuery);
+        return sqlFail(QStringLiteral("Create table version"), createQuery);
     }
 
     bool forceRemoteDiscovery = false;
@@ -530,7 +529,7 @@ bool SyncJournalDb::checkConnect()
         createQuery.bindValue(3, MIRALL_VERSION_PATCH);
         createQuery.bindValue(4, MIRALL_VERSION_BUILD);
         if (!createQuery.exec()) {
-            return sqlFail("Update version", createQuery);
+            return sqlFail(QStringLiteral("Update version"), createQuery);
         }
 
     } else {
@@ -563,12 +562,12 @@ bool SyncJournalDb::checkConnect()
             createQuery.bindValue(6, minor);
             createQuery.bindValue(7, patch);
             if (!createQuery.exec()) {
-                return sqlFail("Update version", createQuery);
+                return sqlFail(QStringLiteral("Update version"), createQuery);
             }
         }
     }
 
-    commitInternal("checkConnect");
+    commitInternal(QStringLiteral("checkConnect"));
 
     bool rc = updateDatabaseStructure();
     if (!rc) {
@@ -588,11 +587,11 @@ bool SyncJournalDb::checkConnect()
     }
 
     if (!_deleteDownloadInfoQuery.initOrReset("DELETE FROM downloadinfo WHERE path=?1", _db)) {
-        return sqlFail("prepare _deleteDownloadInfoQuery", _deleteDownloadInfoQuery);
+        return sqlFail(QStringLiteral("prepare _deleteDownloadInfoQuery"), _deleteDownloadInfoQuery);
     }
 
     if (!_deleteUploadInfoQuery.initOrReset("DELETE FROM uploadinfo WHERE path=?1", _db)) {
-        return sqlFail("prepare _deleteUploadInfoQuery", _deleteUploadInfoQuery);
+        return sqlFail(QStringLiteral("prepare _deleteUploadInfoQuery"), _deleteUploadInfoQuery);
     }
 
     QByteArray sql("SELECT lastTryEtag, lastTryModtime, retrycount, errorstring, lastTryTime, ignoreDuration, renameTarget, errorCategory, requestId "
@@ -603,11 +602,11 @@ bool SyncJournalDb::checkConnect()
         sql += " COLLATE NOCASE";
     }
     if (!_getErrorBlacklistQuery.initOrReset(sql, _db)) {
-        return sqlFail("prepare _getErrorBlacklistQuery", _getErrorBlacklistQuery);
+        return sqlFail(QStringLiteral("prepare _getErrorBlacklistQuery"), _getErrorBlacklistQuery);
     }
 
     // don't start a new transaction now
-    commitInternal(QString("checkConnect End"), false);
+    commitInternal(QStringLiteral("checkConnect End"), false);
 
     // This avoid reading from the DB if we already know it is empty
     // thereby speeding up the initial discovery significantly.
@@ -615,9 +614,9 @@ bool SyncJournalDb::checkConnect()
 
     // Hide 'em all!
     FileSystem::setFileHidden(databaseFilePath(), true);
-    FileSystem::setFileHidden(databaseFilePath() + "-wal", true);
-    FileSystem::setFileHidden(databaseFilePath() + "-shm", true);
-    FileSystem::setFileHidden(databaseFilePath() + "-journal", true);
+    FileSystem::setFileHidden(databaseFilePath() + QStringLiteral("-wal"), true);
+    FileSystem::setFileHidden(databaseFilePath() + QStringLiteral("-shm"), true);
+    FileSystem::setFileHidden(databaseFilePath() + QStringLiteral("-journal"), true);
 
     return rc;
 }
@@ -659,113 +658,113 @@ bool SyncJournalDb::updateMetadataTableStructure()
         SqlQuery query(_db);
         query.prepare("ALTER TABLE metadata ADD COLUMN fileid VARCHAR(128);");
         if (!query.exec()) {
-            sqlFail("updateMetadataTableStructure: Add column fileid", query);
+            sqlFail(QStringLiteral("updateMetadataTableStructure: Add column fileid"), query);
             re = false;
         }
 
         query.prepare("CREATE INDEX metadata_file_id ON metadata(fileid);");
         if (!query.exec()) {
-            sqlFail("updateMetadataTableStructure: create index fileid", query);
+            sqlFail(QStringLiteral("updateMetadataTableStructure: create index fileid"), query);
             re = false;
         }
-        commitInternal("update database structure: add fileid col");
+        commitInternal(QStringLiteral("update database structure: add fileid col"));
     }
     if (columns.indexOf("remotePerm") == -1) {
         SqlQuery query(_db);
         query.prepare("ALTER TABLE metadata ADD COLUMN remotePerm VARCHAR(128);");
         if (!query.exec()) {
-            sqlFail("updateMetadataTableStructure: add column remotePerm", query);
+            sqlFail(QStringLiteral("updateMetadataTableStructure: add column remotePerm"), query);
             re = false;
         }
-        commitInternal("update database structure (remotePerm)");
+        commitInternal(QStringLiteral("update database structure (remotePerm)"));
     }
     if (columns.indexOf("filesize") == -1) {
         SqlQuery query(_db);
         query.prepare("ALTER TABLE metadata ADD COLUMN filesize BIGINT;");
         if (!query.exec()) {
-            sqlFail("updateDatabaseStructure: add column filesize", query);
+            sqlFail(QStringLiteral("updateDatabaseStructure: add column filesize"), query);
             re = false;
         }
-        commitInternal("update database structure: add filesize col");
+        commitInternal(QStringLiteral("update database structure: add filesize col"));
     }
 
     if (true) {
         SqlQuery query(_db);
         query.prepare("CREATE INDEX IF NOT EXISTS metadata_inode ON metadata(inode);");
         if (!query.exec()) {
-            sqlFail("updateMetadataTableStructure: create index inode", query);
+            sqlFail(QStringLiteral("updateMetadataTableStructure: create index inode"), query);
             re = false;
         }
-        commitInternal("update database structure: add inode index");
+        commitInternal(QStringLiteral("update database structure: add inode index"));
     }
 
     if (true) {
         SqlQuery query(_db);
         query.prepare("CREATE INDEX IF NOT EXISTS metadata_path ON metadata(path);");
         if (!query.exec()) {
-            sqlFail("updateMetadataTableStructure: create index path", query);
+            sqlFail(QStringLiteral("updateMetadataTableStructure: create index path"), query);
             re = false;
         }
-        commitInternal("update database structure: add path index");
+        commitInternal(QStringLiteral("update database structure: add path index"));
     }
 
     if (1) {
         SqlQuery query(_db);
         query.prepare("CREATE INDEX IF NOT EXISTS metadata_parent ON metadata(parent_hash(path));");
         if (!query.exec()) {
-            sqlFail("updateMetadataTableStructure: create index parent", query);
+            sqlFail(QStringLiteral("updateMetadataTableStructure: create index parent"), query);
             re = false;
         }
-        commitInternal("update database structure: add parent index");
+        commitInternal(QStringLiteral("update database structure: add parent index"));
     }
 
     if (columns.indexOf("ignoredChildrenRemote") == -1) {
         SqlQuery query(_db);
         query.prepare("ALTER TABLE metadata ADD COLUMN ignoredChildrenRemote INT;");
         if (!query.exec()) {
-            sqlFail("updateMetadataTableStructure: add ignoredChildrenRemote column", query);
+            sqlFail(QStringLiteral("updateMetadataTableStructure: add ignoredChildrenRemote column"), query);
             re = false;
         }
-        commitInternal("update database structure: add ignoredChildrenRemote col");
+        commitInternal(QStringLiteral("update database structure: add ignoredChildrenRemote col"));
     }
 
     if (columns.indexOf("contentChecksum") == -1) {
         SqlQuery query(_db);
         query.prepare("ALTER TABLE metadata ADD COLUMN contentChecksum TEXT;");
         if (!query.exec()) {
-            sqlFail("updateMetadataTableStructure: add contentChecksum column", query);
+            sqlFail(QStringLiteral("updateMetadataTableStructure: add contentChecksum column"), query);
             re = false;
         }
-        commitInternal("update database structure: add contentChecksum col");
+        commitInternal(QStringLiteral("update database structure: add contentChecksum col"));
     }
     if (columns.indexOf("contentChecksumTypeId") == -1) {
         SqlQuery query(_db);
         query.prepare("ALTER TABLE metadata ADD COLUMN contentChecksumTypeId INTEGER;");
         if (!query.exec()) {
-            sqlFail("updateMetadataTableStructure: add contentChecksumTypeId column", query);
+            sqlFail(QStringLiteral("updateMetadataTableStructure: add contentChecksumTypeId column"), query);
             re = false;
         }
-        commitInternal("update database structure: add contentChecksumTypeId col");
+        commitInternal(QStringLiteral("update database structure: add contentChecksumTypeId col"));
     }
 
     if (!columns.contains("e2eMangledName")) {
         SqlQuery query(_db);
         query.prepare("ALTER TABLE metadata ADD COLUMN e2eMangledName TEXT;");
         if (!query.exec()) {
-            sqlFail("updateMetadataTableStructure: add e2eMangledName column", query);
+            sqlFail(QStringLiteral("updateMetadataTableStructure: add e2eMangledName column"), query);
             re = false;
         }
-        commitInternal("update database structure: add e2eMangledName col");
+        commitInternal(QStringLiteral("update database structure: add e2eMangledName col"));
     }
 
     if (!columns.contains("isE2eEncrypted")) {
         SqlQuery query(_db);
         query.prepare("ALTER TABLE metadata ADD COLUMN isE2eEncrypted INTEGER;");
         if (!query.exec()) {
-            sqlFail("updateMetadataTableStructure: add isE2eEncrypted column", query);
+            sqlFail(QStringLiteral("updateMetadataTableStructure: add isE2eEncrypted column"), query);
             re = false;
         }
-        commitInternal("update database structure: add isE2eEncrypted col");
+        commitInternal(QStringLiteral("update database structure: add isE2eEncrypted col"));
     }
 
     auto uploadInfoColumns = tableColumns("uploadinfo");
@@ -775,10 +774,10 @@ bool SyncJournalDb::updateMetadataTableStructure()
         SqlQuery query(_db);
         query.prepare("ALTER TABLE uploadinfo ADD COLUMN contentChecksum TEXT;");
         if (!query.exec()) {
-            sqlFail("updateMetadataTableStructure: add contentChecksum column", query);
+            sqlFail(QStringLiteral("updateMetadataTableStructure: add contentChecksum column"), query);
             re = false;
         }
-        commitInternal("update database structure: add contentChecksum col for uploadinfo");
+        commitInternal(QStringLiteral("update database structure: add contentChecksum col for uploadinfo"));
     }
 
     auto conflictsColumns = tableColumns("conflicts");
@@ -788,7 +787,7 @@ bool SyncJournalDb::updateMetadataTableStructure()
         SqlQuery query(_db);
         query.prepare("ALTER TABLE conflicts ADD COLUMN basePath TEXT;");
         if (!query.exec()) {
-            sqlFail("updateMetadataTableStructure: add basePath column", query);
+            sqlFail(QStringLiteral("updateMetadataTableStructure: add basePath column"), query);
             re = false;
         }
     }
@@ -797,10 +796,10 @@ bool SyncJournalDb::updateMetadataTableStructure()
         SqlQuery query(_db);
         query.prepare("CREATE INDEX IF NOT EXISTS metadata_e2e_id ON metadata(e2eMangledName);");
         if (!query.exec()) {
-            sqlFail("updateMetadataTableStructure: create index e2eMangledName", query);
+            sqlFail(QStringLiteral("updateMetadataTableStructure: create index e2eMangledName"), query);
             re = false;
         }
-        commitInternal("update database structure: add e2eMangledName index");
+        commitInternal(QStringLiteral("update database structure: add e2eMangledName index"));
     }
 
     return re;
@@ -819,50 +818,50 @@ bool SyncJournalDb::updateErrorBlacklistTableStructure()
         SqlQuery query(_db);
         query.prepare("ALTER TABLE blacklist ADD COLUMN lastTryTime INTEGER(8);");
         if (!query.exec()) {
-            sqlFail("updateBlacklistTableStructure: Add lastTryTime fileid", query);
+            sqlFail(QStringLiteral("updateBlacklistTableStructure: Add lastTryTime fileid"), query);
             re = false;
         }
         query.prepare("ALTER TABLE blacklist ADD COLUMN ignoreDuration INTEGER(8);");
         if (!query.exec()) {
-            sqlFail("updateBlacklistTableStructure: Add ignoreDuration fileid", query);
+            sqlFail(QStringLiteral("updateBlacklistTableStructure: Add ignoreDuration fileid"), query);
             re = false;
         }
-        commitInternal("update database structure: add lastTryTime, ignoreDuration cols");
+        commitInternal(QStringLiteral("update database structure: add lastTryTime, ignoreDuration cols"));
     }
     if (columns.indexOf("renameTarget") == -1) {
         SqlQuery query(_db);
         query.prepare("ALTER TABLE blacklist ADD COLUMN renameTarget VARCHAR(4096);");
         if (!query.exec()) {
-            sqlFail("updateBlacklistTableStructure: Add renameTarget", query);
+            sqlFail(QStringLiteral("updateBlacklistTableStructure: Add renameTarget"), query);
             re = false;
         }
-        commitInternal("update database structure: add renameTarget col");
+        commitInternal(QStringLiteral("update database structure: add renameTarget col"));
     }
 
     if (columns.indexOf("errorCategory") == -1) {
         SqlQuery query(_db);
         query.prepare("ALTER TABLE blacklist ADD COLUMN errorCategory INTEGER(8);");
         if (!query.exec()) {
-            sqlFail("updateBlacklistTableStructure: Add errorCategory", query);
+            sqlFail(QStringLiteral("updateBlacklistTableStructure: Add errorCategory"), query);
             re = false;
         }
-        commitInternal("update database structure: add errorCategory col");
+        commitInternal(QStringLiteral("update database structure: add errorCategory col"));
     }
 
     if (columns.indexOf("requestId") == -1) {
         SqlQuery query(_db);
         query.prepare("ALTER TABLE blacklist ADD COLUMN requestId VARCHAR(36);");
         if (!query.exec()) {
-            sqlFail("updateBlacklistTableStructure: Add requestId", query);
+            sqlFail(QStringLiteral("updateBlacklistTableStructure: Add requestId"), query);
             re = false;
         }
-        commitInternal("update database structure: add errorCategory col");
+        commitInternal(QStringLiteral("update database structure: add errorCategory col"));
     }
 
     SqlQuery query(_db);
     query.prepare("CREATE INDEX IF NOT EXISTS blacklist_index ON blacklist(path collate nocase);");
     if (!query.exec()) {
-        sqlFail("updateErrorBlacklistTableStructure: create index blacklit", query);
+        sqlFail(QStringLiteral("updateErrorBlacklistTableStructure: create index blacklit"), query);
         re = false;
     }
 
@@ -882,7 +881,7 @@ QVector<QByteArray> SyncJournalDb::tableColumns(const QByteArray &table)
     while (query.next().hasData) {
         columns.append(query.baValue(1));
     }
-    qCDebug(lcDb) << "Columns in the current journal: " << columns;
+    qCDebug(lcDb) << "Columns in the current journal:" << columns;
     return columns;
 }
 
@@ -928,7 +927,7 @@ bool SyncJournalDb::setFileRecord(const SyncJournalFileRecord &_record)
         QByteArray fileId(record._fileId);
         if (fileId.isEmpty())
             fileId = "";
-        QByteArray remotePerm = record._remotePerm.toString();
+        QByteArray remotePerm = record._remotePerm.toDbValue();
         QByteArray checksumType, checksum;
         parseChecksumHeader(record._checksumHeader, &checksumType, &checksum);
         int contentChecksumTypeId = mapChecksumType(checksumType);
@@ -973,6 +972,7 @@ bool SyncJournalDb::setFileRecord(const SyncJournalFileRecord &_record)
     }
 }
 
+// TODO: filename -> QBytearray?
 bool SyncJournalDb::deleteFileRecord(const QString &filename, bool recursively)
 {
     QMutexLocker locker(&_mutex);
@@ -1035,7 +1035,7 @@ bool SyncJournalDb::getFileRecord(const QByteArray &filename, SyncJournalFileRec
         auto next = _getFileRecordQuery.next();
         if (!next.ok) {
             QString err = _getFileRecordQuery.error();
-            qCWarning(lcDb) << "No journal entry found for " << filename << "Error: " << err;
+            qCWarning(lcDb) << "No journal entry found for" << filename << "Error:" << err;
             close();
             return false;
         }
@@ -1243,7 +1243,7 @@ bool SyncJournalDb::listFilesInPath(const QByteArray& path,
         SyncJournalFileRecord rec;
         fillFileRecordFromGetQuery(rec, _listFilesInPathQuery);
         if (!rec._path.startsWith(path) || rec._path.indexOf("/", path.size() + 1) > 0) {
-            qWarning(lcDb) << "hash collision " << path << rec._path;
+            qWarning(lcDb) << "hash collision" << path << rec._path;
             continue;
         }
         rowCallback(rec);
@@ -1376,7 +1376,7 @@ static bool deleteBatch(SqlQuery &query, const QStringList &entries, const QStri
     if (entries.isEmpty())
         return true;
 
-    qCDebug(lcDb) << "Removing stale " << qPrintable(name) << " entries: " << entries.join(", ");
+    qCDebug(lcDb) << "Removing stale" << name << "entries:" << entries.join(QStringLiteral(", "));
     // FIXME: Was ported from execBatch, check if correct!
     foreach (const QString &entry, entries) {
         query.reset_and_clear_bindings();
@@ -1473,7 +1473,7 @@ QVector<SyncJournalDb::DownloadInfo> SyncJournalDb::getAndDeleteStaleDownloadInf
         }
     }
 
-    if (!deleteBatch(_deleteDownloadInfoQuery, superfluousPaths, "downloadinfo"))
+    if (!deleteBatch(_deleteDownloadInfoQuery, superfluousPaths, QStringLiteral("downloadinfo")))
         return empty_result;
 
     return deleted_entries;
@@ -1488,7 +1488,7 @@ int SyncJournalDb::downloadInfoCount()
         SqlQuery query("SELECT count(*) FROM downloadinfo", _db);
 
         if (!query.exec()) {
-            sqlFail("Count number of downloadinfo entries failed", query);
+            sqlFail(QStringLiteral("Count number of downloadinfo entries failed"), query);
         }
         if (query.next().hasData) {
             re = query.intValue(0);
@@ -1592,7 +1592,7 @@ QVector<uint> SyncJournalDb::deleteStaleUploadInfos(const QSet<QString> &keep)
         }
     }
 
-    deleteBatch(_deleteUploadInfoQuery, superfluousPaths, "uploadinfo");
+    deleteBatch(_deleteUploadInfoQuery, superfluousPaths, QStringLiteral("uploadinfo"));
     return ids;
 }
 
@@ -1653,7 +1653,7 @@ bool SyncJournalDb::deleteStaleErrorBlacklistEntries(const QSet<QString> &keep)
 
     SqlQuery delQuery(_db);
     delQuery.prepare("DELETE FROM blacklist WHERE path = ?");
-    return deleteBatch(delQuery, superfluousPaths, "blacklist");
+    return deleteBatch(delQuery, superfluousPaths, QStringLiteral("blacklist"));
 }
 
 void SyncJournalDb::deleteStaleFlagsEntries()
@@ -1675,7 +1675,7 @@ int SyncJournalDb::errorBlackListEntryCount()
         SqlQuery query("SELECT count(*) FROM blacklist", _db);
 
         if (!query.exec()) {
-            sqlFail("Count number of blacklist entries failed", query);
+            sqlFail(QStringLiteral("Count number of blacklist entries failed"), query);
         }
         if (query.next().hasData) {
             re = query.intValue(0);
@@ -1693,7 +1693,7 @@ int SyncJournalDb::wipeErrorBlacklist()
         query.prepare("DELETE FROM blacklist");
 
         if (!query.exec()) {
-            sqlFail("Deletion of whole blacklist failed", query);
+            sqlFail(QStringLiteral("Deletion of whole blacklist failed"), query);
             return -1;
         }
         return query.numRowsAffected();
@@ -1714,7 +1714,7 @@ void SyncJournalDb::wipeErrorBlacklistEntry(const QString &file)
         query.prepare("DELETE FROM blacklist WHERE path=?1");
         query.bindValue(1, file);
         if (!query.exec()) {
-            sqlFail("Deletion of blacklist item failed.", query);
+            sqlFail(QStringLiteral("Deletion of blacklist item failed."), query);
         }
     }
 }
@@ -1728,7 +1728,7 @@ void SyncJournalDb::wipeErrorBlacklistCategory(SyncJournalErrorBlacklistRecord::
         query.prepare("DELETE FROM blacklist WHERE errorCategory=?1");
         query.bindValue(1, category);
         if (!query.exec()) {
-            sqlFail("Deletion of blacklist category failed.", query);
+            sqlFail(QStringLiteral("Deletion of blacklist category failed."), query);
         }
     }
 }
@@ -1737,7 +1737,7 @@ void SyncJournalDb::setErrorBlacklistEntry(const SyncJournalErrorBlacklistRecord
 {
     QMutexLocker locker(&_mutex);
 
-    qCInfo(lcDb) << "Setting blacklist entry for " << item._file << item._retryCount
+    qCInfo(lcDb) << "Setting blacklist entry for" << item._file << item._retryCount
                  << item._errorString << item._lastTryTime << item._ignoreDuration
                  << item._lastTryModtime << item._lastTryEtag << item._renameTarget
                  << item._errorCategory;
@@ -1883,7 +1883,7 @@ void SyncJournalDb::setSelectiveSyncList(SyncJournalDb::SelectiveSyncListType ty
         }
     }
 
-    commitInternal("setSelectiveSyncList");
+    commitInternal(QStringLiteral("setSelectiveSyncList"));
 }
 
 void SyncJournalDb::avoidRenamesOnNextSync(const QByteArray &path)
@@ -2349,7 +2349,7 @@ bool SyncJournalDb::isOpen()
 
 void SyncJournalDb::commitInternal(const QString &context, bool startTrans)
 {
-    qCDebug(lcDb) << "Transaction commit " << context << (startTrans ? "and starting new transaction" : "");
+    qCDebug(lcDb) << "Transaction commit" << context << (startTrans ? "and starting new transaction" : "");
     commitTransaction();
 
     if (startTrans) {
index 9e4f13ce8a59844ebe250f6234a72c6a9523ac0e..55ff8647c49a319ac62f6a55133cc23438abf1b2 100644 (file)
@@ -97,7 +97,7 @@ QString Utility::formatFingerprint(const QByteArray &fmhash, bool colonSeparated
 
     QString fp = QString::fromLatin1(hash.trimmed());
     if (colonSeparated) {
-        fp.replace(QChar(' '), QChar(':'));
+        fp.replace(QLatin1Char(' '), QLatin1Char(':'));
     }
 
     return fp;
@@ -177,13 +177,14 @@ static QLatin1String platform()
 QByteArray Utility::userAgentString()
 {
     return QStringLiteral("Mozilla/5.0 (%1) mirall/%2 (%3, %4-%5 ClientArchitecture: %6 OsArchitecture: %7)")
-                     .arg(platform(),
-                         QLatin1String(MIRALL_VERSION_STRING),
-                         qApp->applicationName(),
-                         QSysInfo::productType(),
-                         QSysInfo::kernelVersion(),
-                         QSysInfo::buildCpuArchitecture(),
-                         QSysInfo::currentCpuArchitecture()).toLatin1();
+        .arg(platform(),
+            QStringLiteral(MIRALL_VERSION_STRING),
+            qApp->applicationName(),
+            QSysInfo::productType(),
+            QSysInfo::kernelVersion(),
+            QSysInfo::buildCpuArchitecture(),
+            QSysInfo::currentCpuArchitecture())
+        .toLatin1();
 }
 
 QByteArray Utility::friendlyUserAgentString()
@@ -240,7 +241,7 @@ QString Utility::compactFormatDouble(double value, int prec, const QString &unit
     QLocale locale = QLocale::system();
     QChar decPoint = locale.decimalPoint();
     QString str = locale.toString(value, 'f', prec);
-    while (str.endsWith('0') || str.endsWith(decPoint)) {
+    while (str.endsWith(QLatin1Char('0')) || str.endsWith(decPoint)) {
         if (str.endsWith(decPoint)) {
             str.chop(1);
             break;
@@ -367,7 +368,7 @@ QString Utility::fileNameForGuiUse(const QString &fName)
 {
     if (isMac()) {
         QString n(fName);
-        return n.replace(QChar(':'), QChar('/'));
+        return n.replace(QLatin1Char(':'), QLatin1Char('/'));
     }
     return fName;
 }
@@ -445,12 +446,12 @@ QByteArray Utility::versionOfInstalledBinary(const QString &command)
             binary = qApp->arguments()[0];
         }
         QStringList params;
-        params << QLatin1String("--version");
+        params << QStringLiteral("--version");
         QProcess process;
         process.start(binary, params);
         process.waitForFinished(); // sets current thread to sleep and waits for pingProcess end
         re = process.readAllStandardOutput();
-        int newline = re.indexOf(QChar('\n'));
+        int newline = re.indexOf('\n');
         if (newline > 0) {
             re.truncate(newline);
         }
@@ -573,10 +574,10 @@ QUrl Utility::concatUrlPath(const QUrl &url, const QString &concatPath,
     QString path = url.path();
     if (!concatPath.isEmpty()) {
         // avoid '//'
-        if (path.endsWith('/') && concatPath.startsWith('/')) {
+        if (path.endsWith(QLatin1Char('/')) && concatPath.startsWith(QLatin1Char('/'))) {
             path.chop(1);
         } // avoid missing '/'
-        else if (!path.endsWith('/') && !concatPath.startsWith('/')) {
+        else if (!path.endsWith(QLatin1Char('/')) && !concatPath.startsWith(QLatin1Char('/'))) {
             path += QLatin1Char('/');
         }
         path += concatPath; // put the complete path together
@@ -593,9 +594,9 @@ QString Utility::makeConflictFileName(
 {
     QString conflictFileName(fn);
     // Add conflict tag before the extension.
-    int dotLocation = conflictFileName.lastIndexOf('.');
+    int dotLocation = conflictFileName.lastIndexOf(QLatin1Char('.'));
     // If no extension, add it at the end  (take care of cases like foo/.hidden or foo.bar/file)
-    if (dotLocation <= conflictFileName.lastIndexOf('/') + 1) {
+    if (dotLocation <= conflictFileName.lastIndexOf(QLatin1Char('/')) + 1) {
         dotLocation = conflictFileName.size();
     }
 
@@ -603,12 +604,10 @@ QString Utility::makeConflictFileName(
     if (!user.isEmpty()) {
         // Don't allow parens in the user name, to ensure
         // we can find the beginning and end of the conflict tag.
-        const auto userName = sanitizeForFileName(user).replace('(', '_').replace(')', '_');
-        conflictMarker.append(userName);
-        conflictMarker.append(' ');
+        const auto userName = sanitizeForFileName(user).replace(QLatin1Char('('), QLatin1Char('_')).replace(QLatin1Char(')'), QLatin1Char('_'));;
+        conflictMarker += userName + QLatin1Char(' ');
     }
-    conflictMarker.append(dt.toString("yyyy-MM-dd hhmmss"));
-    conflictMarker.append(')');
+    conflictMarker += dt.toString(QStringLiteral("yyyy-MM-dd hhmmss")) + QLatin1Char(')');
 
     conflictFileName.insert(dotLocation, conflictMarker);
     return conflictFileName;
@@ -636,7 +635,7 @@ bool Utility::isConflictFile(const char *name)
 
 bool Utility::isConflictFile(const QString &name)
 {
-    auto bname = name.midRef(name.lastIndexOf('/') + 1);
+    auto bname = name.midRef(name.lastIndexOf(QLatin1Char('/')) + 1);
 
     if (bname.contains(QStringLiteral("_conflict-")))
         return true;
index f2dc8ad68feaa61cdabae24a37e3cd33c170e90a..72b66875e5aa29cf6be5510b71bcdfcc342eeab8 100644 (file)
@@ -92,7 +92,7 @@ void setLaunchOnStartup_private(const QString &appName, const QString &guiName,
     QString runPath = QLatin1String(runPathC);
     QSettings settings(runPath, QSettings::NativeFormat);
     if (enable) {
-        settings.setValue(appName, QCoreApplication::applicationFilePath().replace('/', '\\'));
+        settings.setValue(appName, QCoreApplication::applicationFilePath().replace(QLatin1Char('/'), QLatin1Char('\\')));
     } else {
         settings.remove(appName);
     }
@@ -172,7 +172,7 @@ QVariant Utility::registryGetKeyValue(HKEY hRootKey, const QString &subKey, cons
                 // If the data has the REG_SZ, REG_MULTI_SZ or REG_EXPAND_SZ type, the string may not have been stored with
                 // the proper terminating null characters. Therefore, even if the function returns ERROR_SUCCESS,
                 // the application should ensure that the string is properly terminated before using it; otherwise, it may overwrite a buffer.
-                if (string.at(newCharSize - 1) == QChar('\0'))
+                if (string.at(newCharSize - 1) == QLatin1Char('\0'))
                     string.resize(newCharSize - 1);
                 value = string;
             }
index 45a00ef8b2d3cd714fb27be638d51bdf6e15c04d..e110795e4215ba3f48654ba42458bd87ee817156 100644 (file)
@@ -50,11 +50,11 @@ QString Vfs::modeToString(Mode mode)
 Optional<Vfs::Mode> Vfs::modeFromString(const QString &str)
 {
     // Note: Strings are used for config and must be stable
-    if (str == "off") {
+    if (str == QLatin1String("off")) {
         return Off;
-    } else if (str == "suffix") {
+    } else if (str == QLatin1String("suffix")) {
         return WithSuffix;
-    } else if (str == "wincfapi") {
+    } else if (str == QLatin1String("wincfapi")) {
         return WindowsCfApi;
     }
     return {};
@@ -116,9 +116,9 @@ VfsOff::~VfsOff() = default;
 static QString modeToPluginName(Vfs::Mode mode)
 {
     if (mode == Vfs::WithSuffix)
-        return "suffix";
+        return QStringLiteral("suffix");
     if (mode == Vfs::WindowsCfApi)
-        return "win";
+        return QStringLiteral("win");
     return QString();
 }
 
@@ -131,26 +131,26 @@ bool OCC::isVfsPluginAvailable(Vfs::Mode mode)
     auto name = modeToPluginName(mode);
     if (name.isEmpty())
         return false;
-    auto pluginPath = pluginFileName("vfs", name);
+    auto pluginPath = pluginFileName(QStringLiteral("vfs"), name);
     QPluginLoader loader(pluginPath);
 
     auto basemeta = loader.metaData();
-    if (basemeta.isEmpty() || !basemeta.contains("IID")) {
+    if (basemeta.isEmpty() || !basemeta.contains(QStringLiteral("IID"))) {
         qCDebug(lcPlugin) << "Plugin doesn't exist" << loader.fileName();
         return false;
     }
-    if (basemeta["IID"].toString() != "org.owncloud.PluginFactory") {
-        qCWarning(lcPlugin) << "Plugin has wrong IID" << loader.fileName() << basemeta["IID"];
+    if (basemeta[QStringLiteral("IID")].toString() != QLatin1String("org.owncloud.PluginFactory")) {
+        qCWarning(lcPlugin) << "Plugin has wrong IID" << loader.fileName() << basemeta[QStringLiteral("IID")];
         return false;
     }
 
-    auto metadata = basemeta["MetaData"].toObject();
-    if (metadata["type"].toString() != "vfs") {
-        qCWarning(lcPlugin) << "Plugin has wrong type" << loader.fileName() << metadata["type"];
+    auto metadata = basemeta[QStringLiteral("MetaData")].toObject();
+    if (metadata[QStringLiteral("type")].toString() != QLatin1String("vfs")) {
+        qCWarning(lcPlugin) << "Plugin has wrong type" << loader.fileName() << metadata[QStringLiteral("type")];
         return false;
     }
-    if (metadata["version"].toString() != MIRALL_VERSION_STRING) {
-        qCWarning(lcPlugin) << "Plugin has wrong version" << loader.fileName() << metadata["version"];
+    if (metadata[QStringLiteral("version")].toString() != QStringLiteral(MIRALL_VERSION_STRING)) {
+        qCWarning(lcPlugin) << "Plugin has wrong version" << loader.fileName() << metadata[QStringLiteral("version")];
         return false;
     }
 
@@ -182,7 +182,7 @@ std::unique_ptr<Vfs> OCC::createVfsFromPlugin(Vfs::Mode mode)
     auto name = modeToPluginName(mode);
     if (name.isEmpty())
         return nullptr;
-    auto pluginPath = pluginFileName("vfs", name);
+    auto pluginPath = pluginFileName(QStringLiteral("vfs"), name);
 
     if (!isVfsPluginAvailable(mode)) {
         qCCritical(lcPlugin) << "Could not load plugin: not existant or bad metadata" << pluginPath;
index 0fa5f3320469262dd173418b39917421d85dc22f..49197e72004b543109714be59ab9052a852b453c 100644 (file)
@@ -1,5 +1,10 @@
 project(libcsync)
 set(CMAKE_AUTOMOC TRUE)
+add_definitions(-DQT_NO_CAST_TO_ASCII
+                -DQT_NO_CAST_FROM_ASCII
+                -DQT_NO_URL_CAST_FROM_STRING
+                -DQT_NO_CAST_FROM_BYTEARRAY)
+
 # global needed variables
 set(APPLICATION_NAME "ocsync")
 
index 2b9c549c2251f6082feddf78bd8b9db0c18cd46b..390095f7690a2c8ddcf0a27c1820325cd165b92b 100644 (file)
@@ -96,16 +96,16 @@ OCSYNC_EXPORT bool csync_is_windows_reserved_word(const QStringRef &filename)
     size_t len_filename = filename.size();
 
     // Drive letters
-    if (len_filename == 2 && filename[1] == ':') {
-        if (filename[0] >= 'a' && filename[0] <= 'z') {
+    if (len_filename == 2 && filename.at(1) == QLatin1Char(':')) {
+        if (filename.at(0) >= QLatin1Char('a') && filename.at(0) <= QLatin1Char('z')) {
             return true;
         }
-        if (filename[0] >= 'A' && filename[0] <= 'Z') {
+        if (filename.at(0) >= QLatin1Char('A') && filename.at(0) <= QLatin1Char('Z')) {
             return true;
         }
     }
 
-    if (len_filename == 3 || (len_filename > 3 && filename[3] == '.')) {
+    if (len_filename == 3 || (len_filename > 3 && filename.at(3) == QLatin1Char('.'))) {
         for (const char *word : win_reserved_words_3) {
             if (filename.left(3).compare(QLatin1String(word), Qt::CaseInsensitive) == 0) {
                 return true;
@@ -113,7 +113,7 @@ OCSYNC_EXPORT bool csync_is_windows_reserved_word(const QStringRef &filename)
         }
     }
 
-    if (len_filename == 4 || (len_filename > 4 && filename[4] == '.')) {
+    if (len_filename == 4 || (len_filename > 4 && filename.at(4) == QLatin1Char('.'))) {
         for (const char *word : win_reserved_words_4) {
             if (filename.left(4).compare(QLatin1String(word), Qt::CaseInsensitive) == 0) {
                 return true;
@@ -137,14 +137,14 @@ static CSYNC_EXCLUDE_TYPE _csync_excluded_common(const QString &path, bool exclu
 
     /* split up the path */
     QStringRef bname(&path);
-    int lastSlash = path.lastIndexOf('/');
+    int lastSlash = path.lastIndexOf(QLatin1Char('/'));
     if (lastSlash >= 0) {
         bname = path.midRef(lastSlash + 1);
     }
 
     size_t blen = bname.size();
     // 9 = strlen(".sync_.db")
-    if (blen >= 9 && bname[0] == '.') {
+    if (blen >= 9 && bname.at(0) == QLatin1Char('.')) {
         if (bname.contains(QLatin1String(".db"))) {
             if (bname.startsWith(QLatin1String("._sync_"), Qt::CaseInsensitive)  // "._sync_*.db*"
                 || bname.startsWith(QLatin1String(".sync_"), Qt::CaseInsensitive) // ".sync_*.db*"
@@ -170,10 +170,10 @@ static CSYNC_EXCLUDE_TYPE _csync_excluded_common(const QString &path, bool exclu
     // as '.' is a separator that is not stored internally, so let's
     // not allow to sync those to avoid file loss/ambiguities (#416)
     if (blen > 1) {
-        if (bname[blen-1]== ' ') {
+        if (bname.at(blen - 1) == QLatin1Char(' ')) {
             match = CSYNC_FILE_EXCLUDE_TRAILING_SPACE;
             goto out;
-        } else if (bname[blen-1]== '.' ) {
+        } else if (bname.at(blen - 1) == QLatin1Char('.')) {
             match = CSYNC_FILE_EXCLUDE_INVALID_CHAR;
             goto out;
         }
@@ -226,7 +226,7 @@ static CSYNC_EXCLUDE_TYPE _csync_excluded_common(const QString &path, bool exclu
     return match;
 }
 
-static QString leftIncludeLast(const QString &arr, char c)
+static QString leftIncludeLast(const QString &arr, const QChar &c)
 {
     // left up to and including `c`
     return arr.left(arr.lastIndexOf(c, arr.size() - 2) + 1);
@@ -238,7 +238,7 @@ ExcludedFiles::ExcludedFiles(const QString &localPath)
     : _localPath(localPath)
     , _clientVersion(MIRALL_VERSION_MAJOR, MIRALL_VERSION_MINOR, MIRALL_VERSION_PATCH)
 {
-    Q_ASSERT(_localPath.endsWith("/"));
+    Q_ASSERT(_localPath.endsWith(QStringLiteral("/")));
     // Windows used to use PathMatchSpec which allows *foo to match abc/deffoo.
     _wildcardsMatchSlash = Utility::isWindows();
 
@@ -247,7 +247,7 @@ ExcludedFiles::ExcludedFiles(const QString &localPath)
         return;
 
     // Load exclude file from base dir
-    QFileInfo fi(_localPath + ".sync-exclude.lst");
+    QFileInfo fi(_localPath + QStringLiteral(".sync-exclude.lst"));
     if (fi.isReadable())
         addInTreeExcludeFilePath(fi.absoluteFilePath());
 }
@@ -261,7 +261,7 @@ void ExcludedFiles::addExcludeFilePath(const QString &path)
 
 void ExcludedFiles::addInTreeExcludeFilePath(const QString &path)
 {
-    BasePathString basePath = leftIncludeLast(path, '/');
+    BasePathString basePath = leftIncludeLast(path, QLatin1Char('/'));
     _excludeFiles[basePath].append(path);
 }
 
@@ -280,9 +280,9 @@ void ExcludedFiles::addManualExclude(const QString &expr, const QString &basePat
 #if defined(Q_OS_WIN)
     Q_ASSERT(basePath.size() >= 2 && basePath.at(1) == ':');
 #else
-    Q_ASSERT(basePath.startsWith('/'));
+    Q_ASSERT(basePath.startsWith(QLatin1Char('/')));
 #endif
-    Q_ASSERT(basePath.endsWith('/'));
+    Q_ASSERT(basePath.endsWith(QLatin1Char('/')));
 
     auto key = basePath;
     _manualExcludes[key].append(expr);
@@ -406,7 +406,7 @@ bool ExcludedFiles::isExcluded(
         // We do want to be able to sync with a hidden folder as the target.
         while (path.size() > basePath.size()) {
             QFileInfo fi(path);
-            if (fi.fileName() != ".sync-exclude.lst"
+            if (fi.fileName() != QStringLiteral(".sync-exclude.lst")
                 && (fi.isHidden() || fi.fileName().startsWith(QLatin1Char('.')))) {
                 return true;
             }
@@ -452,14 +452,14 @@ CSYNC_EXCLUDE_TYPE ExcludedFiles::traversalPatternMatch(const QString &path, Ite
     // Check the bname part of the path to see whether the full
     // regex should be run.
     QStringRef bnameStr(&path);
-    int lastSlash = path.lastIndexOf('/');
+    int lastSlash = path.lastIndexOf(QLatin1Char('/'));
     if (lastSlash >= 0) {
         bnameStr = path.midRef(lastSlash + 1);
     }
 
     QString basePath(_localPath + path);
     while (basePath.size() > _localPath.size()) {
-        basePath = leftIncludeLast(basePath, '/');
+        basePath = leftIncludeLast(basePath, QLatin1Char('/'));
         QRegularExpressionMatch m;
         if (filetype == ItemTypeDirectory
             && _bnameTraversalRegexDir.contains(basePath)) {
@@ -483,7 +483,7 @@ CSYNC_EXCLUDE_TYPE ExcludedFiles::traversalPatternMatch(const QString &path, Ite
     // third capture: full path matching is triggered
     basePath = _localPath + path;
     while (basePath.size() > _localPath.size()) {
-        basePath = leftIncludeLast(basePath, '/');
+        basePath = leftIncludeLast(basePath, QLatin1Char('/'));
         QRegularExpressionMatch m;
         if (filetype == ItemTypeDirectory
             && _fullTraversalRegexDir.contains(basePath)) {
@@ -517,12 +517,12 @@ CSYNC_EXCLUDE_TYPE ExcludedFiles::fullPatternMatch(const QString &p, ItemType fi
     // `path` seems to always be relative to `_localPath`, the tests however have not been
     // written that way... this makes the tests happy for now. TODO Fix the tests at some point
     QString path = p;
-    if (path[0] == '/')
+    if (path[0] == QLatin1Char('/'))
         path = path.mid(1);
 
     QString basePath(_localPath + path);
     while (basePath.size() > _localPath.size()) {
-        basePath = leftIncludeLast(basePath, '/');
+        basePath = leftIncludeLast(basePath, QLatin1Char('/'));
         QRegularExpressionMatch m;
         if (filetype == ItemTypeDirectory
             && _fullRegexDir.contains(basePath)) {
@@ -576,17 +576,17 @@ QString ExcludedFiles::convertToRegexpSyntax(QString exclude, bool wildcardsMatc
         case '*':
             flush();
             if (wildcardsMatchSlash) {
-                regex.append(".*");
+                regex.append(QLatin1String(".*"));
             } else {
-                regex.append("[^/]*");
+                regex.append(QLatin1String("[^/]*"));
             }
             break;
         case '?':
             flush();
             if (wildcardsMatchSlash) {
-                regex.append(".");
+                regex.append(QLatin1Char('.'));
             } else {
-                regex.append("[^/]");
+                regex.append(QStringLiteral("[^/]"));
             }
             break;
         case '[': {
@@ -594,19 +594,19 @@ QString ExcludedFiles::convertToRegexpSyntax(QString exclude, bool wildcardsMatc
             // Find the end of the bracket expression
             auto j = i + 1;
             for (; j < len; ++j) {
-                if (exclude[j] == ']')
+                if (exclude[j] == QLatin1Char(']'))
                     break;
-                if (j != len - 1 && exclude[j] == '\\' && exclude[j + 1] == ']')
+                if (j != len - 1 && exclude[j] == QLatin1Char('\\') && exclude[j + 1] == QLatin1Char(']'))
                     ++j;
             }
             if (j == len) {
                 // no matching ], just insert the escaped [
-                regex.append("\\[");
+                regex.append(QStringLiteral("\\["));
                 break;
             }
             // Translate [! to [^
             QString bracketExpr = exclude.mid(i, j - i + 1);
-            if (bracketExpr.startsWith("[!"))
+            if (bracketExpr.startsWith(QLatin1String("[!")))
                 bracketExpr[1] = '^';
             regex.append(bracketExpr);
             i = j;
@@ -615,7 +615,7 @@ QString ExcludedFiles::convertToRegexpSyntax(QString exclude, bool wildcardsMatc
         case '\\':
             flush();
             if (i == len - 1) {
-                regex.append("\\\\");
+                regex.append(QStringLiteral("\\\\"));
                 break;
             }
             // '\*' -> '\*', but '\z' -> '\\z'
@@ -645,7 +645,7 @@ QString ExcludedFiles::extractBnameTrigger(const QString &exclude, bool wildcard
 {
     // We can definitely drop everything to the left of a / - that will never match
     // any bname.
-    QString pattern = exclude.mid(exclude.lastIndexOf('/') + 1);
+    QString pattern = exclude.mid(exclude.lastIndexOf(QLatin1Char('/')) + 1);
 
     // Easy case, nothing else can match a slash, so that's it.
     if (!wildcardsMatchSlash)
@@ -672,7 +672,7 @@ QString ExcludedFiles::extractBnameTrigger(const QString &exclude, bool wildcard
 
     // And if there was a wildcard, it starts with a *
     if (i >= 0)
-        pattern.prepend('*');
+        pattern.prepend(QLatin1Char('*'));
 
     return pattern;
 }
@@ -733,25 +733,25 @@ void ExcludedFiles::prepare(const BasePathString & basePath)
     auto regexAppend = [](QString &fileDirPattern, QString &dirPattern, const QString &appendMe, bool dirOnly) {
         QString &pattern = dirOnly ? dirPattern : fileDirPattern;
         if (!pattern.isEmpty())
-            pattern.append("|");
+            pattern.append(QLatin1Char('|'));
         pattern.append(appendMe);
     };
 
     for (auto exclude : _allExcludes.value(basePath)) {
-        if (exclude[0] == '\n')
+        if (exclude[0] == QLatin1Char('\n'))
             continue; // empty line
-        if (exclude[0] == '\r')
+        if (exclude[0] == QLatin1Char('\r'))
             continue; // empty line
 
-        bool matchDirOnly = exclude.endsWith('/');
+        bool matchDirOnly = exclude.endsWith(QLatin1Char('/'));
         if (matchDirOnly)
             exclude = exclude.left(exclude.size() - 1);
 
-        bool removeExcluded = (exclude[0] == ']');
+        bool removeExcluded = (exclude[0] == QLatin1Char(']'));
         if (removeExcluded)
             exclude = exclude.mid(1);
 
-        bool fullPath = exclude.contains('/');
+        bool fullPath = exclude.contains(QLatin1Char('/'));
 
         /* Use QRegularExpression, append to the right pattern */
         auto &bnameFileDir = removeExcluded ? bnameFileDirRemove : bnameFileDirKeep;
@@ -784,7 +784,7 @@ void ExcludedFiles::prepare(const BasePathString & basePath)
     // The empty pattern would match everything - change it to match-nothing
     auto emptyMatchNothing = [](QString &pattern) {
         if (pattern.isEmpty())
-            pattern = "a^";
+            pattern = QStringLiteral("a^");
     };
     emptyMatchNothing(fullFileDirKeep);
     emptyMatchNothing(fullFileDirRemove);
@@ -805,58 +805,58 @@ void ExcludedFiles::prepare(const BasePathString & basePath)
     // If the third group matches, the fullActivatedRegex needs to be applied
     // to the full path.
     _bnameTraversalRegexFile[basePath].setPattern(
-        "^(?P<exclude>" + bnameFileDirKeep + ")$|"
-        + "^(?P<excluderemove>" + bnameFileDirRemove + ")$|"
-        + "^(?P<trigger>" + bnameTriggerFileDir + ")$");
+        QStringLiteral("^(?P<exclude>%1)$|"
+                       "^(?P<excluderemove>%2)$|"
+                       "^(?P<trigger>%3)$")
+            .arg(bnameFileDirKeep, bnameFileDirRemove, bnameTriggerFileDir));
     _bnameTraversalRegexDir[basePath].setPattern(
-        "^(?P<exclude>" + bnameFileDirKeep + "|" + bnameDirKeep + ")$|"
-        + "^(?P<excluderemove>" + bnameFileDirRemove + "|" + bnameDirRemove + ")$|"
-        + "^(?P<trigger>" + bnameTriggerFileDir + "|" + bnameTriggerDir + ")$");
+        QStringLiteral("^(?P<exclude>%1|%2)$|"
+                       "^(?P<excluderemove>%3|%4)$|"
+                       "^(?P<trigger>%5|%6)$")
+            .arg(bnameFileDirKeep, bnameDirKeep, bnameFileDirRemove, bnameDirRemove, bnameTriggerFileDir, bnameTriggerDir));
 
     // The full traveral regex is applied to the full path if the trigger capture of
     // the bname regex matches. Its basic form is (exclude)|(excluderemove)".
     // This pattern can be much simpler than fullRegex since we can assume a traversal
     // situation and doesn't need to look for bname patterns in parent paths.
     _fullTraversalRegexFile[basePath].setPattern(
-        QLatin1String("")
         // Full patterns are anchored to the beginning
-        + "^(?P<exclude>" + fullFileDirKeep + ")(?:$|/)"
-        + "|"
-        + "^(?P<excluderemove>" + fullFileDirRemove + ")(?:$|/)");
+        QStringLiteral("^(?P<exclude>%1)(?:$|/)"
+                       "|"
+                       "^(?P<excluderemove>%2)(?:$|/)")
+            .arg(fullFileDirKeep, fullFileDirRemove));
     _fullTraversalRegexDir[basePath].setPattern(
-        QLatin1String("")
-        + "^(?P<exclude>" + fullFileDirKeep + "|" + fullDirKeep + ")(?:$|/)"
-        + "|"
-        + "^(?P<excluderemove>" + fullFileDirRemove + "|" + fullDirRemove + ")(?:$|/)");
+        QStringLiteral("^(?P<exclude>%1|%2)(?:$|/)"
+                       "|"
+                       "^(?P<excluderemove>%3|%4)(?:$|/)")
+            .arg(fullFileDirKeep, fullDirKeep, fullFileDirRemove, fullDirRemove));
 
     // The full regex is applied to the full path and incorporates both bname and
     // full-path patterns. It has the form "(exclude)|(excluderemove)".
     _fullRegexFile[basePath].setPattern(
-        QLatin1String("(?P<exclude>")
-        // Full patterns are anchored to the beginning
-        + "^(?:" + fullFileDirKeep + ")(?:$|/)" + "|"
-        // Simple bname patterns can be any path component
-        + "(?:^|/)(?:" + bnameFileDirKeep + ")(?:$|/)" + "|"
-        // When checking a file for exclusion we must check all parent paths
-        // against the dir-only patterns as well.
-        + "(?:^|/)(?:" + bnameDirKeep + ")/"
-        + ")"
-        + "|"
-        + "(?P<excluderemove>"
-        + "^(?:" + fullFileDirRemove + ")(?:$|/)" + "|"
-        + "(?:^|/)(?:" + bnameFileDirRemove + ")(?:$|/)" + "|"
-        + "(?:^|/)(?:" + bnameDirRemove + ")/"
-        + ")");
+        QStringLiteral("(?P<exclude>"
+                       // Full patterns are anchored to the beginning
+                       "^(?:%1)(?:$|/)|"
+                       // Simple bname patterns can be any path component
+                       "(?:^|/)(?:%2)(?:$|/)|"
+                       // When checking a file for exclusion we must check all parent paths
+                       // against the dir-only patterns as well.
+                       "(?:^|/)(?:%3)/)"
+                       "|"
+                       "(?P<excluderemove>"
+                       "^(?:%4)(?:$|/)|"
+                       "(?:^|/)(?:%5)(?:$|/)|"
+                       "(?:^|/)(?:%6)/)")
+            .arg(fullFileDirKeep, bnameFileDirKeep, bnameDirKeep, fullFileDirRemove, bnameFileDirRemove, bnameDirRemove));
     _fullRegexDir[basePath].setPattern(
-        QLatin1String("(?P<exclude>")
-        + "^(?:" + fullFileDirKeep + "|" + fullDirKeep + ")(?:$|/)" + "|"
-        + "(?:^|/)(?:" + bnameFileDirKeep + "|" + bnameDirKeep + ")(?:$|/)"
-        + ")"
-        + "|"
-        + "(?P<excluderemove>"
-        + "^(?:" + fullFileDirRemove + "|" + fullDirRemove + ")(?:$|/)" + "|"
-        + "(?:^|/)(?:" + bnameFileDirRemove + "|" + bnameDirRemove + ")(?:$|/)"
-        + ")");
+        QStringLiteral("(?P<exclude>"
+                       "^(?:%1|%2)(?:$|/)|"
+                       "(?:^|/)(?:%3|%4)(?:$|/))"
+                       "|"
+                       "(?P<excluderemove>"
+                       "^(?:%5|%6)(?:$|/)|"
+                       "(?:^|/)(?:%7|%8)(?:$|/))")
+            .arg(fullFileDirKeep, fullDirKeep, bnameFileDirKeep, bnameDirKeep, fullFileDirRemove, fullDirRemove, bnameFileDirRemove, bnameDirRemove));
 
     QRegularExpression::PatternOptions patternOptions = QRegularExpression::NoPatternOption;
     if (OCC::Utility::fsCasePreserving())
index d06c5e107d35956531552daeb93de3c943d23694..7d41a33266ae9af93924dc0caedfdef85c67924a 100644 (file)
@@ -185,13 +185,13 @@ private:
         BasePathString(QString &&other)
             : QString(std::move(other))
         {
-            Q_ASSERT(endsWith('/'));
+            Q_ASSERT(endsWith(QLatin1Char('/')));
         }
 
         BasePathString(const QString &other)
             : QString(other)
         {
-            Q_ASSERT(endsWith('/'));
+            Q_ASSERT(endsWith(QLatin1Char('/')));
         }
     };
 
index 9f035422b7612cc05da8efcd29ebd39f50a8caef..d83c946733fd585c9646e72fcf95192f42ab0c71 100644 (file)
@@ -56,7 +56,7 @@ csync_vio_handle_t *csync_vio_local_opendir(const QString &name) {
 
     auto dirname = QFile::encodeName(name);
 
-    handle->dh = _topendir( dirname );
+    handle->dh = _topendir(dirname.constData());
     if (!handle->dh) {
         return nullptr;
     }
index 354aea0f3491cd25c287307b1c3ab73715be51a6..ac0eb95e771d9f9e39dc0d3962ed7d4ba76aa936 100644 (file)
@@ -137,7 +137,7 @@ std::unique_ptr<csync_file_stat_t> csync_vio_local_readdir(csync_vio_handle_t *h
       }
   }
   auto path = QString::fromWCharArray(handle->ffd.cFileName);
-  if (path == "." || path == "..")
+  if (path == QLatin1String(".") || path == QLatin1String(".."))
       return csync_vio_local_readdir(handle, vfs);
 
   file_stat = std::make_unique<csync_file_stat_t>();
index 8881ace39221316b53962420dc106780147c48db..98ac0fa2244cb1199fd1999c1df24baf82fc42be 100644 (file)
@@ -32,56 +32,56 @@ static void check_long_win_path(void **state)
     (void) state; /* unused */
 
     {
-        const char *path = "C://DATA/FILES/MUSIC/MY_MUSIC.mp3"; // check a short path
-        const char *exp_path = R"(\\?\C:\\DATA\FILES\MUSIC\MY_MUSIC.mp3)";
-        QByteArray new_short = OCC::FileSystem::pathtoUNC(QByteArray::fromRawData(path, strlen(path)));
-        assert_string_equal(new_short, exp_path);
+        const auto path = QStringLiteral("C://DATA/FILES/MUSIC/MY_MUSIC.mp3"); // check a short path
+        const auto exp_path = QStringLiteral(R"(\\?\C:\\DATA\FILES\MUSIC\MY_MUSIC.mp3)");
+        QString new_short = OCC::FileSystem::pathtoUNC(path);
+        assert_string_equal(new_short.constData(), exp_path.constData());
     }
 
     {
-        const char *path = R"(\\foo\bar/MY_MUSIC.mp3)";
-        const char *exp_path = R"(\\foo\bar\MY_MUSIC.mp3)";
-        QByteArray new_short = OCC::FileSystem::pathtoUNC(QByteArray::fromRawData(path, strlen(path)));
-        assert_string_equal(new_short, exp_path);
+        const auto path = QStringLiteral(R"(\\foo\bar/MY_MUSIC.mp3)");
+        const auto exp_path = QStringLiteral(R"(\\foo\bar\MY_MUSIC.mp3)");
+        QString new_short = OCC::FileSystem::pathtoUNC(path);
+        assert_string_equal(new_short.constData(), exp_path.constData());
     }
 
     {
-        const char *path = R"(//foo\bar/MY_MUSIC.mp3)";
-        const char *exp_path = R"(\\foo\bar\MY_MUSIC.mp3)";
-        QByteArray new_short = OCC::FileSystem::pathtoUNC(QByteArray::fromRawData(path, strlen(path)));
-        assert_string_equal(new_short, exp_path);
+        const auto path = QStringLiteral(R"(//foo\bar/MY_MUSIC.mp3)");
+        const auto exp_path = QStringLiteral(R"(\\foo\bar\MY_MUSIC.mp3)");
+        QString new_short = OCC::FileSystem::pathtoUNC(path);
+        assert_string_equal(new_short.constData(), exp_path.constData());
     }
 
     {
-        const char *path = "\\foo\\bar";
-        const char *exp_path = R"(\\?\foo\bar)";
-        QByteArray new_short = OCC::FileSystem::pathtoUNC(QByteArray::fromRawData(path, strlen(path)));
-        assert_string_equal(new_short, exp_path);
+        const auto path = QStringLiteral(R"(\foo\bar)");
+        const auto exp_path = QStringLiteral(R"(\\?\foo\bar)");
+        QString new_short = OCC::FileSystem::pathtoUNC(path);
+        assert_string_equal(new_short.constData(), exp_path.constData());
     }
 
     {
-        const char *path = "/foo/bar";
-        const char *exp_path = R"(\\?\foo\bar)";
-        QByteArray new_short = OCC::FileSystem::pathtoUNC(QByteArray::fromRawData(path, strlen(path)));
-        assert_string_equal(new_short, exp_path);
+        const auto path = QStringLiteral("/foo/bar");
+        const auto exp_path = QStringLiteral(R"(\\?\foo\bar)");
+        QString new_short = OCC::FileSystem::pathtoUNC(path);
+        assert_string_equal(new_short.constData(), exp_path.constData());
     }
 
-    const char *longPath = "D://alonglonglonglong/blonglonglonglong/clonglonglonglong/dlonglonglonglong/"
-            "elonglonglonglong/flonglonglonglong/glonglonglonglong/hlonglonglonglong/ilonglonglonglong/"
-            "jlonglonglonglong/klonglonglonglong/llonglonglonglong/mlonglonglonglong/nlonglonglonglong/"
-            "olonglonglonglong/file.txt";
-    const char *longPathConv = R"(\\?\D:\\alonglonglonglong\blonglonglonglong\clonglonglonglong\dlonglonglonglong\)"
-            R"(elonglonglonglong\flonglonglonglong\glonglonglonglong\hlonglonglonglong\ilonglonglonglong\)"
-            R"(jlonglonglonglong\klonglonglonglong\llonglonglonglong\mlonglonglonglong\nlonglonglonglong\)"
-            R"(olonglonglonglong\file.txt)";
+    const auto longPath = QStringLiteral("D://alonglonglonglong/blonglonglonglong/clonglonglonglong/dlonglonglonglong/"
+                                         "elonglonglonglong/flonglonglonglong/glonglonglonglong/hlonglonglonglong/ilonglonglonglong/"
+                                         "jlonglonglonglong/klonglonglonglong/llonglonglonglong/mlonglonglonglong/nlonglonglonglong/"
+                                         "olonglonglonglong/file.txt");
+    const auto longPathConv = QStringLiteral(R"(\\?\D:\\alonglonglonglong\blonglonglonglong\clonglonglonglong\dlonglonglonglong\)"
+                                             R"(elonglonglonglong\flonglonglonglong\glonglonglonglong\hlonglonglonglong\ilonglonglonglong\)"
+                                             R"(jlonglonglonglong\klonglonglonglong\llonglonglonglong\mlonglonglonglong\nlonglonglonglong\)"
+                                             R"(olonglonglonglong\file.txt)");
 
-    QByteArray new_long = OCC::FileSystem::pathtoUNC(QByteArray::fromRawData(longPath, strlen(longPath)));
-    // printf("XXXXXXXXXXXX %s %d\n", new_long, mem_reserved);
+    QString new_long = OCC::FileSystem::pathtoUNC(longPath);
+    // printf( "XXXXXXXXXXXX %s %d\n", new_long, mem_reserved);
 
-    assert_string_equal(new_long, longPathConv);
+    assert_string_equal(new_long.constData(), longPathConv.constData());
 
-    // printf("YYYYYYYYYYYY %ld\n", strlen(new_long));
-    assert_int_equal(strlen(new_long), 286);
+    // printf( "YYYYYYYYYYYY %ld\n", strlen(new_long));
+    assert_int_equal(new_long.length(), 286);
 }
 
 int torture_run_tests(void)
index 52db78f6e408b7f88f02bb9d2bba215fd2e5c306..2097989885f81de6db38c1f5f0db199104b33603 100644 (file)
@@ -111,7 +111,7 @@ static int teardown(void **state) {
 static void create_dirs( const char *path )
 {
   int rc;
-  auto _mypath = QStringLiteral("%1/%2").arg(CSYNC_TEST_DIR, path).toUtf8();
+  auto _mypath = QStringLiteral("%1/%2").arg(CSYNC_TEST_DIR, QString::fromUtf8(path)).toUtf8();
   char *mypath = _mypath.data();
 
   char *p = mypath + CSYNC_TEST_DIR.size() + 1; /* start behind the offset */
@@ -188,9 +188,9 @@ static void traverse_dir(void **state, const QString &dir, int *cnt)
         } else {
             *cnt = *cnt +1;
         }
-        output(subdir_out);
+        output(subdir_out.constData());
         if( is_dir ) {
-          traverse_dir( state, subdir, cnt);
+            traverse_dir(state, QString::fromUtf8(subdir), cnt);
         }
     }
 
@@ -201,9 +201,9 @@ static void traverse_dir(void **state, const QString &dir, int *cnt)
 
 static void create_file( const char *path, const char *name, const char *content)
 {
-   QFile file(QStringLiteral("%1/%2%3").arg(CSYNC_TEST_DIR, path, name));
-   assert_int_equal(1, file.open(QIODevice::WriteOnly | QIODevice::NewOnly));
-   file.write(content);
+    QFile file(QStringLiteral("%1/%2%3").arg(CSYNC_TEST_DIR, QString::fromUtf8(path), QString::fromUtf8(name)));
+    assert_int_equal(1, file.open(QIODevice::WriteOnly | QIODevice::NewOnly));
+    file.write(content);
 }
 
 static void check_readdir_shorttree(void **state)
@@ -216,12 +216,15 @@ static void check_readdir_shorttree(void **state)
     
     traverse_dir(state, CSYNC_TEST_DIR, &files_cnt);
 
-    assert_string_equal( sv->result,
-                         QString::fromUtf8("<DIR> %1/alibaba"
-                                        "<DIR> %1/alibaba/und"
-                                        "<DIR> %1/alibaba/und/die"
-                                        "<DIR> %1/alibaba/und/die/vierzig"
-                                        "<DIR> %1/alibaba/und/die/vierzig/räuber").arg(CSYNC_TEST_DIR).toUtf8().constData() );
+    assert_string_equal(sv->result.constData(),
+        QString::fromUtf8("<DIR> %1/alibaba"
+                          "<DIR> %1/alibaba/und"
+                          "<DIR> %1/alibaba/und/die"
+                          "<DIR> %1/alibaba/und/die/vierzig"
+                          "<DIR> %1/alibaba/und/die/vierzig/räuber")
+            .arg(CSYNC_TEST_DIR)
+            .toUtf8()
+            .constData());
     assert_int_equal(files_cnt, 0);
 }
 
@@ -239,11 +242,14 @@ static void check_readdir_with_content(void **state)
 
     traverse_dir(state, CSYNC_TEST_DIR, &files_cnt);
 
-    assert_string_equal( sv->result,
-                         QString::fromUtf8("<DIR> %1/warum"
-                         "<DIR> %1/warum/nur"
-                         "<DIR> %1/warum/nur/40"
-                         "<DIR> %1/warum/nur/40/Räuber").arg(CSYNC_TEST_DIR).toUtf8().constData());
+    assert_string_equal(sv->result.constData(),
+        QString::fromUtf8("<DIR> %1/warum"
+                          "<DIR> %1/warum/nur"
+                          "<DIR> %1/warum/nur/40"
+                          "<DIR> %1/warum/nur/40/Räuber")
+            .arg(CSYNC_TEST_DIR)
+            .toUtf8()
+            .constData());
     /*                   "      %1/warum/nur/40/Räuber/Räuber Max.txt"
                          "      %1/warum/nur/40/Räuber/пя́тница.txt"; */
     assert_int_equal(files_cnt, 2); /* Two files in the sub dir */
@@ -315,9 +321,7 @@ static void check_readdir_longtree(void **state)
     traverse_dir(state, CSYNC_TEST_DIR, &files_cnt);
     assert_int_equal(files_cnt, 0);
     /* and compare. */
-    assert_string_equal( sv->result, result);
-
-
+    assert_string_equal(sv->result.constData(), result.constData());
 }
 
 // https://github.com/owncloud/client/issues/3128 https://github.com/owncloud/client/issues/2777
@@ -329,11 +333,11 @@ static void check_readdir_bigunicode(void **state)
 //    3: ? ASCII: 191 - BF
 //    4: ASCII: 32    - 20
 
-    QString p = QStringLiteral("%1/%2").arg(CSYNC_TEST_DIR, "goodone/" );
+    QString p = QStringLiteral("%1/%2").arg(CSYNC_TEST_DIR, QStringLiteral("goodone/"));
     int rc = oc_mkdir(p);
     assert_int_equal(rc, 0);
 
-    p = QStringLiteral("%1/%2").arg(CSYNC_TEST_DIR, "goodone/ugly\xEF\xBB\xBF\x32" ".txt" ); // file with encoding error
+    p = QStringLiteral("%1/goodone/ugly\xEF\xBB\xBF\x32.txt").arg(CSYNC_TEST_DIR); // file with encoding error
 
     rc = oc_mkdir(p);
 
@@ -341,10 +345,10 @@ static void check_readdir_bigunicode(void **state)
 
     int files_cnt = 0;
     traverse_dir(state, CSYNC_TEST_DIR, &files_cnt);
-    const auto expected_result =  QString::fromUtf8("<DIR> %1/goodone"
-                                   "<DIR> %1/goodone/ugly\xEF\xBB\xBF\x32" ".txt").arg(CSYNC_TEST_DIR)
-                                   ;
-    assert_string_equal( sv->result, expected_result.toUtf8().constData());
+    const auto expected_result = QStringLiteral("<DIR> %1/goodone"
+                                                "<DIR> %1/goodone/ugly\xEF\xBB\xBF\x32.txt")
+                                     .arg(CSYNC_TEST_DIR);
+    assert_string_equal(sv->result.constData(), expected_result.toUtf8().constData());
 
     assert_int_equal(files_cnt, 0);
 }