Replace a few make_unexpected with ResultError

Change-Id: I64637b8b43c1932dee59e37b8922c18d27c2deb9
Reviewed-by: Jarek Kobus <jaroslaw.kobus@qt.io>
This commit is contained in:
hjk
2025-04-15 10:23:32 +02:00
parent 8f54275827
commit ae0e846eab
32 changed files with 174 additions and 176 deletions

View File

@@ -1195,7 +1195,7 @@ Result<QString> DockManager::createWorkspace(const QString &workspaceName)
Result<> result = write(filePath, saveState(workspaceName)); // TODO utils Result<> result = write(filePath, saveState(workspaceName)); // TODO utils
if (!result) if (!result)
return make_unexpected(result.error()); return ResultError(result.error());
Workspace workspace(filePath, false); Workspace workspace(filePath, false);
@@ -1210,7 +1210,7 @@ Result<> DockManager::openWorkspace(const QString &fileName)
Workspace *wrk = workspace(fileName); Workspace *wrk = workspace(fileName);
if (!wrk) if (!wrk)
return make_unexpected(Tr::tr("Workspace \"%1\" does not exist.").arg(fileName)); return ResultError(Tr::tr("Workspace \"%1\" does not exist.").arg(fileName));
// Do nothing if workspace is already loaded, exception if it is a preset workspace. In this // Do nothing if workspace is already loaded, exception if it is a preset workspace. In this
// case we still want to be able to load the default workspace to undo potential user changes. // case we still want to be able to load the default workspace to undo potential user changes.
@@ -1228,12 +1228,12 @@ Result<> DockManager::openWorkspace(const QString &fileName)
// Try loading the file // Try loading the file
const Result<QByteArray> data = loadWorkspace(*wrk); const Result<QByteArray> data = loadWorkspace(*wrk);
if (!data) if (!data)
return make_unexpected(data.error()); return ResultError(data.error());
emit openingWorkspace(wrk->fileName()); emit openingWorkspace(wrk->fileName());
// If data was loaded from file try to restore its state // If data was loaded from file try to restore its state
if (!data->isNull() && !restoreState(*data)) if (!data->isNull() && !restoreState(*data))
return make_unexpected(Tr::tr("Cannot restore \"%1\".").arg(wrk->filePath().toUserOutput())); return ResultError(Tr::tr("Cannot restore \"%1\".").arg(wrk->filePath().toUserOutput()));
d->m_workspace = *wrk; d->m_workspace = *wrk;
emit workspaceLoaded(wrk->fileName()); emit workspaceLoaded(wrk->fileName());
@@ -1248,16 +1248,16 @@ Result<> DockManager::reloadActiveWorkspace()
Workspace *wrk = activeWorkspace(); Workspace *wrk = activeWorkspace();
if (!workspaces().contains(*wrk)) if (!workspaces().contains(*wrk))
return make_unexpected( return ResultError(
Tr::tr("Cannot reload \"%1\". It is not in the list of workspaces.") Tr::tr("Cannot reload \"%1\". It is not in the list of workspaces.")
.arg(wrk->filePath().toUserOutput())); .arg(wrk->filePath().toUserOutput()));
const Result<QByteArray> data = loadWorkspace(*wrk); const Result<QByteArray> data = loadWorkspace(*wrk);
if (!data) if (!data)
return make_unexpected(data.error()); return ResultError(data.error());
if (!data->isNull() && !restoreState(*data)) if (!data->isNull() && !restoreState(*data))
return make_unexpected(Tr::tr("Cannot restore \"%1\".").arg(wrk->filePath().toUserOutput())); return ResultError(Tr::tr("Cannot restore \"%1\".").arg(wrk->filePath().toUserOutput()));
emit workspaceReloaded(wrk->fileName()); emit workspaceReloaded(wrk->fileName());
@@ -1301,19 +1301,19 @@ Result<QString> DockManager::cloneWorkspace(const QString &originalFileName,
Workspace *w = workspace(originalFileName); Workspace *w = workspace(originalFileName);
if (!w) if (!w)
return make_unexpected(Tr::tr("Workspace \"%1\" does not exist.").arg(originalFileName)); return ResultError(Tr::tr("Workspace \"%1\" does not exist.").arg(originalFileName));
const FilePath originalPath = w->filePath(); const FilePath originalPath = w->filePath();
if (!originalPath.exists()) if (!originalPath.exists())
return make_unexpected( return ResultError(
Tr::tr("Workspace \"%1\" does not exist.").arg(originalPath.toUserOutput())); Tr::tr("Workspace \"%1\" does not exist.").arg(originalPath.toUserOutput()));
const FilePath clonePath = workspaceNameToFilePath(cloneName); const FilePath clonePath = workspaceNameToFilePath(cloneName);
const Result<> copyResult = originalPath.copyFile(clonePath); const Result<> copyResult = originalPath.copyFile(clonePath);
if (!copyResult) if (!copyResult)
return make_unexpected(Tr::tr("Could not clone \"%1\" due to: %2") return ResultError(Tr::tr("Could not clone \"%1\" due to: %2")
.arg(originalPath.toUserOutput(), copyResult.error())); .arg(originalPath.toUserOutput(), copyResult.error()));
writeDisplayName(clonePath, cloneName); writeDisplayName(clonePath, cloneName);
@@ -1329,7 +1329,7 @@ Result<QString> DockManager::renameWorkspace(const QString &originalFileName,
Workspace *w = workspace(originalFileName); Workspace *w = workspace(originalFileName);
if (!w) if (!w)
return make_unexpected(Tr::tr("Workspace \"%1\" does not exist.").arg(originalFileName)); return ResultError(Tr::tr("Workspace \"%1\" does not exist.").arg(originalFileName));
w->setName(newName); w->setName(newName);
@@ -1359,7 +1359,7 @@ Result<> DockManager::resetWorkspacePreset(const QString &fileName)
Result<> DockManager::save() Result<> DockManager::save()
{ {
if (isModeChangeState()) if (isModeChangeState())
return make_unexpected(Tr::tr("Cannot save workspace while in mode change state.")); return ResultError(Tr::tr("Cannot save workspace while in mode change state."));
emit aboutToSaveWorkspace(); emit aboutToSaveWorkspace();
@@ -1390,7 +1390,7 @@ Result<QString> DockManager::importWorkspace(const QString &filePath)
const FilePath sourceFilePath = FilePath::fromUserInput(filePath); const FilePath sourceFilePath = FilePath::fromUserInput(filePath);
if (!sourceFilePath.exists()) if (!sourceFilePath.exists())
return make_unexpected( return ResultError(
Tr::tr("File \"%1\" does not exist.").arg(sourceFilePath.toUserOutput())); Tr::tr("File \"%1\" does not exist.").arg(sourceFilePath.toUserOutput()));
// Extract workspace file name. Check if the workspace is already contained in the list of // Extract workspace file name. Check if the workspace is already contained in the list of
@@ -1402,7 +1402,7 @@ Result<QString> DockManager::importWorkspace(const QString &filePath)
const Result<> copyResult = sourceFilePath.copyFile(targetFilePath); const Result<> copyResult = sourceFilePath.copyFile(targetFilePath);
if (!copyResult) if (!copyResult)
return make_unexpected( return ResultError(
Tr::tr("Could not copy \"%1\" to \"%2\" due to: %3") Tr::tr("Could not copy \"%1\" to \"%2\" due to: %3")
.arg(filePath, targetFilePath.toUserOutput(), copyResult.error())); .arg(filePath, targetFilePath.toUserOutput(), copyResult.error()));
@@ -1424,26 +1424,26 @@ Result<QString> DockManager::exportWorkspace(const QString &targetFilePath,
// Remove the file which supposed to be overwritten // Remove the file which supposed to be overwritten
if (targetFile.exists()) { if (targetFile.exists()) {
if (!targetFile.removeFile()) { if (!targetFile.removeFile()) {
return make_unexpected( return ResultError(
Tr::tr("Could not remove \"%1\".").arg(targetFile.toUserOutput())); Tr::tr("Could not remove \"%1\".").arg(targetFile.toUserOutput()));
} }
} }
// Check if the target directory exists // Check if the target directory exists
if (!targetFile.parentDir().exists()) if (!targetFile.parentDir().exists())
return make_unexpected( return ResultError(
Tr::tr("The directory \"%1\" does not exist.").arg(targetFile.parentDir().toUserOutput())); Tr::tr("The directory \"%1\" does not exist.").arg(targetFile.parentDir().toUserOutput()));
// Check if the workspace exists // Check if the workspace exists
const FilePath workspaceFile = userDirectory().pathAppended(sourceFileName); const FilePath workspaceFile = userDirectory().pathAppended(sourceFileName);
if (!workspaceFile.exists()) if (!workspaceFile.exists())
return make_unexpected( return ResultError(
Tr::tr("The workspace \"%1\" does not exist ").arg(workspaceFile.toUserOutput())); Tr::tr("The workspace \"%1\" does not exist ").arg(workspaceFile.toUserOutput()));
// Finally copy the workspace to the target // Finally copy the workspace to the target
const Result<> copyResult = workspaceFile.copyFile(targetFile); const Result<> copyResult = workspaceFile.copyFile(targetFile);
if (!copyResult) if (!copyResult)
return make_unexpected( return ResultError(
Tr::tr("Could not copy \"%1\" to \"%2\" due to: %3") Tr::tr("Could not copy \"%1\" to \"%2\" due to: %3")
.arg(sourceFileName, workspaceFile.toUserOutput(), copyResult.error())); .arg(sourceFileName, workspaceFile.toUserOutput(), copyResult.error()));
@@ -1610,14 +1610,14 @@ Result<> DockManager::write(const FilePath &filePath, const QByteArray &data)
qCInfo(adsLog) << "Write" << filePath; qCInfo(adsLog) << "Write" << filePath;
if (!filePath.parentDir().ensureWritableDir()) if (!filePath.parentDir().ensureWritableDir())
return make_unexpected(Tr::tr("Cannot write to \"%1\".").arg(filePath.toUserOutput())); return ResultError(Tr::tr("Cannot write to \"%1\".").arg(filePath.toUserOutput()));
FileSaver fileSaver(filePath, QIODevice::Text); FileSaver fileSaver(filePath, QIODevice::Text);
if (!fileSaver.hasError()) if (!fileSaver.hasError())
fileSaver.write(data); fileSaver.write(data);
if (!fileSaver.finalize()) if (!fileSaver.finalize())
return make_unexpected(Tr::tr("Cannot write to \"%1\" due to: %2") return ResultError(Tr::tr("Cannot write to \"%1\" due to: %2")
.arg(filePath.toUserOutput(), fileSaver.errorString())); .arg(filePath.toUserOutput(), fileSaver.errorString()));
return {}; return {};
@@ -1628,7 +1628,7 @@ Result<QByteArray> DockManager::loadWorkspace(const Workspace &workspace) const
qCInfo(adsLog) << "Load workspace" << workspace.fileName(); qCInfo(adsLog) << "Load workspace" << workspace.fileName();
if (!workspace.exists()) if (!workspace.exists())
return make_unexpected( return ResultError(
Tr::tr("Workspace \"%1\" does not exist.").arg(workspace.filePath().toUserOutput())); Tr::tr("Workspace \"%1\" does not exist.").arg(workspace.filePath().toUserOutput()));
return workspace.filePath().fileContents(); return workspace.filePath().fileContents();

View File

@@ -811,11 +811,11 @@ Result<std::unique_ptr<PluginSpec>> readCppPluginSpec(const FilePath &fileName)
spec->d->loader->setFileName(absPath.toFSPathString()); spec->d->loader->setFileName(absPath.toFSPathString());
if (spec->d->loader->fileName().isEmpty()) if (spec->d->loader->fileName().isEmpty())
return make_unexpected(::ExtensionSystem::Tr::tr("Cannot open file")); return ResultError(::ExtensionSystem::Tr::tr("Cannot open file"));
Result<> r = spec->readMetaData(spec->d->loader->metaData()); Result<> r = spec->readMetaData(spec->d->loader->metaData());
if (!r) if (!r)
return make_unexpected(r.error()); return ResultError(r.error());
return spec; return spec;
} }
@@ -828,7 +828,7 @@ Result<std::unique_ptr<PluginSpec>> readCppPluginSpec(const QStaticPlugin &plugi
spec->d->staticPlugin = plugin; spec->d->staticPlugin = plugin;
Result<> r = spec->readMetaData(plugin.metaData()); Result<> r = spec->readMetaData(plugin.metaData());
if (!r) if (!r)
return make_unexpected(r.error()); return ResultError(r.error());
return spec; return spec;
} }
@@ -882,10 +882,10 @@ Result<> CppPluginSpec::readMetaData(const QJsonObject &pluginMetaData)
QJsonValue value; QJsonValue value;
value = pluginMetaData.value(QLatin1String("IID")); value = pluginMetaData.value(QLatin1String("IID"));
if (!value.isString()) if (!value.isString())
return make_unexpected(::ExtensionSystem::Tr::tr("No IID found")); return ResultError(::ExtensionSystem::Tr::tr("No IID found"));
if (value.toString() != PluginManager::pluginIID()) if (value.toString() != PluginManager::pluginIID())
return make_unexpected(::ExtensionSystem::Tr::tr("Expected IID \"%1\", but found \"%2\"") return ResultError(::ExtensionSystem::Tr::tr("Expected IID \"%1\", but found \"%2\"")
.arg(PluginManager::pluginIID()) .arg(PluginManager::pluginIID())
.arg(value.toString())); .arg(value.toString()));
@@ -920,9 +920,9 @@ Utils::Result<> PluginSpecPrivate::readMetaData(const QJsonObject &data)
auto assign = [&data](QString &member, const char *fieldName) -> Result<> { auto assign = [&data](QString &member, const char *fieldName) -> Result<> {
QJsonValue value = data.value(QLatin1String(fieldName)); QJsonValue value = data.value(QLatin1String(fieldName));
if (value.isUndefined()) if (value.isUndefined())
return make_unexpected(msgValueMissing(fieldName)); return ResultError(msgValueMissing(fieldName));
if (!value.isString()) if (!value.isString())
return make_unexpected(msgValueIsNotAString(fieldName)); return ResultError(msgValueIsNotAString(fieldName));
member = value.toString(); member = value.toString();
return {}; return {};
}; };
@@ -940,11 +940,11 @@ Utils::Result<> PluginSpecPrivate::readMetaData(const QJsonObject &data)
if constexpr (isString) { if constexpr (isString) {
if (!value.isString()) if (!value.isString())
return make_unexpected(msgValueIsNotAString(fieldName)); return ResultError(msgValueIsNotAString(fieldName));
member = value.toString(); member = value.toString();
} else if constexpr (isBool) { } else if constexpr (isBool) {
if (!value.isBool()) if (!value.isBool())
return make_unexpected(msgValueIsNotABool(fieldName)); return ResultError(msgValueIsNotABool(fieldName));
member = value.toBool(); member = value.toBool();
} }
} }
@@ -956,7 +956,7 @@ Utils::Result<> PluginSpecPrivate::readMetaData(const QJsonObject &data)
if (value.isUndefined()) if (value.isUndefined())
return {}; return {};
if (!readMultiLineString(value, &member)) if (!readMultiLineString(value, &member))
return make_unexpected(msgValueIsNotAMultilineString(fieldName)); return ResultError(msgValueIsNotAMultilineString(fieldName));
return {}; return {};
}; };
@@ -1483,7 +1483,7 @@ QList<PluginSpec *> pluginSpecsFromArchive(const Utils::FilePath &path)
Result<FilePaths> PluginSpec::filesToUninstall() const Result<FilePaths> PluginSpec::filesToUninstall() const
{ {
if (isSystemPlugin()) if (isSystemPlugin())
return make_unexpected(Tr::tr("Cannot remove system plugins.")); return ResultError(Tr::tr("Cannot remove system plugins."));
// Try to figure out where we are ... // Try to figure out where we are ...
const FilePaths pluginPaths = PluginManager::pluginPaths(); const FilePaths pluginPaths = PluginManager::pluginPaths();
@@ -1492,7 +1492,7 @@ Result<FilePaths> PluginSpec::filesToUninstall() const
if (location().isChildOf(pluginPath)) { if (location().isChildOf(pluginPath)) {
const FilePath rootFolder = location().relativeChildPath(pluginPath); const FilePath rootFolder = location().relativeChildPath(pluginPath);
if (rootFolder.isEmpty()) if (rootFolder.isEmpty())
return make_unexpected(Tr::tr("Could not determine root folder.")); return ResultError(Tr::tr("Could not determine root folder."));
const FilePath pathToDelete = pluginPath const FilePath pathToDelete = pluginPath
/ rootFolder.pathComponents().first().toString(); / rootFolder.pathComponents().first().toString();

View File

@@ -27,7 +27,7 @@ Result<QString> run(const CommandLine &cmdLine, const QByteArray &inputData = {}
p.setWriteData(inputData); p.setWriteData(inputData);
p.runBlocking(); p.runBlocking();
if (p.exitCode() != 0) { if (p.exitCode() != 0) {
return make_unexpected(Tr::tr("Command failed with exit code %1: %2") return ResultError(Tr::tr("Command failed with exit code %1: %2")
.arg(p.exitCode()) .arg(p.exitCode())
.arg(p.readAllStandardOutput())); .arg(p.readAllStandardOutput()));
} }
@@ -455,7 +455,7 @@ Result<QByteArray> FileAccess::fileContents(const FilePath &filePath,
} }
return data; return data;
} catch (const std::exception &e) { } catch (const std::exception &e) {
return make_unexpected( return ResultError(
Tr::tr("Error reading file: %1").arg(QString::fromLocal8Bit(e.what()))); Tr::tr("Error reading file: %1").arg(QString::fromLocal8Bit(e.what())));
} }
} }
@@ -468,7 +468,7 @@ Result<qint64> FileAccess::writeFileContents(const FilePath &filePath,
QTC_ASSERT_RESULT(f, return {}); QTC_ASSERT_RESULT(f, return {});
return f->result(); return f->result();
} catch (const std::exception &e) { } catch (const std::exception &e) {
return make_unexpected( return ResultError(
Tr::tr("Error writing file: %1").arg(QString::fromLocal8Bit(e.what()))); Tr::tr("Error writing file: %1").arg(QString::fromLocal8Bit(e.what())));
} }
} }
@@ -607,7 +607,7 @@ Result<FilePath> FileAccess::createTempFile(const FilePath &filePath)
return result; return result;
return filePath.withNewPath(result->path()); return filePath.withNewPath(result->path());
} catch (const std::exception &e) { } catch (const std::exception &e) {
return make_unexpected( return ResultError(
Tr::tr("Error creating temporary file: %1").arg(QString::fromLocal8Bit(e.what()))); Tr::tr("Error creating temporary file: %1").arg(QString::fromLocal8Bit(e.what())));
} }
} }

