// 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;
}
{
// 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];
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");
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++;
}
// 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
}
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
bool FileSystem::isLnkFile(const QString &filename)
{
- return filename.endsWith(".lnk");
+ return filename.endsWith(QLatin1String(".lnk"));
}
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
* - 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);
}
/** @} */
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;
}
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;
return _errId;
}
-QString SqlQuery::lastQuery() const
+const QByteArray &SqlQuery::lastQuery() const
{
return _sql;
}
bindValueInternal(pos, value);
}
- QString lastQuery() const;
+ const QByteArray &lastQuery() const;
int numRowsAffected();
void reset_and_clear_bindings();
void finish();
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);
}
}
return result;
}
-QByteArray RemotePermissions::toString() const
+QString RemotePermissions::toString() const
{
- return toDbValue();
+ return QString::fromUtf8(toDbValue());
}
RemotePermissions RemotePermissions::fromDbValue(const QByteArray &value)
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 &);
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) {
// 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";
}
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));
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
}
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;
}
{
if (_transaction == 0) {
if (!_db.transaction()) {
- qCWarning(lcDb) << "ERROR starting transaction: " << _db.error();
+ qCWarning(lcDb) << "ERROR starting transaction:" << _db.error();
return;
}
_transaction = 1;
{
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;
// 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;
}
}
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);
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);
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);
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;
}
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,
return checkConnect();
}
- return sqlFail("Create table metadata", createQuery);
+ return sqlFail(QStringLiteral("Create table metadata"), createQuery);
}
createQuery.prepare("CREATE TABLE IF NOT EXISTS downloadinfo("
");");
if (!createQuery.exec()) {
- return sqlFail("Create table downloadinfo", createQuery);
+ return sqlFail(QStringLiteral("Create table downloadinfo"), createQuery);
}
createQuery.prepare("CREATE TABLE IF NOT EXISTS uploadinfo("
");");
if (!createQuery.exec()) {
- return sqlFail("Create table uploadinfo", createQuery);
+ return sqlFail(QStringLiteral("Create table uploadinfo"), createQuery);
}
// create the blacklist table.
");");
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("
"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.
");");
if (!createQuery.exec()) {
- return sqlFail("Create table selectivesync", createQuery);
+ return sqlFail(QStringLiteral("Create table selectivesync"), createQuery);
}
// create the checksumtype table.
"name TEXT UNIQUE"
");");
if (!createQuery.exec()) {
- return sqlFail("Create table version", createQuery);
+ return sqlFail(QStringLiteral("Create table version"), createQuery);
}
// create the datafingerprint table.
"fingerprint TEXT UNIQUE"
");");
if (!createQuery.exec()) {
- return sqlFail("Create table datafingerprint", createQuery);
+ return sqlFail(QStringLiteral("Create table datafingerprint"), createQuery);
}
// create the flags table.
"pinState INTEGER"
");");
if (!createQuery.exec()) {
- return sqlFail("Create table flags", createQuery);
+ return sqlFail(QStringLiteral("Create table flags"), createQuery);
}
// create the conflicts table.
"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("
"custom VARCHAR(256)"
");");
if (!createQuery.exec()) {
- return sqlFail("Create table version", createQuery);
+ return sqlFail(QStringLiteral("Create table version"), createQuery);
}
bool forceRemoteDiscovery = false;
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 {
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) {
}
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 "
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.
// 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;
}
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");
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");
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;
}
}
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;
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;
}
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;
}
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);
}
}
+// TODO: filename -> QBytearray?
bool SyncJournalDb::deleteFileRecord(const QString &filename, bool recursively)
{
QMutexLocker locker(&_mutex);
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;
}
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);
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();
}
}
- if (!deleteBatch(_deleteDownloadInfoQuery, superfluousPaths, "downloadinfo"))
+ if (!deleteBatch(_deleteDownloadInfoQuery, superfluousPaths, QStringLiteral("downloadinfo")))
return empty_result;
return deleted_entries;
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);
}
}
- deleteBatch(_deleteUploadInfoQuery, superfluousPaths, "uploadinfo");
+ deleteBatch(_deleteUploadInfoQuery, superfluousPaths, QStringLiteral("uploadinfo"));
return ids;
}
SqlQuery delQuery(_db);
delQuery.prepare("DELETE FROM blacklist WHERE path = ?");
- return deleteBatch(delQuery, superfluousPaths, "blacklist");
+ return deleteBatch(delQuery, superfluousPaths, QStringLiteral("blacklist"));
}
void SyncJournalDb::deleteStaleFlagsEntries()
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);
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();
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);
}
}
}
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);
}
}
}
{
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;
}
}
- commitInternal("setSelectiveSyncList");
+ commitInternal(QStringLiteral("setSelectiveSyncList"));
}
void SyncJournalDb::avoidRenamesOnNextSync(const QByteArray &path)
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) {
QString fp = QString::fromLatin1(hash.trimmed());
if (colonSeparated) {
- fp.replace(QChar(' '), QChar(':'));
+ fp.replace(QLatin1Char(' '), QLatin1Char(':'));
}
return fp;
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()
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;
{
if (isMac()) {
QString n(fName);
- return n.replace(QChar(':'), QChar('/'));
+ return n.replace(QLatin1Char(':'), QLatin1Char('/'));
}
return fName;
}
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);
}
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
{
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();
}
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;
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;
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);
}
// 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;
}
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 {};
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();
}
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;
}
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;
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")
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;
}
}
- 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;
/* 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*"
// 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;
}
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);
: _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();
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());
}
void ExcludedFiles::addInTreeExcludeFilePath(const QString &path)
{
- BasePathString basePath = leftIncludeLast(path, '/');
+ BasePathString basePath = leftIncludeLast(path, QLatin1Char('/'));
_excludeFiles[basePath].append(path);
}
#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);
// 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;
}
// 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)) {
// 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)) {
// `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)) {
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 '[': {
// 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;
case '\\':
flush();
if (i == len - 1) {
- regex.append("\\\\");
+ regex.append(QStringLiteral("\\\\"));
break;
}
// '\*' -> '\*', but '\z' -> '\\z'
{
// 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)
// And if there was a wildcard, it starts with a *
if (i >= 0)
- pattern.prepend('*');
+ pattern.prepend(QLatin1Char('*'));
return pattern;
}
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;
// 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);
// 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())
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('/')));
}
};
auto dirname = QFile::encodeName(name);
- handle->dh = _topendir( dirname );
+ handle->dh = _topendir(dirname.constData());
if (!handle->dh) {
return nullptr;
}
}
}
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>();
(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)
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 */
} 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);
}
}
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)
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);
}
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 */
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
// 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);
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);
}