FilePath: Remove ::toDir() and deprecation hints

Change-Id: Ib561c019e3fd44cd85504ad4286eb3759ce19516
Reviewed-by: hjk <hjk@qt.io>
This commit is contained in:
Marcus Tillmanns
2022-07-28 15:59:52 +02:00
parent 783f0e1205
commit 451d02c88d
14 changed files with 101 additions and 106 deletions

View File

@@ -153,7 +153,7 @@ Qt::CaseSensitivity FilePath::caseSensitivity() const
// FIXME: This could or possibly should the target device's file name case sensitivity // FIXME: This could or possibly should the target device's file name case sensitivity
// into account by diverting to IDevice. However, as this is expensive and we are // into account by diverting to IDevice. However, as this is expensive and we are
// in time-critical path here, we go with "good enough" for now: // in time-critical path here, we go with "good enough" for now:
// The first approximation is "Anything unusual is not case sensitive" // The first approximation is "most things are case-sensitive".
return Qt::CaseSensitive; return Qt::CaseSensitive;
} }
@@ -387,6 +387,16 @@ FilePath FilePath::fromUrl(const QUrl &url)
return fn; return fn;
} }
FilePath FilePath::currentWorkingPath()
{
return FilePath::fromString(QDir::currentPath());
}
FilePath FilePath::rootPath()
{
return FilePath::fromString(QDir::rootPath());
}
static QString hostEncoded(QString host) static QString hostEncoded(QString host)
{ {
host.replace('%', "%25"); host.replace('%', "%25");
@@ -839,6 +849,7 @@ FilePath FilePath::parentDir() const
if (basePath.isEmpty()) if (basePath.isEmpty())
return FilePath(); return FilePath();
// TODO: Replace usage of QDir !!
const QDir base(basePath); const QDir base(basePath);
if (base.isRoot()) if (base.isRoot())
return FilePath(); return FilePath();
@@ -854,22 +865,16 @@ FilePath FilePath::parentDir() const
FilePath FilePath::absolutePath() const FilePath FilePath::absolutePath() const
{ {
if (isAbsolutePath()) const FilePath parentPath = isAbsolutePath() ? parentDir() : FilePath::currentWorkingPath().resolvePath(*this).parentDir();
return parentDir(); return parentPath.isEmpty() ? *this : parentPath;
QTC_ASSERT(!needsDevice(), return *this);
FilePath result = *this;
result.m_data = QFileInfo(m_data).absolutePath();
return result;
} }
FilePath FilePath::absoluteFilePath() const FilePath FilePath::absoluteFilePath() const
{ {
if (isAbsolutePath()) if (isAbsolutePath())
return *this; return *this;
QTC_ASSERT(!needsDevice(), return *this);
FilePath result = *this; return FilePath::currentWorkingPath().resolvePath(*this);
result.m_data = QFileInfo(m_data).absoluteFilePath();
return result;
} }
QString FilePath::specialPath(SpecialPathComponent component) QString FilePath::specialPath(SpecialPathComponent component)
@@ -1102,11 +1107,6 @@ QVariant FilePath::toVariant() const
return toString(); return toString();
} }
QDir FilePath::toDir() const
{
return QDir(m_data);
}
bool FilePath::operator==(const FilePath &other) const bool FilePath::operator==(const FilePath &other) const
{ {
return QString::compare(m_data, other.m_data, caseSensitivity()) == 0 return QString::compare(m_data, other.m_data, caseSensitivity()) == 0

View File

@@ -79,6 +79,10 @@ public:
[[nodiscard]] static FilePath fromVariant(const QVariant &variant); [[nodiscard]] static FilePath fromVariant(const QVariant &variant);
[[nodiscard]] static FilePath fromUrl(const QUrl &url); [[nodiscard]] static FilePath fromUrl(const QUrl &url);
[[nodiscard]] static FilePath currentWorkingPath();
[[nodiscard]] static FilePath rootPath();
QString toUserOutput() const; QString toUserOutput() const;
QString toString() const; QString toString() const;
QString toFSPathString() const; QString toFSPathString() const;
@@ -156,6 +160,8 @@ public:
size_t hash(uint seed) const; size_t hash(uint seed) const;
[[nodiscard]] FilePath absoluteFilePath() const;
[[nodiscard]] FilePath absolutePath() const;
[[nodiscard]] FilePath resolvePath(const FilePath &tail) const; [[nodiscard]] FilePath resolvePath(const FilePath &tail) const;
[[nodiscard]] FilePath resolvePath(const QString &tail) const; [[nodiscard]] FilePath resolvePath(const QString &tail) const;
[[nodiscard]] FilePath cleanPath() const; [[nodiscard]] FilePath cleanPath() const;
@@ -206,12 +212,8 @@ public:
// on FilePath::osType(). // on FilePath::osType().
bool needsDevice() const; bool needsDevice() const;
// Deprecated. [[nodiscard]] QFileInfo toFileInfo() const;
[[nodiscard]] static FilePath fromFileInfo(const QFileInfo &info); // Avoid. [[nodiscard]] static FilePath fromFileInfo(const QFileInfo &info);
[[nodiscard]] QFileInfo toFileInfo() const; // Avoid.
[[nodiscard]] QDir toDir() const; // Avoid.
[[nodiscard]] FilePath absolutePath() const; // Avoid. Use resolvePath(...)[.parent()] with proper base.
[[nodiscard]] FilePath absoluteFilePath() const; // Avoid. Use resolvePath(...) with proper base.
enum class SpecialPathComponent { enum class SpecialPathComponent {
RootName, RootName,

View File

@@ -632,12 +632,15 @@ void ExternalToolConfig::showInfoForItem(const QModelIndex &index)
static FilePath getUserFilePath(const QString &proposalFileName) static FilePath getUserFilePath(const QString &proposalFileName)
{ {
const QDir resourceDir(ICore::userResourcePath().toDir()); const FilePath resourceDir(ICore::userResourcePath());
if (!resourceDir.exists(QLatin1String("externaltools"))) const FilePath externalToolsDir = resourceDir / "externalTools";
resourceDir.mkpath(QLatin1String("externaltools")); if (!externalToolsDir.isDir())
const QFileInfo fi(proposalFileName); externalToolsDir.createDir();
const QString &suffix = QLatin1Char('.') + fi.completeSuffix();
const FilePath newFilePath = ICore::userResourcePath("externaltools") / fi.baseName(); const FilePath proposal = FilePath::fromString(proposalFileName);
const QString suffix = QLatin1Char('.') + proposal.suffix();
const FilePath newFilePath = externalToolsDir / proposal.baseName();
int count = 0; int count = 0;
FilePath tryPath = newFilePath + suffix; FilePath tryPath = newFilePath + suffix;
while (tryPath.exists()) { while (tryPath.exists()) {

View File

@@ -180,13 +180,14 @@ void GeneralSettingsWidget::fillLanguageBox() const
m_languageBox->setCurrentIndex(m_languageBox->count() - 1); m_languageBox->setCurrentIndex(m_languageBox->count() - 1);
const FilePath creatorTrPath = ICore::resourcePath("translations"); const FilePath creatorTrPath = ICore::resourcePath("translations");
const QStringList languageFiles = creatorTrPath.toDir().entryList( const FilePaths languageFiles = creatorTrPath.dirEntries(
QStringList(QLatin1String("qtcreator*.qm"))); QStringList(QLatin1String("qtcreator*.qm")));
for (const QString &languageFile : languageFiles) { for (const FilePath &languageFile : languageFiles) {
int start = languageFile.indexOf('_') + 1; const QString path = languageFile.path();
int end = languageFile.lastIndexOf('.'); int start = path.indexOf('_') + 1;
const QString locale = languageFile.mid(start, end-start); int end = path.lastIndexOf('.');
const QString locale = path.mid(start, end-start);
// no need to show a language that creator will not load anyway // no need to show a language that creator will not load anyway
if (hasQmFilesForLocale(locale, creatorTrPath.toString())) { if (hasQmFilesForLocale(locale, creatorTrPath.toString())) {
QLocale tmpLocale(locale); QLocale tmpLocale(locale);

View File

@@ -182,12 +182,12 @@ void GeneratedFile::setEditorId(Id id)
bool GeneratedFile::write(QString *errorMessage) const bool GeneratedFile::write(QString *errorMessage) const
{ {
// Ensure the directory // Ensure the directory
const QDir dir = m_d->path.parentDir().toDir(); const FilePath parentDir = m_d->path.parentDir();
if (!dir.exists()) { if (!parentDir.isDir()) {
if (!dir.mkpath(dir.absolutePath())) { if (!parentDir.createDir()) {
*errorMessage = QCoreApplication::translate("BaseFileWizard", *errorMessage = QCoreApplication::translate("BaseFileWizard",
"Unable to create the directory %1.") "Unable to create the directory %1.")
.arg(QDir::toNativeSeparators(dir.absolutePath())); .arg(parentDir.toUserOutput());
return false; return false;
} }
} }

View File

@@ -257,8 +257,7 @@ void ProjectExplorer::ProjectExplorerPlugin::testJsonWizardsComboBox()
static QString iconInsideResource(const QString &relativePathToIcon) static QString iconInsideResource(const QString &relativePathToIcon)
{ {
const QDir resourcePath(Core::ICore::resourcePath().toDir()); return Core::ICore::resourcePath().resolvePath(relativePathToIcon).toString();
return resourcePath.filePath(relativePathToIcon);
} }
void ProjectExplorer::ProjectExplorerPlugin::testJsonWizardsIconList() void ProjectExplorer::ProjectExplorerPlugin::testJsonWizardsIconList()

View File

@@ -70,7 +70,7 @@ static FolderNode *recursiveFindOrCreateFolderNode(FolderNode *folder,
Utils::FilePath directoryWithoutPrefix; Utils::FilePath directoryWithoutPrefix;
bool isRelative = false; bool isRelative = false;
if (path.isEmpty() || path.toDir().isRoot()) { if (path.isEmpty() || path == FilePath::rootPath()) {
directoryWithoutPrefix = directory; directoryWithoutPrefix = directory;
isRelative = false; isRelative = false;
} else { } else {

View File

@@ -32,9 +32,11 @@
#include <richtexteditor/richtexteditor.h> #include <richtexteditor/richtexteditor.h>
#include <projectexplorer/target.h> #include <projectexplorer/target.h>
#include <qmlprojectmanager/qmlproject.h> #include <qmlprojectmanager/qmlproject.h>
#include <utils/qtcassert.h>
#include <QCryptographicHash> #include <QCryptographicHash>
using namespace Utils;
namespace QmlDesigner { namespace QmlDesigner {
AnnotationCommentTab::AnnotationCommentTab(QWidget *parent) AnnotationCommentTab::AnnotationCommentTab(QWidget *parent)
@@ -53,7 +55,8 @@ AnnotationCommentTab::AnnotationCommentTab(QWidget *parent)
const QmlDesigner::DesignDocument *designDocument = QmlDesigner::QmlDesignerPlugin::instance() const QmlDesigner::DesignDocument *designDocument = QmlDesigner::QmlDesignerPlugin::instance()
->documentManager().currentDesignDocument(); ->documentManager().currentDesignDocument();
Utils::FilePath projectPath;
FilePath projectPath;
Q_ASSERT(designDocument); Q_ASSERT(designDocument);
@@ -142,7 +145,8 @@ QString AnnotationCommentTab::backupFile(const QString &filePath)
{ {
const QmlDesigner::DesignDocument *designDocument = QmlDesigner::QmlDesignerPlugin::instance() const QmlDesigner::DesignDocument *designDocument = QmlDesigner::QmlDesignerPlugin::instance()
->documentManager().currentDesignDocument(); ->documentManager().currentDesignDocument();
Utils::FilePath projectFolderPath;
FilePath projectFolderPath;
Q_ASSERT(designDocument); Q_ASSERT(designDocument);
@@ -155,43 +159,35 @@ QString AnnotationCommentTab::backupFile(const QString &filePath)
else else
return {}; return {};
const QDir projDir(projectFolderPath.toDir()); if (!projectFolderPath.isDir())
if (!projDir.exists())
return {}; return {};
const QString imageSubDir(".AnnotationImages"); const QString imageSubDir(".AnnotationImages");
const QDir imgDir(projDir.absolutePath() + QDir::separator() + imageSubDir); const FilePath imgDir(projectFolderPath / imageSubDir);
ensureDir(imgDir);
Q_ASSERT(imgDir.exists());
if (!imgDir.exists()) if (!imgDir.exists())
return {}; imgDir.createDir();
const QFileInfo oldFile(filePath); QTC_ASSERT(imgDir.isDir(), return {});
QFileInfo newFile(imgDir, oldFile.fileName());
QString newName = newFile.baseName() + "_%1." + newFile.completeSuffix(); const FilePath oldFile = FilePath::fromString(filePath);
FilePath newFile = imgDir.resolvePath(oldFile.fileName());
QString newNameTemplate = newFile.baseName() + "_%1." + newFile.completeSuffix();
for (size_t i = 1; true; ++i) { for (size_t i = 1; true; ++i) {
if (!newFile.exists()) { if (!newFile.exists()) {
QFile(oldFile.absoluteFilePath()).copy(newFile.absoluteFilePath()); oldFile.copyFile(newFile);
break; break;
} else if (compareFileChecksum(oldFile.absoluteFilePath(), newFile.absoluteFilePath()) == 0) } else if (compareFileChecksum(oldFile.absoluteFilePath().toString(), newFile.absoluteFilePath().toString()) == 0)
break; break;
newFile.setFile(imgDir, newName.arg(i)); newFile = imgDir / newNameTemplate.arg(i);
} }
return projDir.relativeFilePath(newFile.absoluteFilePath()); return newFile.relativeChildPath(projectFolderPath).toString();
} }
void AnnotationCommentTab::ensureDir(const QDir &dir)
{
if (!dir.exists())
dir.mkdir(".");
}
int AnnotationCommentTab::compareFileChecksum(const QString &firstFile, const QString &secondFile) int AnnotationCommentTab::compareFileChecksum(const QString &firstFile, const QString &secondFile)
{ {

View File

@@ -69,7 +69,6 @@ signals:
private: private:
QString backupFile(const QString &filePath); QString backupFile(const QString &filePath);
void ensureDir(const QDir &dir);
int compareFileChecksum(const QString &firstFile, const QString &secondFile); int compareFileChecksum(const QString &firstFile, const QString &secondFile);
private: private:

View File

@@ -494,11 +494,11 @@ public:
minorVersion = importInfo.version().minorVersion(); minorVersion = importInfo.version().minorVersion();
typeName.prepend(name + QLatin1Char('.')); typeName.prepend(name + QLatin1Char('.'));
} else if (importInfo.isValid() && importInfo.type() == ImportType::Directory) { } else if (importInfo.isValid() && importInfo.type() == ImportType::Directory) {
QString path = importInfo.path(); const Utils::FilePath path = Utils::FilePath::fromString(importInfo.path());
QDir dir = m_doc->path().toDir(); const Utils::FilePath dir = m_doc->path();
// should probably try to make it relatve to some import path, not to the document path // should probably try to make it relative to some import path, not to the document path
QString relativeDir = dir.relativeFilePath(path); const Utils::FilePath relativePath = path.relativeChildPath(dir);
QString name = relativeDir.replace(QLatin1Char('/'), QLatin1Char('.')); QString name = relativePath.path().replace(QLatin1Char('/'), QLatin1Char('.'));
if (!name.isEmpty() && name != QLatin1String(".")) if (!name.isEmpty() && name != QLatin1String("."))
typeName.prepend(name + QLatin1Char('.')); typeName.prepend(name + QLatin1Char('.'));
} else if (importInfo.isValid() && importInfo.type() == ImportType::QrcDirectory) { } else if (importInfo.isValid() && importInfo.type() == ImportType::QrcDirectory) {

View File

@@ -124,11 +124,11 @@ static inline QString getModuleName(const ScopeChain &scopeChain, const Document
return moduleName + QString::number(majorVersion) + QLatin1Char('.') return moduleName + QString::number(majorVersion) + QLatin1Char('.')
+ QString::number(minorVersion) ; + QString::number(minorVersion) ;
} else if (importInfo.isValid() && importInfo.type() == ImportType::Directory) { } else if (importInfo.isValid() && importInfo.type() == ImportType::Directory) {
const QString path = importInfo.path(); const Utils::FilePath path = Utils::FilePath::fromString(importInfo.path());
const QDir dir = qmlDocument->path().toDir(); const Utils::FilePath dir = qmlDocument->path();
// should probably try to make it relatve to some import path, not to the document path // should probably try to make it relatve to some import path, not to the document path
QString relativeDir = dir.relativeFilePath(path); const Utils::FilePath relativePath = path.relativeChildPath(dir);
const QString name = relativeDir.replace(QLatin1Char('/'), QLatin1Char('.')); const QString name = relativePath.path().replace(QLatin1Char('/'), QLatin1Char('.'));
return name; return name;
} else if (importInfo.isValid() && importInfo.type() == ImportType::QrcDirectory) { } else if (importInfo.isValid() && importInfo.type() == ImportType::QrcDirectory) {
QString path = Utils::QrcParser::normalizedQrcDirectoryPath(importInfo.path()); QString path = Utils::QrcParser::normalizedQrcDirectoryPath(importInfo.path());

View File

@@ -289,9 +289,8 @@ bool QmlBuildSystem::setFileSettingInProjectFile(const QString &setting, const U
const QString settingQmlCode = setting + ":"; const QString settingQmlCode = setting + ":";
QDir projectDir = project()->projectFilePath().toDir(); const Utils::FilePath projectDir = project()->projectFilePath().parentDir();
projectDir.cdUp(); const QString relativePath = mainFilePath.relativeChildPath(projectDir).path();
const QString relativePath = projectDir.relativeFilePath(mainFilePath.toString());
if (fileContent.indexOf(settingQmlCode) < 0) { if (fileContent.indexOf(settingQmlCode) < 0) {
QString addedText = QString("\n %1 \"%2\"\n").arg(settingQmlCode).arg(relativePath); QString addedText = QString("\n %1 \"%2\"\n").arg(settingQmlCode).arg(relativePath);

View File

@@ -194,9 +194,9 @@ const Utils::FilePath findQmlProjectUpwards(const Utils::FilePath &folder)
if (ret.exists()) if (ret.exists())
return ret; return ret;
QDir dir = folder.toDir(); if (folder.parentDir().isDir())
if (dir.cdUp()) return findQmlProjectUpwards(folder.parentDir());
return findQmlProjectUpwards(Utils::FilePath::fromString(dir.absolutePath()));
return {}; return {};
} }

View File

@@ -262,18 +262,18 @@ public:
} // namespace Internal } // namespace Internal
static Utils::FilePath customStylesPath() static FilePath customStylesPath()
{ {
return Core::ICore::userResourcePath("styles"); return Core::ICore::userResourcePath("styles");
} }
static Utils::FilePath createColorSchemeFileName(const QString &pattern) static FilePath createColorSchemeFileName(const QString &pattern)
{ {
const Utils::FilePath stylesPath = customStylesPath(); const FilePath stylesPath = customStylesPath();
// Find an available file name // Find an available file name
int i = 1; int i = 1;
Utils::FilePath filePath; FilePath filePath;
do { do {
filePath = stylesPath.pathAppended(pattern.arg((i == 1) ? QString() : QString::number(i))); filePath = stylesPath.pathAppended(pattern.arg((i == 1) ? QString() : QString::number(i)));
++i; ++i;
@@ -545,7 +545,7 @@ void FontSettingsPageWidget::copyColorScheme(const QString &name)
QString baseFileName = QFileInfo(entry.fileName).completeBaseName(); QString baseFileName = QFileInfo(entry.fileName).completeBaseName();
baseFileName += QLatin1String("_copy%1.xml"); baseFileName += QLatin1String("_copy%1.xml");
Utils::FilePath fileName = createColorSchemeFileName(baseFileName); FilePath fileName = createColorSchemeFileName(baseFileName);
if (!fileName.isEmpty()) { if (!fileName.isEmpty()) {
// Ask about saving any existing modifications // Ask about saving any existing modifications
@@ -604,7 +604,7 @@ void FontSettingsPageWidget::deleteColorScheme()
void FontSettingsPageWidget::importScheme() void FontSettingsPageWidget::importScheme()
{ {
const Utils::FilePath importedFile const FilePath importedFile
= Utils::FileUtils::getOpenFilePath(this, = Utils::FileUtils::getOpenFilePath(this,
tr("Import Color Scheme"), tr("Import Color Scheme"),
{}, {},
@@ -613,7 +613,7 @@ void FontSettingsPageWidget::importScheme()
if (importedFile.isEmpty()) if (importedFile.isEmpty())
return; return;
Utils::FilePath fileName = createColorSchemeFileName(importedFile.baseName() + "%1." FilePath fileName = createColorSchemeFileName(importedFile.baseName() + "%1."
+ importedFile.suffix()); + importedFile.suffix());
// Ask about saving any existing modifications // Ask about saving any existing modifications
@@ -647,10 +647,10 @@ void FontSettingsPageWidget::exportScheme()
const ColorSchemeEntry &entry = m_schemeListModel.colorSchemeAt(index); const ColorSchemeEntry &entry = m_schemeListModel.colorSchemeAt(index);
const Utils::FilePath filePath const FilePath filePath
= Utils::FileUtils::getSaveFilePath(this, = Utils::FileUtils::getSaveFilePath(this,
tr("Export Color Scheme"), tr("Export Color Scheme"),
Utils::FilePath::fromString(entry.fileName), FilePath::fromString(entry.fileName),
tr("Color scheme (*.xml);;All files (*)")); tr("Color scheme (*.xml);;All files (*)"));
if (!filePath.isEmpty()) if (!filePath.isEmpty())
@@ -686,34 +686,30 @@ void FontSettingsPageWidget::refreshColorSchemeList()
{ {
QList<ColorSchemeEntry> colorSchemes; QList<ColorSchemeEntry> colorSchemes;
QDir styleDir(Core::ICore::resourcePath("styles").toDir()); const FilePath styleDir = Core::ICore::resourcePath("styles");
styleDir.setNameFilters(QStringList() << QLatin1String("*.xml"));
styleDir.setFilter(QDir::Files); FilePaths schemeList = styleDir.dirEntries(FileFilter({"*.xml"}, QDir::Files));
const FilePath defaultScheme = FilePath::fromString(FontSettings::defaultSchemeFileName());
if (schemeList.removeAll(defaultScheme))
schemeList.prepend(defaultScheme);
int selected = 0; int selected = 0;
QStringList schemeList = styleDir.entryList(); for (const FilePath &file : qAsConst(schemeList)) {
QString defaultScheme = Utils::FilePath::fromString(FontSettings::defaultSchemeFileName()).fileName(); if (FilePath::fromString(m_value.colorSchemeFileName()) == file)
if (schemeList.removeAll(defaultScheme))
schemeList.prepend(defaultScheme);
for (const QString &file : qAsConst(schemeList)) {
const QString fileName = styleDir.absoluteFilePath(file);
if (m_value.colorSchemeFileName() == fileName)
selected = colorSchemes.size(); selected = colorSchemes.size();
colorSchemes.append(ColorSchemeEntry(fileName, true)); colorSchemes.append(ColorSchemeEntry(file.toString(), true));
} }
if (colorSchemes.isEmpty()) if (colorSchemes.isEmpty())
qWarning() << "Warning: no color schemes found in path:" << styleDir.path(); qWarning() << "Warning: no color schemes found in path:" << styleDir.toUserOutput();
styleDir.setPath(customStylesPath().path()); const FilePaths files = customStylesPath().dirEntries(FileFilter({"*.xml"}, QDir::Files));
for (const FilePath &file : files) {
const QStringList files = styleDir.entryList(); if (FilePath::fromString(m_value.colorSchemeFileName()) == file)
for (const QString &file : files) {
const QString fileName = styleDir.absoluteFilePath(file);
if (m_value.colorSchemeFileName() == fileName)
selected = colorSchemes.size(); selected = colorSchemes.size();
colorSchemes.append(ColorSchemeEntry(fileName, false)); colorSchemes.append(ColorSchemeEntry(file.toString(), false));
} }
m_refreshingSchemeList = true; m_refreshingSchemeList = true;