View File

@@ -178,7 +178,7 @@ std::optional<Result<>> ClientPrivate::handleWatchResults(const QVariantMap &map
auto it = watchers.find(id); auto it = watchers.find(id);
if (it == watchers.end()) if (it == watchers.end())
return make_unexpected(QString("No watcher found for id %1").arg(id)); return ResultError(QString("No watcher found for id %1").arg(id));
auto promise = it.value(); auto promise = it.value();
if (!promise->isCanceled()) if (!promise->isCanceled())
@@ -197,7 +197,7 @@ std::optional<Result<>> ClientPrivate::handleWatchResults(const QVariantMap &map
Result<> ClientPrivate::readPacket(QCborStreamReader &reader) Result<> ClientPrivate::readPacket(QCborStreamReader &reader)
{ {
if (!reader.enterContainer()) if (!reader.enterContainer())
return make_unexpected(QString("The packet did not contain a container")); return ResultError(QString("The packet did not contain a container"));
Q_ASSERT(QThread::currentThread() == thread); Q_ASSERT(QThread::currentThread() == thread);
@@ -209,10 +209,10 @@ Result<> ClientPrivate::readPacket(QCborStreamReader &reader)
} }
if (!reader.leaveContainer()) if (!reader.leaveContainer())
return make_unexpected(QString("The packet did not contain a finalized map")); return ResultError(QString("The packet did not contain a finalized map"));
if (!map.contains("Id")) { if (!map.contains("Id")) {
return make_unexpected(QString("The packet did not contain an Id")); return ResultError(QString("The packet did not contain an Id"));
} }
auto watchHandled = handleWatchResults(map); auto watchHandled = handleWatchResults(map);
@@ -223,7 +223,7 @@ Result<> ClientPrivate::readPacket(QCborStreamReader &reader)
auto j = jobs.readLocked(); auto j = jobs.readLocked();
auto it = j->map.find(id); auto it = j->map.find(id);
if (it == j->map.end()) if (it == j->map.end())
return make_unexpected( return ResultError(
QString("No job found for packet with id %1: %2") QString("No job found for packet with id %1: %2")
.arg(id) .arg(id)
.arg(QString::fromUtf8(QJsonDocument::fromVariant(map).toJson()))); .arg(QString::fromUtf8(QJsonDocument::fromVariant(map).toJson())));
@@ -421,7 +421,7 @@ static Utils::Result<QFuture<R>> createJob(
Errors handleErrors = Errors::Handle) Errors handleErrors = Errors::Handle)
{ {
if (!d->process || !d->process->isRunning()) if (!d->process || !d->process->isRunning())
return make_unexpected(Tr::tr("Bridge process not running")); return ResultError(Tr::tr("Bridge process not running"));
std::shared_ptr<QPromise<R>> promise = std::make_shared<QPromise<R>>(); std::shared_ptr<QPromise<R>> promise = std::make_shared<QPromise<R>>();
QFuture<R> future = promise->future(); QFuture<R> future = promise->future();
@@ -515,7 +515,7 @@ Result<QFuture<Client::FindData>> Client::find(
{ {
// TODO: golang's walkDir does not support automatically following symlinks. // TODO: golang's walkDir does not support automatically following symlinks.
if (filter.iteratorFlags.testFlag(QDirIterator::FollowSymlinks)) if (filter.iteratorFlags.testFlag(QDirIterator::FollowSymlinks))
return make_unexpected(Tr::tr("FollowSymlinks is not supported")); return ResultError(Tr::tr("FollowSymlinks is not supported"));
QCborMap findArgs{ QCborMap findArgs{
{"Type", "find"}, {"Type", "find"},
@@ -818,12 +818,12 @@ Utils::Result<std::unique_ptr<FilePathWatcher>> Client::watch(const QString &pat
}); });
if (!jobResult) if (!jobResult)
return make_unexpected(jobResult.error()); return ResultError(jobResult.error());
try { try {
return std::make_unique<GoFilePathWatcher>(jobResult->result()); return std::make_unique<GoFilePathWatcher>(jobResult->result());
} catch (const std::exception &e) { } catch (const std::exception &e) {
return make_unexpected(QString::fromUtf8(e.what())); return ResultError(QString::fromUtf8(e.what()));
} }
} }
@@ -841,9 +841,9 @@ Utils::Result<QFuture<void>> Client::signalProcess(int pid, Utils::ControlSignal
signalString = "kill"; signalString = "kill";
break; break;
case ControlSignal::KickOff: case ControlSignal::KickOff:
return make_unexpected(Tr::tr("Kickoff signal is not supported")); return ResultError(Tr::tr("Kickoff signal is not supported"));
case ControlSignal::CloseWriteChannel: case ControlSignal::CloseWriteChannel:
return make_unexpected(Tr::tr("CloseWriteChannel signal is not supported")); return ResultError(Tr::tr("CloseWriteChannel signal is not supported"));
} }
return createVoidJob( return createVoidJob(
@@ -942,7 +942,7 @@ Result<FilePath> Client::getCmdBridgePath(
if (result.exists()) if (result.exists())
return result; return result;
return make_unexpected( return ResultError(
QString(Tr::tr("No command bridge found for architecture %1-%2")).arg(type, arch)); QString(Tr::tr("No command bridge found for architecture %1-%2")).arg(type, arch));
} }

View File

@@ -313,7 +313,7 @@ Result<QByteArray> DeviceFileAccess::fileContents(const FilePath &filePath,
Q_UNUSED(limit) Q_UNUSED(limit)
Q_UNUSED(offset) Q_UNUSED(offset)
QTC_CHECK(false); QTC_CHECK(false);
return make_unexpected( return ResultError(
Tr::tr("fileContents is not implemented for \"%1\".").arg(filePath.toUserOutput())); Tr::tr("fileContents is not implemented for \"%1\".").arg(filePath.toUserOutput()));
} }
@@ -323,7 +323,7 @@ Result<qint64> DeviceFileAccess::writeFileContents(const FilePath &filePath,
Q_UNUSED(filePath) Q_UNUSED(filePath)
Q_UNUSED(data) Q_UNUSED(data)
QTC_CHECK(false); QTC_CHECK(false);
return make_unexpected( return ResultError(
Tr::tr("writeFileContents is not implemented for \"%1\".").arg(filePath.toUserOutput())); Tr::tr("writeFileContents is not implemented for \"%1\".").arg(filePath.toUserOutput()));
} }
@@ -389,7 +389,7 @@ Result<FilePath> DeviceFileAccess::createTempFile(const FilePath &filePath)
{ {
Q_UNUSED(filePath) Q_UNUSED(filePath)
QTC_CHECK(false); QTC_CHECK(false);
return make_unexpected( return ResultError(
Tr::tr("createTempFile is not implemented for \"%1\".").arg(filePath.toUserOutput())); Tr::tr("createTempFile is not implemented for \"%1\".").arg(filePath.toUserOutput()));
} }
@@ -397,7 +397,7 @@ Utils::Result<std::unique_ptr<FilePathWatcher>> DeviceFileAccess::watch(
const FilePath &path) const const FilePath &path) const
{ {
Q_UNUSED(path); Q_UNUSED(path);
return make_unexpected(Tr::tr("watch is not implemented.")); return ResultError(Tr::tr("watch is not implemented."));
} }
QTextCodec *DeviceFileAccess::processStdOutCodec(const FilePath &executable) const QTextCodec *DeviceFileAccess::processStdOutCodec(const FilePath &executable) const
@@ -566,7 +566,7 @@ Result<QByteArray> UnavailableDeviceFileAccess::fileContents(const FilePath &fil
Q_UNUSED(filePath) Q_UNUSED(filePath)
Q_UNUSED(limit) Q_UNUSED(limit)
Q_UNUSED(offset) Q_UNUSED(offset)
return make_unexpected(unavailableMessage()); return ResultError(unavailableMessage());
} }
Result<qint64> UnavailableDeviceFileAccess::writeFileContents(const FilePath &filePath, Result<qint64> UnavailableDeviceFileAccess::writeFileContents(const FilePath &filePath,
@@ -574,7 +574,7 @@ Result<qint64> UnavailableDeviceFileAccess::writeFileContents(const FilePath &fi
{ {
Q_UNUSED(filePath) Q_UNUSED(filePath)
Q_UNUSED(data) Q_UNUSED(data)
return make_unexpected(unavailableMessage()); return ResultError(unavailableMessage());
} }
FilePathInfo UnavailableDeviceFileAccess::filePathInfo(const FilePath &filePath) const FilePathInfo UnavailableDeviceFileAccess::filePathInfo(const FilePath &filePath) const
@@ -630,14 +630,14 @@ std::optional<FilePath> UnavailableDeviceFileAccess::refersToExecutableFile(
Result<FilePath> UnavailableDeviceFileAccess::createTempFile(const FilePath &filePath) Result<FilePath> UnavailableDeviceFileAccess::createTempFile(const FilePath &filePath)
{ {
Q_UNUSED(filePath) Q_UNUSED(filePath)
return make_unexpected(unavailableMessage()); return ResultError(unavailableMessage());
} }
Result<std::unique_ptr<FilePathWatcher>> Result<std::unique_ptr<FilePathWatcher>>
UnavailableDeviceFileAccess::watch(const FilePath &path) const UnavailableDeviceFileAccess::watch(const FilePath &path) const
{ {
Q_UNUSED(path); Q_UNUSED(path);
return make_unexpected(unavailableMessage()); return ResultError(unavailableMessage());
} }
// DesktopDeviceFileAccess // DesktopDeviceFileAccess
@@ -1138,10 +1138,10 @@ Result<QByteArray> DesktopDeviceFileAccess::fileContents(const FilePath &filePat
const QString path = filePath.path(); const QString path = filePath.path();
QFile f(path); QFile f(path);
if (!f.exists()) if (!f.exists())
return make_unexpected(Tr::tr("File \"%1\" does not exist.").arg(path)); return ResultError(Tr::tr("File \"%1\" does not exist.").arg(path));
if (!f.open(QFile::ReadOnly)) if (!f.open(QFile::ReadOnly))
return make_unexpected(Tr::tr("Could not open File \"%1\".").arg(path)); return ResultError(Tr::tr("Could not open File \"%1\".").arg(path));
if (offset != 0) if (offset != 0)
f.seek(offset); f.seek(offset);
@@ -1151,7 +1151,7 @@ Result<QByteArray> DesktopDeviceFileAccess::fileContents(const FilePath &filePat
const QByteArray data = f.readAll(); const QByteArray data = f.readAll();
if (f.error() != QFile::NoError) { if (f.error() != QFile::NoError) {
return make_unexpected( return ResultError(
Tr::tr("Cannot read \"%1\": %2").arg(filePath.toUserOutput(), f.errorString())); Tr::tr("Cannot read \"%1\": %2").arg(filePath.toUserOutput(), f.errorString()));
} }
@@ -1164,12 +1164,12 @@ Result<qint64> DesktopDeviceFileAccess::writeFileContents(const FilePath &filePa
QFile file(filePath.path()); QFile file(filePath.path());
const bool isOpened = file.open(QFile::WriteOnly | QFile::Truncate); const bool isOpened = file.open(QFile::WriteOnly | QFile::Truncate);
if (!isOpened) if (!isOpened)
return make_unexpected( return ResultError(
Tr::tr("Could not open file \"%1\" for writing.").arg(filePath.toUserOutput())); Tr::tr("Could not open file \"%1\" for writing.").arg(filePath.toUserOutput()));
qint64 res = file.write(data); qint64 res = file.write(data);
if (res != data.size()) if (res != data.size())
return make_unexpected( return ResultError(
Tr::tr("Could not write to file \"%1\" (only %2 of %n byte(s) written).", Tr::tr("Could not write to file \"%1\" (only %2 of %n byte(s) written).",
nullptr, nullptr,
data.size()) data.size())
@@ -1183,7 +1183,7 @@ Result<FilePath> DesktopDeviceFileAccess::createTempFile(const FilePath &filePat
QTemporaryFile file(filePath.path()); QTemporaryFile file(filePath.path());
file.setAutoRemove(false); file.setAutoRemove(false);
if (!file.open()) { if (!file.open()) {
return make_unexpected(Tr::tr("Could not create temporary file in \"%1\" (%2).") return ResultError(Tr::tr("Could not create temporary file in \"%1\" (%2).")
.arg(filePath.toUserOutput()) .arg(filePath.toUserOutput())
.arg(file.errorString())); .arg(file.errorString()));
} }
@@ -1196,7 +1196,7 @@ Utils::Result<std::unique_ptr<FilePathWatcher>> DesktopDeviceFileAccess::watch(
auto watcher = std::make_unique<DesktopFilePathWatcher>(path); auto watcher = std::make_unique<DesktopFilePathWatcher>(path);
if (watcher->error().isEmpty()) if (watcher->error().isEmpty())
return watcher; return watcher;
return make_unexpected(watcher->error()); return ResultError(watcher->error());
} }
QTextCodec *DesktopDeviceFileAccess::processStdOutCodec(const FilePath &executable) const QTextCodec *DesktopDeviceFileAccess::processStdOutCodec(const FilePath &executable) const
@@ -1489,12 +1489,12 @@ Result<QByteArray> UnixDeviceFileAccess::fileContents(const FilePath &filePath,
p.setCommand({dd, args, OsType::OsTypeLinux}); p.setCommand({dd, args, OsType::OsTypeLinux});
p.runBlocking(0s); // Run forever p.runBlocking(0s); // Run forever
if (p.exitCode() != 0) { if (p.exitCode() != 0) {
return make_unexpected(Tr::tr("Failed reading file \"%1\": %2") return ResultError(Tr::tr("Failed reading file \"%1\": %2")
.arg(filePath.toUserOutput(), p.readAllStandardError())); .arg(filePath.toUserOutput(), p.readAllStandardError()));
} }
return p.rawStdOut(); return p.rawStdOut();
#else #else
return make_unexpected(QString("Not implemented")); return ResultError(QString("Not implemented"));
#endif #endif
} }
@@ -1509,7 +1509,7 @@ Result<qint64> UnixDeviceFileAccess::writeFileContents(const FilePath &filePath,
RunResult result = runInShell({"dd", args, OsType::OsTypeLinux}, data); RunResult result = runInShell({"dd", args, OsType::OsTypeLinux}, data);
if (result.exitCode != 0) { if (result.exitCode != 0) {
return make_unexpected(Tr::tr("Failed writing file \"%1\": %2") return ResultError(Tr::tr("Failed writing file \"%1\": %2")
.arg(filePath.toUserOutput(), QString::fromUtf8(result.stdErr))); .arg(filePath.toUserOutput(), QString::fromUtf8(result.stdErr)));
} }
return data.size(); return data.size();
@@ -1530,7 +1530,7 @@ Result<FilePath> UnixDeviceFileAccess::createTempFile(const FilePath &filePath)
const RunResult result = runInShell({"mktemp", {tmplate}, OsType::OsTypeLinux}); const RunResult result = runInShell({"mktemp", {tmplate}, OsType::OsTypeLinux});
if (result.exitCode != 0) { if (result.exitCode != 0) {
return make_unexpected( return ResultError(
Tr::tr("Failed creating temporary file \"%1\": %2") Tr::tr("Failed creating temporary file \"%1\": %2")
.arg(filePath.toUserOutput(), QString::fromUtf8(result.stdErr))); .arg(filePath.toUserOutput(), QString::fromUtf8(result.stdErr)));
} }
@@ -1561,7 +1561,7 @@ Result<FilePath> UnixDeviceFileAccess::createTempFile(const FilePath &filePath)
} }
newPath = filePath.withNewPath(tmplate); newPath = filePath.withNewPath(tmplate);
if (--maxTries == 0) { if (--maxTries == 0) {
return make_unexpected(Tr::tr("Failed creating temporary file \"%1\" (too many tries).") return ResultError(Tr::tr("Failed creating temporary file \"%1\" (too many tries).")
.arg(filePath.toUserOutput())); .arg(filePath.toUserOutput()));
} }
} while (newPath.exists()); } while (newPath.exists());
@@ -1569,7 +1569,7 @@ Result<FilePath> UnixDeviceFileAccess::createTempFile(const FilePath &filePath)
const Result<qint64> createResult = newPath.writeFileContents({}); const Result<qint64> createResult = newPath.writeFileContents({});
if (!createResult) if (!createResult)
return make_unexpected(createResult.error()); return ResultError(createResult.error());
return newPath; return newPath;
} }

View File

@@ -185,7 +185,7 @@ Result<> DeviceShell::start()
if (!m_shellProcess->waitForStarted()) { if (!m_shellProcess->waitForStarted()) {
closeShellProcess(); closeShellProcess();
return make_unexpected(Tr::tr("The process failed to start.")); return ResultError(Tr::tr("The process failed to start."));
} }
auto installResult = installShellScript(); auto installResult = installShellScript();
@@ -219,7 +219,7 @@ Result<> DeviceShell::start()
const QString stdErr = m_shellProcess->readAllStandardError(); const QString stdErr = m_shellProcess->readAllStandardError();
m_shellProcess.reset(); m_shellProcess.reset();
return make_unexpected(Tr::tr("Failed to install shell script: %1\n%2") return ResultError(Tr::tr("Failed to install shell script: %1\n%2")
.arg(installResult.error()) .arg(installResult.error())
.arg(stdErr)); .arg(stdErr));
}, },
@@ -235,14 +235,14 @@ Result<QByteArray> DeviceShell::checkCommand(const QByteArray &command)
m_shellProcess->writeRaw(checkCmd); m_shellProcess->writeRaw(checkCmd);
if (!m_shellProcess->waitForReadyRead()) { if (!m_shellProcess->waitForReadyRead()) {
return make_unexpected( return ResultError(
Tr::tr("Timeout while trying to check for %1.").arg(QString::fromUtf8(command))); Tr::tr("Timeout while trying to check for %1.").arg(QString::fromUtf8(command)));
} }
QByteArray out = m_shellProcess->readAllRawStandardOutput(); QByteArray out = m_shellProcess->readAllRawStandardOutput();
if (out.contains("<missing>")) { if (out.contains("<missing>")) {
m_shellScriptState = State::Failed; m_shellScriptState = State::Failed;
m_missingFeatures.append(QString::fromUtf8(command)); m_missingFeatures.append(QString::fromUtf8(command));
return make_unexpected( return ResultError(
Tr::tr("Command \"%1\" was not found.").arg(QString::fromUtf8(command))); Tr::tr("Command \"%1\" was not found.").arg(QString::fromUtf8(command)));
} }

View File

@@ -121,7 +121,7 @@ Result<qint64> ProcessStubCreator::startStubProcess(const ProcessSetupData &setu
QTemporaryFile shFile; QTemporaryFile shFile;
shFile.setAutoRemove(false); shFile.setAutoRemove(false);
QTC_ASSERT(shFile.open(), QTC_ASSERT(shFile.open(),
return make_unexpected(Tr::tr("Failed to open temporary script file."))); return ResultError(Tr::tr("Failed to open temporary script file.")));
const QString shScript = QString("cd '%1'\n%2\nclear\n'%3' %4\nrm '%5'\n") const QString shScript = QString("cd '%1'\n%2\nclear\n'%3' %4\nrm '%5'\n")
.arg(setupData.m_workingDirectory.nativePath()) .arg(setupData.m_workingDirectory.nativePath())
@@ -148,7 +148,7 @@ Result<qint64> ProcessStubCreator::startStubProcess(const ProcessSetupData &setu
process->start(); process->start();
if (!process->waitForStarted()) { if (!process->waitForStarted()) {
return make_unexpected( return ResultError(
Tr::tr("Failed to start terminal process: \"%1\".").arg(process->errorString())); Tr::tr("Failed to start terminal process: \"%1\".").arg(process->errorString()));
} }
@@ -196,7 +196,7 @@ Result<qint64> ProcessStubCreator::startStubProcess(const ProcessSetupData &setu
process->start(); process->start();
process->waitForStarted(); process->waitForStarted();
if (process->error() != QProcess::UnknownError) { if (process->error() != QProcess::UnknownError) {
return make_unexpected( return ResultError(
Tr::tr("Failed to start terminal process: \"%1\".").arg(process->errorString())); Tr::tr("Failed to start terminal process: \"%1\".").arg(process->errorString()));
} }

View File

@@ -631,7 +631,7 @@ void FancyLineEdit::validate()
if (validates) if (validates)
result = t; result = t;
else else
result = make_unexpected(error); result = ResultError(error);
handleValidationResult(result, t); handleValidationResult(result, t);
} }

View File

@@ -649,7 +649,7 @@ Result<FilePath> FilePath::tmpDir() const
if (!isLocal()) { if (!isLocal()) {
const Result<Environment> env = deviceEnvironmentWithError(); const Result<Environment> env = deviceEnvironmentWithError();
if (!env) if (!env)
return make_unexpected(env.error()); return ResultError(env.error());
if (env->hasKey("TMPDIR")) if (env->hasKey("TMPDIR"))
return withNewPath(env->value("TMPDIR")).cleanPath(); return withNewPath(env->value("TMPDIR")).cleanPath();
@@ -660,7 +660,7 @@ Result<FilePath> FilePath::tmpDir() const
if (osType() != OsTypeWindows) if (osType() != OsTypeWindows)
return withNewPath("/tmp"); return withNewPath("/tmp");
return make_unexpected(QString("Could not find temporary directory on device %1") return ResultError(QString("Could not find temporary directory on device %1")
.arg(displayName())); .arg(displayName()));
} }
@@ -675,7 +675,7 @@ Result<FilePath> FilePath::createTempFile() const
if (file.open()) if (file.open())
return FilePath::fromString(file.fileName()); return FilePath::fromString(file.fileName());
return make_unexpected(QString("Could not create temporary file: %1").arg(file.errorString())); return ResultError(QString("Could not create temporary file: %1").arg(file.errorString()));
} }
return fileAccess()->createTempFile(*this); return fileAccess()->createTempFile(*this);
@@ -2342,7 +2342,7 @@ Result<FilePath> FilePath::localSource() const
return *this; return *this;
QTC_ASSERT(deviceFileHooks().localSource, QTC_ASSERT(deviceFileHooks().localSource,
return make_unexpected(Tr::tr("No \"localSource\" device hook set."))); return ResultError(Tr::tr("No \"localSource\" device hook set.")));
return deviceFileHooks().localSource(*this); return deviceFileHooks().localSource(*this);
} }
@@ -2572,7 +2572,7 @@ Result<std::unique_ptr<TemporaryFilePath>> TemporaryFilePath::create(
{ {
Result<FilePath> result = templatePath.createTempFile(); Result<FilePath> result = templatePath.createTempFile();
if (!result) if (!result)
return make_unexpected(result.error()); return ResultError(result.error());
return std::unique_ptr<TemporaryFilePath>(new TemporaryFilePath(templatePath, *result)); return std::unique_ptr<TemporaryFilePath>(new TemporaryFilePath(templatePath, *result));
} }

View File

@@ -132,7 +132,7 @@ FileStreamHandle FileStreamerManager::copy(const FilePath &source, const FilePat
if (streamer->result() == Tasking::DoneResult::Success) if (streamer->result() == Tasking::DoneResult::Success)
cont({}); cont({});
else else
cont(make_unexpected(Tr::tr("Failed copying file."))); cont(ResultError(Tr::tr("Failed copying file.")));
}; };
return execute(onSetup, onDone, context); return execute(onSetup, onDone, context);
} }
@@ -156,7 +156,7 @@ FileStreamHandle FileStreamerManager::read(const FilePath &source, QObject *cont
if (streamer->result() == Tasking::DoneResult::Success) if (streamer->result() == Tasking::DoneResult::Success)
cont(streamer->readData()); cont(streamer->readData());
else else
cont(make_unexpected(Tr::tr("Failed reading file."))); cont(ResultError(Tr::tr("Failed reading file.")));
}; };
return execute(onSetup, onDone, context); return execute(onSetup, onDone, context);
} }
@@ -182,7 +182,7 @@ FileStreamHandle FileStreamerManager::write(const FilePath &destination, const Q
if (streamer->result() == Tasking::DoneResult::Success) if (streamer->result() == Tasking::DoneResult::Success)
cont(0); // TODO: return write count? cont(0); // TODO: return write count?
else else
cont(make_unexpected(Tr::tr("Failed writing file."))); cont(ResultError(Tr::tr("Failed writing file.")));
}; };
return execute(onSetup, onDone, context); return execute(onSetup, onDone, context);
} }

View File

@@ -835,7 +835,7 @@ Result<FilePath> scratchBufferFilePath(const QString &pattern)
QTemporaryFile file(tmp); QTemporaryFile file(tmp);
file.setAutoRemove(false); file.setAutoRemove(false);
if (!file.open()) { if (!file.open()) {
return make_unexpected(Tr::tr("Failed to set up scratch buffer in \"%1\".") return ResultError(Tr::tr("Failed to set up scratch buffer in \"%1\".")
.arg(FilePath::fromString(tmp).parentDir().toUserOutput())); .arg(FilePath::fromString(tmp).parentDir().toUserOutput()));
} }
file.close(); file.close();

View File

@@ -22,7 +22,7 @@ LuaInterface *luaInterface()
Result<std::unique_ptr<LuaState>> runScript(const QString &script, const QString &name) Result<std::unique_ptr<LuaState>> runScript(const QString &script, const QString &name)
{ {
if (!s_luaInterface) if (!s_luaInterface)
return make_unexpected(Tr::tr("No Lua interface set")); return ResultError(Tr::tr("No Lua interface set"));
return s_luaInterface->runScript(script, name); return s_luaInterface->runScript(script, name);
} }

View File

@@ -415,8 +415,7 @@ QVariant MacroExpander::expandVariant(const QVariant &v) const
return v; return v;
} }
Result<QString> MacroExpander::expandProcessArgs( Result<QString> MacroExpander::expandProcessArgs(const QString &argsWithVariables, OsType osType) const
const QString &argsWithVariables, Utils::OsType osType) const
{ {
QString result = argsWithVariables; QString result = argsWithVariables;
const bool ok = ProcessArgs::expandMacros( const bool ok = ProcessArgs::expandMacros(
@@ -425,7 +424,7 @@ Result<QString> MacroExpander::expandProcessArgs(
osType); osType);
if (!ok) { if (!ok) {
return make_unexpected( return ResultError(
Tr::tr("Failed to expand macros in process arguments: %1").arg(argsWithVariables)); Tr::tr("Failed to expand macros in process arguments: %1").arg(argsWithVariables));
} }
return result; return result;

View File

@@ -49,7 +49,7 @@ inline Utils::Result<OsType> osTypeFromString(const QString &string)
if (string.compare("other unix", Qt::CaseInsensitive) == 0) if (string.compare("other unix", Qt::CaseInsensitive) == 0)
return OsTypeOtherUnix; return OsTypeOtherUnix;
return Utils::make_unexpected(QString::fromLatin1("Unknown os type: %1").arg(string)); return Utils::ResultError(QString::fromLatin1("Unknown os type: %1").arg(string));
} }
inline Utils::Result<OsArch> osArchFromString(const QString &architecture) inline Utils::Result<OsArch> osArchFromString(const QString &architecture)
@@ -65,7 +65,7 @@ inline Utils::Result<OsArch> osArchFromString(const QString &architecture)
if (architecture == QLatin1String("arm64") || architecture == QLatin1String("aarch64")) if (architecture == QLatin1String("arm64") || architecture == QLatin1String("aarch64"))
return OsArchArm64; return OsArchArm64;
return Utils::make_unexpected(QString::fromLatin1("Unknown architecture: %1").arg(architecture)); return Utils::ResultError(QString::fromLatin1("Unknown architecture: %1").arg(architecture));
} }
namespace OsSpecificAspects { namespace OsSpecificAspects {

View File

@@ -539,7 +539,7 @@ static FancyLineEdit::AsyncValidationResult validatePath(FilePath filePath,
if (!defaultValue.isEmpty()) { if (!defaultValue.isEmpty()) {
filePath = FilePath::fromUserInput(defaultValue); filePath = FilePath::fromUserInput(defaultValue);
} else { } else {
return make_unexpected(Tr::tr("The path must not be empty.")); return ResultError(Tr::tr("The path must not be empty."));
} }
} }
@@ -547,57 +547,57 @@ static FancyLineEdit::AsyncValidationResult validatePath(FilePath filePath,
switch (kind) { switch (kind) {
case PathChooser::ExistingDirectory: case PathChooser::ExistingDirectory:
if (!filePath.exists()) { if (!filePath.exists()) {
return make_unexpected( return ResultError(
Tr::tr("The path \"%1\" does not exist.").arg(filePath.toUserOutput())); Tr::tr("The path \"%1\" does not exist.").arg(filePath.toUserOutput()));
} }
if (!filePath.isDir()) { if (!filePath.isDir()) {
return make_unexpected( return ResultError(
Tr::tr("The path \"%1\" is not a directory.").arg(filePath.toUserOutput())); Tr::tr("The path \"%1\" is not a directory.").arg(filePath.toUserOutput()));
} }
break; break;
case PathChooser::File: case PathChooser::File:
if (!filePath.exists()) { if (!filePath.exists()) {
return make_unexpected( return ResultError(
Tr::tr("The path \"%1\" does not exist.").arg(filePath.toUserOutput())); Tr::tr("The path \"%1\" does not exist.").arg(filePath.toUserOutput()));
} }
if (!filePath.isFile()) { if (!filePath.isFile()) {
return make_unexpected( return ResultError(
Tr::tr("The path \"%1\" is not a file.").arg(filePath.toUserOutput())); Tr::tr("The path \"%1\" is not a file.").arg(filePath.toUserOutput()));
} }
break; break;
case PathChooser::SaveFile: case PathChooser::SaveFile:
if (!filePath.parentDir().exists()) { if (!filePath.parentDir().exists()) {
return make_unexpected( return ResultError(
Tr::tr("The directory \"%1\" does not exist.").arg(filePath.toUserOutput())); Tr::tr("The directory \"%1\" does not exist.").arg(filePath.toUserOutput()));
} }
if (filePath.exists() && filePath.isDir()) { if (filePath.exists() && filePath.isDir()) {
return make_unexpected( return ResultError(
Tr::tr("The path \"%1\" is not a file.").arg(filePath.toUserOutput())); Tr::tr("The path \"%1\" is not a file.").arg(filePath.toUserOutput()));
} }
break; break;
case PathChooser::ExistingCommand: case PathChooser::ExistingCommand:
if (!filePath.exists()) { if (!filePath.exists()) {
return make_unexpected( return ResultError(
Tr::tr("The path \"%1\" does not exist.").arg(filePath.toUserOutput())); Tr::tr("The path \"%1\" does not exist.").arg(filePath.toUserOutput()));
} }
if (!filePath.isExecutableFile()) { if (!filePath.isExecutableFile()) {
return make_unexpected( return ResultError(
Tr::tr("The path \"%1\" is not an executable file.").arg(filePath.toUserOutput())); Tr::tr("The path \"%1\" is not an executable file.").arg(filePath.toUserOutput()));
} }
break; break;
case PathChooser::Directory: case PathChooser::Directory:
if (filePath.exists() && !filePath.isDir()) { if (filePath.exists() && !filePath.isDir()) {
return make_unexpected( return ResultError(
Tr::tr("The path \"%1\" is not a directory.").arg(filePath.toUserOutput())); Tr::tr("The path \"%1\" is not a directory.").arg(filePath.toUserOutput()));
} }
if (filePath.osType() == OsTypeWindows && !filePath.startsWithDriveLetter() if (filePath.osType() == OsTypeWindows && !filePath.startsWithDriveLetter()
&& !filePath.startsWith("\\\\") && !filePath.startsWith("//")) { && !filePath.startsWith("\\\\") && !filePath.startsWith("//")) {
return make_unexpected(Tr::tr("Invalid path \"%1\".").arg(filePath.toUserOutput())); return ResultError(Tr::tr("Invalid path \"%1\".").arg(filePath.toUserOutput()));
} }
break; break;
case PathChooser::Command: case PathChooser::Command:
if (filePath.exists() && !filePath.isExecutableFile()) { if (filePath.exists() && !filePath.isExecutableFile()) {
return make_unexpected(Tr::tr("Cannot execute \"%1\".").arg(filePath.toUserOutput())); return ResultError(Tr::tr("Cannot execute \"%1\".").arg(filePath.toUserOutput()));
} }
break; break;
@@ -613,14 +613,14 @@ FancyLineEdit::AsyncValidationFunction PathChooser::defaultValidationFunction()
return [this](const QString &text) -> FancyLineEdit::AsyncValidationFuture { return [this](const QString &text) -> FancyLineEdit::AsyncValidationFuture {
if (text.isEmpty()) { if (text.isEmpty()) {
return QtFuture::makeReadyFuture((Utils::Result<QString>( return QtFuture::makeReadyFuture((Utils::Result<QString>(
make_unexpected(Tr::tr("The path must not be empty."))))); ResultError(Tr::tr("The path must not be empty.")))));
} }
const FilePath expanded = d->expandedPath(FilePath::fromUserInput(text)); const FilePath expanded = d->expandedPath(FilePath::fromUserInput(text));
if (expanded.isEmpty()) { if (expanded.isEmpty()) {
return QtFuture::makeReadyFuture((Utils::Result<QString>( return QtFuture::makeReadyFuture((Utils::Result<QString>(
make_unexpected(Tr::tr("The path \"%1\" expanded to an empty string.") ResultError(Tr::tr("The path \"%1\" expanded to an empty string.")
.arg(expanded.toUserOutput()))))); .arg(expanded.toUserOutput())))));
} }

View File

@@ -227,7 +227,7 @@ ExecutableItem portsFromProcessRecipe(const Storage<PortsInputData> &input,
const QString stdErr = process.stdErr(); const QString stdErr = process.stdErr();
const QString outputString const QString outputString
= stdErr.isEmpty() ? stdErr : Tr::tr("Remote error output was: %1").arg(stdErr); = stdErr.isEmpty() ? stdErr : Tr::tr("Remote error output was: %1").arg(stdErr);
*output = make_unexpected(Utils::joinStrings({errorString, outputString}, '\n')); *output = ResultError(Utils::joinStrings({errorString, outputString}, '\n'));
} }
}; };
return ProcessTask(onSetup, onDone); return ProcessTask(onSetup, onDone);

View File

@@ -38,11 +38,11 @@ static Result<QList<ProcessInfo>> getLocalProcessesUsingProc(const FilePath &dev
{ {
const FilePath procDir = devicePath.withNewPath("/proc"); const FilePath procDir = devicePath.withNewPath("/proc");
if (!procDir.exists()) if (!procDir.exists())
return make_unexpected(Tr::tr("%1 does not exist").arg(procDir.toUserOutput())); return ResultError(Tr::tr("%1 does not exist").arg(procDir.toUserOutput()));
const FilePath find = devicePath.withNewPath("find").searchInPath(); const FilePath find = devicePath.withNewPath("find").searchInPath();
if (!find.isExecutableFile()) if (!find.isExecutableFile())
return make_unexpected(Tr::tr("find is not an existing executable")); return ResultError(Tr::tr("find is not an existing executable"));
static const QString execs = "-exec test -f {}/exe \\; " static const QString execs = "-exec test -f {}/exe \\; "
"-exec test -f {}/cmdline \\; " "-exec test -f {}/cmdline \\; "
@@ -63,7 +63,7 @@ static Result<QList<ProcessInfo>> getLocalProcessesUsingProc(const FilePath &dev
// We can only check the errorString here. The exit code maybe != 0 if one of the "test"s failed. // We can only check the errorString here. The exit code maybe != 0 if one of the "test"s failed.
if (!procProcess.errorString().isEmpty()) { if (!procProcess.errorString().isEmpty()) {
return make_unexpected(Tr::tr("Failed to run %1: %2") return ResultError(Tr::tr("Failed to run %1: %2")
.arg(cmd.executable().toUserOutput()) .arg(cmd.executable().toUserOutput())
.arg(procProcess.errorString())); .arg(procProcess.errorString()));
} }
@@ -116,12 +116,12 @@ static Result<QMap<qint64, QString>> getLocalProcessDataUsingPs(
process.setCommand({ps, {"-e", "-o", "pid," + column}}); process.setCommand({ps, {"-e", "-o", "pid," + column}});
process.runBlocking(); process.runBlocking();
if (!process.errorString().isEmpty()) { if (!process.errorString().isEmpty()) {
return make_unexpected( return ResultError(
Tr::tr("Failed to run %1: %2").arg(ps.toUserOutput()).arg(process.errorString())); Tr::tr("Failed to run %1: %2").arg(ps.toUserOutput()).arg(process.errorString()));
} }
if (process.exitCode() != 0) { if (process.exitCode() != 0) {
return make_unexpected(Tr::tr("Failed to run %1: %2") return ResultError(Tr::tr("Failed to run %1: %2")
.arg(ps.toUserOutput()) .arg(ps.toUserOutput())
.arg(process.readAllStandardError())); .arg(process.readAllStandardError()));
} }
@@ -144,17 +144,17 @@ static Result<QList<ProcessInfo>> getLocalProcessesUsingPs(const FilePath &devic
const FilePath ps = deviceRoot.withNewPath("ps").searchInPath(); const FilePath ps = deviceRoot.withNewPath("ps").searchInPath();
if (!ps.isExecutableFile()) if (!ps.isExecutableFile())
return make_unexpected(Tr::tr("ps is not an existing executable")); return ResultError(Tr::tr("ps is not an existing executable"));
// cmdLines are full command lines, usually with absolute path, // cmdLines are full command lines, usually with absolute path,
// exeNames only the file part of the executable's path. // exeNames only the file part of the executable's path.
const auto exeNames = getLocalProcessDataUsingPs(ps, "comm"); const auto exeNames = getLocalProcessDataUsingPs(ps, "comm");
if (!exeNames) if (!exeNames)
return make_unexpected(exeNames.error()); return ResultError(exeNames.error());
const auto cmdLines = getLocalProcessDataUsingPs(ps, "args"); const auto cmdLines = getLocalProcessDataUsingPs(ps, "args");
if (!cmdLines) if (!cmdLines)
return make_unexpected(cmdLines.error()); return ResultError(cmdLines.error());
for (auto it = exeNames->begin(), end = exeNames->end(); it != end; ++it) { for (auto it = exeNames->begin(), end = exeNames->end(); it != end; ++it) {
const qint64 pid = it.key(); const qint64 pid = it.key();
@@ -179,17 +179,17 @@ static Result<QList<ProcessInfo>> getProcessesUsingPidin(const FilePath &deviceR
{ {
const FilePath pidin = deviceRoot.withNewPath("pidin").searchInPath(); const FilePath pidin = deviceRoot.withNewPath("pidin").searchInPath();
if (!pidin.isExecutableFile()) if (!pidin.isExecutableFile())
return make_unexpected(Tr::tr("pidin is not an existing executable")); return ResultError(Tr::tr("pidin is not an existing executable"));
Process process; Process process;
process.setCommand({pidin, {"-F", "%a %A {/%n}"}}); process.setCommand({pidin, {"-F", "%a %A {/%n}"}});
process.runBlocking(); process.runBlocking();
if (process.errorString().isEmpty()) { if (process.errorString().isEmpty()) {
return make_unexpected( return ResultError(
Tr::tr("Failed to run %1: %2").arg(pidin.toUserOutput()).arg(process.errorString())); Tr::tr("Failed to run %1: %2").arg(pidin.toUserOutput()).arg(process.errorString()));
} }
if (process.exitCode() != 0) if (process.exitCode() != 0)
return make_unexpected(process.readAllStandardError()); return ResultError(process.readAllStandardError());
QList<ProcessInfo> processes; QList<ProcessInfo> processes;
QStringList lines = process.readAllStandardOutput().split(QLatin1Char('\n')); QStringList lines = process.readAllStandardOutput().split(QLatin1Char('\n'));
@@ -251,7 +251,7 @@ Result<QList<ProcessInfo>> ProcessInfo::processInfoList(const FilePath &deviceRo
pe.dwSize = sizeof(PROCESSENTRY32); pe.dwSize = sizeof(PROCESSENTRY32);
HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snapshot == INVALID_HANDLE_VALUE) { if (snapshot == INVALID_HANDLE_VALUE) {
return make_unexpected( return ResultError(
Tr::tr("Failed to create snapshot: %1").arg(winErrorMessage(GetLastError()))); Tr::tr("Failed to create snapshot: %1").arg(winErrorMessage(GetLastError())));
} }

View File

@@ -24,7 +24,7 @@ Result<> makeResult(bool ok, const QString &errorMessage)
{ {
if (ok) if (ok)
return ResultOk; return ResultOk;
return tl::make_unexpected(errorMessage); return ResultError(errorMessage);
} }
} // Utils } // Utils

View File

@@ -157,10 +157,10 @@ Result<Store> storeFromJson(const QByteArray &json)
QJsonParseError error; QJsonParseError error;
QJsonDocument doc = QJsonDocument::fromJson(json, &error); QJsonDocument doc = QJsonDocument::fromJson(json, &error);
if (error.error != QJsonParseError::NoError) if (error.error != QJsonParseError::NoError)
return make_unexpected(error.errorString()); return ResultError(error.errorString());
if (!doc.isObject()) if (!doc.isObject())
return make_unexpected(QString("Not a valid JSON object.")); return ResultError(QString("Not a valid JSON object."));
return storeFromMap(doc.toVariant().toMap()); return storeFromMap(doc.toVariant().toMap());
} }

View File

@@ -19,7 +19,7 @@ Result<FilePath> defaultShellForDevice(const FilePath &deviceRoot)
const Result<Environment> env = deviceRoot.deviceEnvironmentWithError(); const Result<Environment> env = deviceRoot.deviceEnvironmentWithError();
if (!env) if (!env)
return make_unexpected(env.error()); return ResultError(env.error());
FilePath shell = FilePath::fromUserInput(env->value_or("SHELL", "/bin/sh")); FilePath shell = FilePath::fromUserInput(env->value_or("SHELL", "/bin/sh"));
@@ -27,7 +27,7 @@ Result<FilePath> defaultShellForDevice(const FilePath &deviceRoot)
shell = env->searchInPath(shell.nativePath()); shell = env->searchInPath(shell.nativePath());
if (shell.isEmpty()) if (shell.isEmpty())
return make_unexpected(Tr::tr("Could not find any shell.")); return ResultError(Tr::tr("Could not find any shell."));
return deviceRoot.withNewMappedPath(shell); return deviceRoot.withNewMappedPath(shell);
} }

View File

@@ -206,27 +206,27 @@ Result<> TerminalInterface::startStubServer()
.arg(QCoreApplication::applicationPid()) .arg(QCoreApplication::applicationPid())
.arg(rand()))) .arg(rand())))
return {}; return {};
return make_unexpected(d->stubServer.errorString()); return ResultError(d->stubServer.errorString());
} }
// We need to put the socket in a private directory, as some systems simply do not // We need to put the socket in a private directory, as some systems simply do not
// check the file permissions of sockets. // check the file permissions of sockets.
if (!QDir(d->tempDir.path()) if (!QDir(d->tempDir.path())
.mkdir("socket")) { // QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner .mkdir("socket")) { // QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner
return make_unexpected(msgCannotCreateTempDir(d->tempDir.filePath("socket"), return ResultError(msgCannotCreateTempDir(d->tempDir.filePath("socket"),
QString::fromLocal8Bit(strerror(errno)))); QString::fromLocal8Bit(strerror(errno))));
} }
if (!QFile::setPermissions(d->tempDir.filePath("socket"), if (!QFile::setPermissions(d->tempDir.filePath("socket"),
QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner)) { QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner)) {
return make_unexpected(Tr::tr("Cannot set permissions on temporary directory \"%1\": %2") return ResultError(Tr::tr("Cannot set permissions on temporary directory \"%1\": %2")
.arg(d->tempDir.filePath("socket")) .arg(d->tempDir.filePath("socket"))
.arg(QString::fromLocal8Bit(strerror(errno)))); .arg(QString::fromLocal8Bit(strerror(errno))));
} }
const QString socketPath = d->tempDir.filePath("socket/stub-socket"); const QString socketPath = d->tempDir.filePath("socket/stub-socket");
if (!d->stubServer.listen(socketPath)) { if (!d->stubServer.listen(socketPath)) {
return make_unexpected( return ResultError(
Tr::tr("Cannot create socket \"%1\": %2").arg(socketPath, d->stubServer.errorString())); Tr::tr("Cannot create socket \"%1\": %2").arg(socketPath, d->stubServer.errorString()));
} }
return {}; return {};

View File

@@ -364,7 +364,7 @@ Result<Theme::Color> Theme::colorToken(const QString &tokenName,
bool ok = false; bool ok = false;
const Color result = static_cast<Color>(colorEnum.keyToValue(colorName.toLatin1(), &ok)); const Color result = static_cast<Color>(colorEnum.keyToValue(colorName.toLatin1(), &ok));
if (!ok) if (!ok)
return make_unexpected(QString::fromLatin1("%1 - Color token \"%2\" not found.") return ResultError(QString::fromLatin1("%1 - Color token \"%2\" not found.")
.arg(Q_FUNC_INFO).arg(tokenName)); .arg(Q_FUNC_INFO).arg(tokenName));
return result; return result;
} }

View File

@@ -114,14 +114,14 @@ enum OpenSslValidation {
static Result<> testJavaC(const FilePath &jdkPath) static Result<> testJavaC(const FilePath &jdkPath)
{ {
if (!jdkPath.isReadableDir()) if (!jdkPath.isReadableDir())
return make_unexpected(Tr::tr("The selected path does not exist or is not readable.")); return ResultError(Tr::tr("The selected path does not exist or is not readable."));
const QString javacCommand("javac"); const QString javacCommand("javac");
const QString versionParameter("-version"); const QString versionParameter("-version");
const FilePath bin = jdkPath / "bin" / (javacCommand + QTC_HOST_EXE_SUFFIX); const FilePath bin = jdkPath / "bin" / (javacCommand + QTC_HOST_EXE_SUFFIX);
if (!bin.isExecutableFile()) if (!bin.isExecutableFile())
return make_unexpected( return ResultError(
Tr::tr("Could not find \"%1\" in the selected path.") Tr::tr("Could not find \"%1\" in the selected path.")
.arg(bin.toUserOutput())); .arg(bin.toUserOutput()));
@@ -136,20 +136,20 @@ static Result<> testJavaC(const FilePath &jdkPath)
const QString stdOut = javacProcess.stdOut().trimmed(); const QString stdOut = javacProcess.stdOut().trimmed();
if (javacProcess.exitCode() != 0) if (javacProcess.exitCode() != 0)
return make_unexpected( return ResultError(
Tr::tr("The selected path does not contain a valid JDK. (%1 failed: %2)") Tr::tr("The selected path does not contain a valid JDK. (%1 failed: %2)")
.arg(cmd.toUserOutput(), stdOut)); .arg(cmd.toUserOutput(), stdOut));
// We expect "javac <version>" where <version> is "major.minor.patch" // We expect "javac <version>" where <version> is "major.minor.patch"
const QString outputPrefix = javacCommand + " "; const QString outputPrefix = javacCommand + " ";
if (!stdOut.startsWith(outputPrefix)) if (!stdOut.startsWith(outputPrefix))
return make_unexpected(Tr::tr("Unexpected output from \"%1\": %2") return ResultError(Tr::tr("Unexpected output from \"%1\": %2")
.arg(cmd.toUserOutput(), stdOut)); .arg(cmd.toUserOutput(), stdOut));
jdkVersion = QVersionNumber::fromString(stdOut.mid(outputPrefix.length()).split('\n').first()); jdkVersion = QVersionNumber::fromString(stdOut.mid(outputPrefix.length()).split('\n').first());
if (jdkVersion.isNull() /* || jdkVersion.majorVersion() != requiredJavaMajorVersion */ ) { if (jdkVersion.isNull() /* || jdkVersion.majorVersion() != requiredJavaMajorVersion */ ) {
return make_unexpected(Tr::tr("Unsupported JDK version (needs to be %1): %2 (parsed: %3)") return ResultError(Tr::tr("Unsupported JDK version (needs to be %1): %2 (parsed: %3)")
.arg(requiredJavaMajorVersion) .arg(requiredJavaMajorVersion)
.arg(stdOut, jdkVersion.toString())); .arg(stdOut, jdkVersion.toString()));
} }
@@ -260,7 +260,7 @@ AndroidSettingsWidget::AndroidSettingsWidget()
Result<> test = testJavaC(FilePath::fromUserInput(s)); Result<> test = testJavaC(FilePath::fromUserInput(s));
if (!test) { if (!test) {
Core::MessageManager::writeSilently(test.error()); Core::MessageManager::writeSilently(test.error());
return make_unexpected(test.error()); return ResultError(test.error());
} }
return s; return s;
}); });

View File

@@ -892,7 +892,7 @@ Group dashboardInfoRecipe(const DashboardInfoHandler &handler)
if (result == DoneWith::Success && dd->m_dashboardInfo) if (result == DoneWith::Success && dd->m_dashboardInfo)
handler(*dd->m_dashboardInfo); handler(*dd->m_dashboardInfo);
else else
handler(make_unexpected(QString("Error"))); // TODO: Collect error message in the storage. handler(ResultError("Error")); // TODO: Collect error message in the storage.
}; };
const Group root { const Group root {

View File

@@ -332,7 +332,7 @@ Utils::FilePath findConfig(const Utils::FilePath &filePath)
return {}; return {};
} }
ICodeStylePreferences *preferencesForFile(const Utils::FilePath &filePath) ICodeStylePreferences *preferencesForFile(const FilePath &filePath)
{ {
const ProjectExplorer::Project *project = ProjectExplorer::ProjectManager::projectForFile( const ProjectExplorer::Project *project = ProjectExplorer::ProjectManager::projectForFile(
filePath); filePath);
@@ -342,7 +342,7 @@ ICodeStylePreferences *preferencesForFile(const Utils::FilePath &filePath)
: TextEditor::TextEditorSettings::codeStyle("Cpp")->currentPreferences(); : TextEditor::TextEditorSettings::codeStyle("Cpp")->currentPreferences();
} }
Utils::FilePath configForFile(const Utils::FilePath &filePath) FilePath configForFile(const FilePath &filePath)
{ {
if (!getCurrentCustomSettings(filePath)) if (!getCurrentCustomSettings(filePath))
return findConfig(filePath); return findConfig(filePath);
@@ -409,14 +409,14 @@ void addQtcStatementMacros(clang::format::FormatStyle &style)
} }
} }
Utils::FilePath filePathToCurrentSettings(const TextEditor::ICodeStylePreferences *codeStyle) FilePath filePathToCurrentSettings(const TextEditor::ICodeStylePreferences *codeStyle)
{ {
return Core::ICore::userResourcePath() / "clang-format/" return Core::ICore::userResourcePath() / "clang-format/"
/ Utils::FileUtils::fileSystemFriendlyName(codeStyle->displayName()) / Utils::FileUtils::fileSystemFriendlyName(codeStyle->displayName())
/ QLatin1String(Constants::SETTINGS_FILE_NAME); / QLatin1String(Constants::SETTINGS_FILE_NAME);
} }
Utils::Result<> parseConfigurationContent(const std::string &fileContent, Result<> parseConfigurationContent(const std::string &fileContent,
clang::format::FormatStyle &style, clang::format::FormatStyle &style,
bool allowUnknownOptions) bool allowUnknownOptions)
{ {
@@ -439,12 +439,11 @@ Utils::Result<> parseConfigurationContent(const std::string &fileContent,
errorMessage = errorMessage.trimmed().isEmpty() ? QString::fromStdString(error.message()) errorMessage = errorMessage.trimmed().isEmpty() ? QString::fromStdString(error.message())
: errorMessage; : errorMessage;
if (error) if (error)
return make_unexpected(errorMessage); return ResultError(errorMessage);
return {}; return ResultOk;
} }
Utils::Result<> parseConfigurationFile(const Utils::FilePath &filePath, Result<> parseConfigurationFile(const FilePath &filePath, clang::format::FormatStyle &style)
clang::format::FormatStyle &style)
{ {
return parseConfigurationContent(filePath.fileContents().value_or(QByteArray()).toStdString(), return parseConfigurationContent(filePath.fileContents().value_or(QByteArray()).toStdString(),
style, true); style, true);

View File

@@ -169,20 +169,20 @@ public:
private: private:
const YAML::Node &m_node; const YAML::Node &m_node;
FileCache &m_fileCache; FileCache &m_fileCache;
Utils::FilePath m_filePath; FilePath m_filePath;
const char *m_fileOffsetKey = nullptr; const char *m_fileOffsetKey = nullptr;
int m_extraOffset = 0; int m_extraOffset = 0;
}; };
} // namespace } // namespace
void parseDiagnostics(QPromise<Utils::Result<Diagnostics>> &promise, void parseDiagnostics(QPromise<Result<Diagnostics>> &promise,
const Utils::FilePath &logFilePath, const FilePath &logFilePath,
const AcceptDiagsFromFilePath &acceptFromFilePath) const AcceptDiagsFromFilePath &acceptFromFilePath)
{ {
const Utils::Result<QByteArray> localFileContents = logFilePath.fileContents(); const Result<QByteArray> localFileContents = logFilePath.fileContents();
if (!localFileContents.has_value()) { if (!localFileContents.has_value()) {
promise.addResult(Utils::make_unexpected(localFileContents.error())); promise.addResult(ResultError(localFileContents.error()));
promise.future().cancel(); promise.future().cancel();
return; return;
} }

View File

@@ -418,14 +418,14 @@ static Result<bool> insertSnippetSilently(const FilePath &cmakeFile,
Constants::CMAKE_EDITOR_ID, Constants::CMAKE_EDITOR_ID,
Core::EditorManager::DoNotMakeVisible | Core::EditorManager::DoNotChangeCurrentEditor)); Core::EditorManager::DoNotMakeVisible | Core::EditorManager::DoNotChangeCurrentEditor));
if (!editor) { if (!editor) {
return make_unexpected("BaseTextEditor cannot be obtained for " + cmakeFile.toUserOutput() return ResultError("BaseTextEditor cannot be obtained for " + cmakeFile.toUserOutput()
+ ":" + QString::number(snippetLocation.line) + ":" + ":" + QString::number(snippetLocation.line) + ":"
+ QString::number(snippetLocation.column)); + QString::number(snippetLocation.column));
} }
editor->insert(snippetLocation.snippet); editor->insert(snippetLocation.snippet);
editor->editorWidget()->autoIndent(); editor->editorWidget()->autoIndent();
if (!Core::DocumentManager::saveDocument(editor->document())) if (!Core::DocumentManager::saveDocument(editor->document()))
return make_unexpected("Changes to " + cmakeFile.toUserOutput() + " could not be saved."); return ResultError("Changes to " + cmakeFile.toUserOutput() + " could not be saved.");
return true; return true;
} }

View File

@@ -703,7 +703,7 @@ static Result<FilePath> clangBinary(
if (!fromPath.isEmpty()) if (!fromPath.isEmpty())
return fromPath; return fromPath;
return make_unexpected(Tr::tr("Could not find %1 executable in %2") return ResultError(Tr::tr("Could not find %1 executable in %2")
.arg(binaryBaseName) .arg(binaryBaseName)
.arg(clangBinDirectory.toUserOutput())); .arg(clangBinDirectory.toUserOutput()));
} }

View File

@@ -127,16 +127,16 @@ struct SavedEntry
QtMsgType level{QtFatalMsg}; QtMsgType level{QtFatalMsg};
std::optional<std::array<bool, 5>> levels; std::optional<std::array<bool, 5>> levels;
static Utils::Result<SavedEntry> fromJson(const QJsonObject &obj) static Result<SavedEntry> fromJson(const QJsonObject &obj)
{ {
if (!obj.contains("name")) if (!obj.contains("name"))
return Utils::make_unexpected(Tr::tr("Entry is missing a logging category name.")); return ResultError(Tr::tr("Entry is missing a logging category name."));
SavedEntry result; SavedEntry result;
result.name = obj.value("name").toString(); result.name = obj.value("name").toString();
if (!obj.contains("entry")) if (!obj.contains("entry"))
return Utils::make_unexpected(Tr::tr("Entry is missing data.")); return ResultError(Tr::tr("Entry is missing data."));
auto entry = obj.value("entry").toObject(); auto entry = obj.value("entry").toObject();
if (entry.contains("color")) if (entry.contains("color"))
@@ -145,7 +145,7 @@ struct SavedEntry
if (entry.contains("level")) { if (entry.contains("level")) {
int lvl = entry.value("level").toInt(0); int lvl = entry.value("level").toInt(0);
if (lvl < QtDebugMsg || lvl > QtInfoMsg) if (lvl < QtDebugMsg || lvl > QtInfoMsg)
return Utils::make_unexpected(Tr::tr("Invalid level: %1").arg(lvl)); return ResultError(Tr::tr("Invalid level: %1").arg(lvl));
result.level = static_cast<QtMsgType>(lvl); result.level = static_cast<QtMsgType>(lvl);
} }
@@ -706,7 +706,7 @@ LoggingViewManagerWidget::LoggingViewManagerWidget(QWidget *parent)
if (re.isValid()) if (re.isValid())
return input; return input;
return Utils::make_unexpected( return ResultError(
Tr::tr("Invalid regular expression: %1").arg(re.errorString())); Tr::tr("Invalid regular expression: %1").arg(re.errorString()));
}); });
}); });

View File

@@ -148,7 +148,7 @@ static Result<std::unique_ptr<PluginSpec>> checkPlugin(
const Result<> ok = checkPlugin(spec->get(), update); const Result<> ok = checkPlugin(spec->get(), update);
if (ok) if (ok)
return spec; return spec;
return Utils::make_unexpected(ok.error()); return ResultError(ok.error());
} }
// Async. Result is set if any issue was found. // Async. Result is set if any issue was found.
@@ -156,11 +156,11 @@ void checkContents(QPromise<CheckResult> &promise, const FilePath &tempDir, bool
{ {
QList<PluginSpec *> plugins = pluginSpecsFromArchive(tempDir); QList<PluginSpec *> plugins = pluginSpecsFromArchive(tempDir);
if (plugins.isEmpty()) { if (plugins.isEmpty()) {
promise.addResult(Utils::make_unexpected(Tr::tr("No plugins found."))); promise.addResult(ResultError(Tr::tr("No plugins found.")));
return; return;
} }
if (plugins.size() > 1) { if (plugins.size() > 1) {
promise.addResult(Utils::make_unexpected(Tr::tr("More than one plugin found."))); promise.addResult(ResultError(Tr::tr("More than one plugin found.")));
qDeleteAll(plugins); qDeleteAll(plugins);
return; return;
} }
@@ -168,7 +168,7 @@ void checkContents(QPromise<CheckResult> &promise, const FilePath &tempDir, bool
PluginSpec *plugin = plugins.front(); PluginSpec *plugin = plugins.front();
const Result<> ok = checkPlugin(plugin, update); const Result<> ok = checkPlugin(plugin, update);
if (!ok) { if (!ok) {
promise.addResult(Utils::make_unexpected(ok.error())); promise.addResult(ResultError(ok.error()));
delete plugin; delete plugin;
return; return;
} }

View File

@@ -54,7 +54,7 @@ static Result<QString> fetchVersionOutput(const FilePath &executable, Environmen
proc.runBlocking(); proc.runBlocking();
QString output = proc.allOutput().trimmed(); QString output = proc.allOutput().trimmed();
if (proc.result() != ProcessResult::FinishedWithSuccess) if (proc.result() != ProcessResult::FinishedWithSuccess)
return make_unexpected(output); return ResultError(output);
return output; return output;
} }
@@ -154,11 +154,11 @@ static Utils::Result<DebuggerItem::TechnicalData> extractLldbTechnicalData(
binaryName.replace(dapServerSuffix, QString{}); binaryName.replace(dapServerSuffix, QString{});
const FilePath lldb = fromExecutable.parentDir() / binaryName; const FilePath lldb = fromExecutable.parentDir() / binaryName;
if (!lldb.exists()) { if (!lldb.exists()) {
return make_unexpected(QString{"%1 does not exist alongside %2"} return ResultError(QString{"%1 does not exist alongside %2"}
.arg(lldb.fileNameView(), fromExecutable.toUserOutput())); .arg(lldb.fileNameView(), fromExecutable.toUserOutput()));
} }
if (!lldb.isExecutableFile()) { if (!lldb.isExecutableFile()) {
return make_unexpected(QString{"%1 exists alongside %2 but is not executable"} return ResultError(QString{"%1 exists alongside %2 but is not executable"}
.arg(lldb.fileNameView(), fromExecutable.toUserOutput())); .arg(lldb.fileNameView(), fromExecutable.toUserOutput()));
} }
@@ -190,8 +190,8 @@ const char DEBUGGER_INFORMATION_WORKINGDIRECTORY[] = "WorkingDirectory";
// DebuggerItem // DebuggerItem
// -------------------------------------------------------------------------- // --------------------------------------------------------------------------
Utils::Result<DebuggerItem::TechnicalData> DebuggerItem::TechnicalData::extract( Result<DebuggerItem::TechnicalData> DebuggerItem::TechnicalData::extract(
const FilePath &fromExecutable, const std::optional<Utils::Environment> &customEnvironment) const FilePath &fromExecutable, const std::optional<Environment> &customEnvironment)
{ {
Environment env = customEnvironment.value_or(fromExecutable.deviceEnvironment()); Environment env = customEnvironment.value_or(fromExecutable.deviceEnvironment());
DebuggerItem::addAndroidLldbPythonEnv(fromExecutable, env); DebuggerItem::addAndroidLldbPythonEnv(fromExecutable, env);
@@ -212,7 +212,7 @@ Utils::Result<DebuggerItem::TechnicalData> DebuggerItem::TechnicalData::extract(
WinDLLFileVersion, fromExecutable.absoluteFilePath().path(), &errorMessage); WinDLLFileVersion, fromExecutable.absoluteFilePath().path(), &errorMessage);
if (!errorMessage.isEmpty()) if (!errorMessage.isEmpty())
return make_unexpected(std::move(errorMessage)); return ResultError(std::move(errorMessage));
return DebuggerItem::TechnicalData{ return DebuggerItem::TechnicalData{
.engineType = UvscEngineType, .engineType = UvscEngineType,
@@ -223,7 +223,7 @@ Utils::Result<DebuggerItem::TechnicalData> DebuggerItem::TechnicalData::extract(
const Result<QString> output = fetchVersionOutput(fromExecutable, env); const Result<QString> output = fetchVersionOutput(fromExecutable, env);
if (!output) { if (!output) {
return make_unexpected(output.error()); return ResultError(output.error());
} }
if (output->contains("gdb")) { if (output->contains("gdb")) {
@@ -267,7 +267,7 @@ Utils::Result<DebuggerItem::TechnicalData> DebuggerItem::TechnicalData::extract(
}; };
} }
return make_unexpected( return ResultError(
QString{"Failed to determine debugger engine type from '%1'"}.arg(*output)); QString{"Failed to determine debugger engine type from '%1'"}.arg(*output));
} }

View File

@@ -221,12 +221,12 @@ public:
Result<FilePath> cmdBridgePath = getCmdBridgePath(); Result<FilePath> cmdBridgePath = getCmdBridgePath();
if (!cmdBridgePath) if (!cmdBridgePath)
return make_unexpected(cmdBridgePath.error()); return ResultError(cmdBridgePath.error());
auto fAccess = std::make_unique<DockerDeviceFileAccess>(this); auto fAccess = std::make_unique<DockerDeviceFileAccess>(this);
if (auto result = updateContainerAccess(); !result) if (auto result = updateContainerAccess(); !result)
return make_unexpected(result.error()); return ResultError(result.error());
Result<> initResult = ResultOk; Result<> initResult = ResultOk;
if (cmdBridgePath->isSameDevice(Docker::Internal::settings().dockerBinaryPath())) { if (cmdBridgePath->isSameDevice(Docker::Internal::settings().dockerBinaryPath())) {
@@ -237,7 +237,7 @@ public:
= fAccess->deployAndInit(Core::ICore::libexecPath(), q->rootPath(), q->environment()); = fAccess->deployAndInit(Core::ICore::libexecPath(), q->rootPath(), q->environment());
} }
if (!initResult) if (!initResult)
return make_unexpected(initResult.error()); return ResultError(initResult.error());
return fAccess; return fAccess;
} }
@@ -548,7 +548,7 @@ Result<Environment> DockerDevicePrivate::fetchEnvironment() const
envCaptureProcess.setWriteData("printenv\n"); envCaptureProcess.setWriteData("printenv\n");
envCaptureProcess.runBlocking(); envCaptureProcess.runBlocking();
if (envCaptureProcess.result() != ProcessResult::FinishedWithSuccess) { if (envCaptureProcess.result() != ProcessResult::FinishedWithSuccess) {
return make_unexpected(envCaptureProcess.readAllStandardError()); return ResultError(envCaptureProcess.readAllStandardError());
} }
const QStringList envLines = QString::fromUtf8(envCaptureProcess.readAllRawStandardOutput()) const QStringList envLines = QString::fromUtf8(envCaptureProcess.readAllRawStandardOutput())
.split('\n', Qt::SkipEmptyParts); .split('\n', Qt::SkipEmptyParts);