Include moc files for a tiny speedup on incremental builds

This commit is contained in:
Nicolas Werner 2024-03-16 01:24:33 +01:00
parent d2009428b6
commit 06927cd3c2
No known key found for this signature in database
GPG key ID: C8D75E610773F2D9
72 changed files with 335 additions and 17 deletions

View file

@ -17,6 +17,8 @@ done;
git diff --exit-code
./scripts/includemocs.py --insert-at-end -n src
if command -v /usr/lib64/qt6/bin/qmllint &> /dev/null; then
/usr/lib64/qt6/bin/qmllint $QML_FILES
elif command -v /usr/lib/qt6/bin/qmllint &> /dev/null; then

197
scripts/includemocs.py Executable file
View file

@ -0,0 +1,197 @@
#!/usr/bin/env python3
#
# This file is part of KDToolBox.
#
# SPDX-FileCopyrightText: 2022 Klarälvdalens Datakonsult AB, a KDAB Group company <info@kdab.com>
# Author: Jesper K. Pedersen <jesper.pedersen@kdab.com>
#
# SPDX-License-Identifier: MIT
#
'''
Script to add inclusion of mocs to files recursively.
'''
# pylint: disable=redefined-outer-name
import os
import re
import argparse
import sys
dirty = False
def stripInitialSlash(path):
if path and path.startswith("/"):
path = path[1:]
return path
# Returns true if the path is to be excluded from the search
def shouldExclude(root, path):
# pylint: disable=used-before-assignment
if not args.excludes:
return False # No excludes provided
assert root.startswith(args.root)
root = stripInitialSlash(root[len(args.root):])
if args.headerPrefix:
assert root.startswith(args.headerPrefix)
root = stripInitialSlash(root[len(args.headerPrefix):])
return (path in args.excludes) or (root + "/" + path in args.excludes)
regexp = re.compile("\\s*(Q_OBJECT|Q_GADGET|Q_NAMESPACE)\\s*")
# Returns true if the header file provides contains a Q_OBJECT, Q_GADGET or Q_NAMESPACE macro
def hasMacro(fileName):
with open(fileName, "r", encoding="ISO-8859-1") as fileHandle:
for line in fileHandle:
if regexp.match(line):
return True
return False
# returns the matching .cpp file for the given .h file
def matchingCPPFile(root, fileName):
assert root.startswith(args.root)
root = stripInitialSlash(root[len(args.root):])
if args.headerPrefix:
assert root.startswith(args.headerPrefix)
root = stripInitialSlash(root[len(args.headerPrefix):])
if args.sourcePrefix:
root = args.sourcePrefix + "/" + root
return args.root + "/" \
+ root + ("/" if root != "" else "") \
+ fileNameWithoutExtension(fileName) + ".cpp"
def fileNameWithoutExtension(fileName):
return os.path.splitext(os.path.basename(fileName))[0]
# returns true if the specifies .cpp file already has the proper include
def cppHasMOCInclude(fileName):
includeStatement = '#include "moc_%s.cpp"' % fileNameWithoutExtension(fileName)
with open(fileName, encoding="utf8") as fileHandle:
return includeStatement in fileHandle.read()
def getMocInsertionLocation(filename, content):
headerIncludeRegex = re.compile(r'#include "%s\.h".*\n' % fileNameWithoutExtension(filename), re.M)
match = headerIncludeRegex.search(content)
if match:
return match.end()
return 0
def trimExistingMocInclude(content, cppFileName):
mocStrRegex = re.compile(r'#include "moc_%s\.cpp"\n' % fileNameWithoutExtension(cppFileName))
match = mocStrRegex.search(content)
if match:
return content[:match.start()] + content[match.end():]
return content
def processFile(root, fileName):
# pylint: disable=global-statement
global dirty
macroFound = hasMacro(root+"/"+fileName)
logVerbose("Inspecting %s %s" %
(root+"/"+fileName, "[Has Q_OBJECT / Q_GADGET / Q_NAMESPACE]" if macroFound else ""))
if macroFound:
cppFileName = matchingCPPFile(root, fileName)
logVerbose(" -> %s" % cppFileName)
if not os.path.exists(cppFileName):
log("file %s didn't exist (which might not be an error)" % cppFileName)
return
if args.replaceExisting or not cppHasMOCInclude(cppFileName):
dirty = True
if args.dryRun:
log("Missing moc include file: %s" % cppFileName)
else:
log("Updating %s" % cppFileName)
with open(cppFileName, "r", encoding="utf8") as f:
content = f.read()
if args.replaceExisting:
content = trimExistingMocInclude(content, cppFileName)
loc = getMocInsertionLocation(cppFileName, content)
if args.insertAtEnd:
with open(cppFileName, "a", encoding="utf8") as f:
f.write('\n#include "moc_%s.cpp"\n' % fileNameWithoutExtension(cppFileName))
else:
with open(cppFileName, "w", encoding="utf8") as f:
f.write(content[:loc] + ('#include "moc_%s.cpp"\n' %
fileNameWithoutExtension(cppFileName)) + content[loc:])
def log(content):
if not args.quiet:
print(content)
def logVerbose(content):
if args.verbose:
print(content)
################################ MAIN #################################
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="""Script to add inclusion of mocs to files recursively.
The source files either need to be in the same directories as the header files or in parallel directories,
where the root of the headers are specified using --header-prefix and the root of the sources are specified using --source-prefix.
If either header-prefix or source-prefix is the current directory, then they may be omitted.""")
parser.add_argument("--dry-run", "-n", dest="dryRun", action='store_true', help="only report files to be updated")
parser.add_argument("--quiet", "-q", dest="quiet", action='store_true', help="suppress output")
parser.add_argument("--verbose", "-v", dest="verbose", action='store_true')
parser.add_argument("--header-prefix", metavar="directory", dest="headerPrefix",
help="This directory will be replaced with source-prefix when "
"searching for matching source files")
parser.add_argument("--source-prefix", metavar="directory", dest="sourcePrefix", help="see --header-prefix")
parser.add_argument("--excludes", metavar="directory", dest="excludes", nargs="*",
help="directories to be excluded, might either be in the form of a directory name, "
"e.g. 3rdparty or a partial directory prefix from the root, e.g 3rdparty/parser")
parser.add_argument("--insert-at-end", dest="insertAtEnd", action='store_true',
help="insert the moc include at the end of the file instead of the beginning")
parser.add_argument("--replace-existing", dest="replaceExisting", action='store_true',
help="delete and readd existing MOC include statements")
parser.add_argument(dest="root", default=".", metavar="directory",
nargs="?", help="root directory for the operation")
args = parser.parse_args()
root = args.root
if args.headerPrefix:
root += "/" + args.headerPrefix
path = os.walk(root)
for root, directories, files in path:
# Filter out directories specified in --exclude
directories[:] = [d for d in directories if not shouldExclude(root, d)]
for file in files:
if file.endswith(".h") or file.endswith(".hpp"):
processFile(root, file)
if not dirty:
log("No changes needed")
sys.exit(-1 if dirty else 0)

View file

@ -333,3 +333,5 @@ AliasEditingModel::commit()
}
});
}
#include "moc_AliasEditModel.cpp"

View file

@ -69,3 +69,5 @@ resolve(const QString &room_id,
resolve(std::move(avatarUrl), size, receiver, callback);
}
}
#include "moc_AvatarProvider.cpp"

View file

@ -45,3 +45,5 @@ BlurhashRunnable::run()
emit done(image.convertToFormat(QImage::Format_RGB32));
}
#include "moc_BlurhashProvider.cpp"

View file

@ -1773,3 +1773,5 @@ ChatPage::removeAllNotifications()
notificationsManager->closeAllNotifications();
#endif
}
#include "moc_ChatPage.cpp"

View file

@ -24,3 +24,5 @@ Clipboard::text() const
{
return QGuiApplication::clipboard()->text();
}
#include "moc_Clipboard.cpp"

View file

@ -2,6 +2,8 @@
//
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <QQuickImageProvider>
class ColorImageProvider final : public QQuickImageProvider

View file

@ -103,3 +103,5 @@ CombinedImagePackModel::data(const QModelIndex &index, int role) const
}
return {};
}
#include "moc_CombinedImagePackModel.cpp"

View file

@ -169,3 +169,5 @@ CompletionProxyModel::setSearchString(const QString &s)
{
emit newSearchString(s);
}
#include "moc_CompletionProxyModel.cpp"

View file

@ -27,3 +27,5 @@ FallbackAuth::openFallbackAuth()
QDesktopServices::openUrl(url);
}
#include "moc_FallbackAuth.cpp"

View file

@ -400,3 +400,5 @@ GridImagePackModel::setSearchString(QString key)
endResetModel();
emit newSearchString();
}
#include "moc_GridImagePackModel.cpp"

View file

@ -97,3 +97,5 @@ ImagePackListModel::containsAccountPack() const
return true;
return false;
}
#include "moc_ImagePackListModel.cpp"

View file

@ -110,3 +110,5 @@ Invitee::Invitee(QString mxid, QString displayName, QString avatarUrl, QObject *
emit userInfoLoaded();
}
}
#include "moc_InviteesModel.cpp"

View file

@ -2,8 +2,7 @@
//
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef INVITEESMODEL_H
#define INVITEESMODEL_H
#pragma once
#include <QAbstractListModel>
#include <QQmlEngine>
@ -73,5 +72,3 @@ private:
QVector<Invitee *> invitees_;
TimelineModel *room_;
};
#endif // INVITEESMODEL_H

View file

@ -120,3 +120,5 @@ JdenticonProvider::isAvailable()
{
return Jdenticon::getJdenticonInterface() != nullptr;
}
#include "moc_JdenticonProvider.cpp"

View file

@ -352,3 +352,5 @@ LoginPage::onLoginButtonClicked(LoginMethod loginMethod,
loggingIn_ = true;
emit loggingInChanged();
}
#include "moc_LoginPage.cpp"

View file

@ -322,3 +322,5 @@ MainWindow::focusedRoom() const
return nullptr;
}
#include "moc_MainWindow.cpp"

View file

@ -169,3 +169,5 @@ MemberList::filterAcceptsRow(int source_row, const QModelIndex &) const
m_model.m_memberList[source_row].first.display_name.contains(filterString,
Qt::CaseInsensitive);
}
#include "moc_MemberList.cpp"

View file

@ -370,3 +370,5 @@ MxcImageProvider::download(const QString &id,
}
}
}
#include "moc_MxcImageProvider.cpp"

View file

@ -827,3 +827,5 @@ PowerlevelsSpacesListModel::roleNames() const
{ApplyPermissions, "applyPermissions"},
};
}
#include "moc_PowerlevelsEditModels.cpp"

View file

@ -27,3 +27,5 @@ ReCaptcha::openReCaptcha()
QDesktopServices::openUrl(url);
}
#include "moc_ReCaptcha.cpp"

View file

@ -129,3 +129,5 @@ ReadReceiptsProxy::ReadReceiptsProxy(QString event_id, QString room_id, QObject
sort(0, Qt::DescendingOrder);
setDynamicSortFilter(true);
}
#include "moc_ReadReceiptsModel.cpp"

View file

@ -2,8 +2,7 @@
//
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef READRECEIPTSMODEL_H
#define READRECEIPTSMODEL_H
#pragma once
#include <QAbstractListModel>
#include <QDateTime>
@ -73,5 +72,3 @@ private:
ReadReceiptsModel model_;
};
#endif // READRECEIPTSMODEL_H

View file

@ -255,3 +255,5 @@ RegisterPage::startRegistration(const QString &username,
devicename.isEmpty() ? LoginPage::initialDeviceName_() : devicename.toStdString());
}
}
#include "moc_RegisterPage.cpp"

View file

@ -228,3 +228,5 @@ RoomDirectoryModel::displayRooms(std::vector<mtx::responses::PublicRoomsChunk> f
nhlog::ui()->debug("Finished loading rooms");
}
#include "moc_RoomDirectoryModel.cpp"

View file

@ -55,3 +55,5 @@ SSOHandler::url() const
{
return "http://localhost:" + std::to_string(port) + "/sso";
}
#include "moc_SSOHandler.cpp"

View file

@ -2,6 +2,8 @@
//
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "httplib.h"
#include <QObject>

View file

@ -488,3 +488,5 @@ SingleImagePackModel::addImageCb(std::string uri, std::string filename, mtx::com
if (this->pack.pack->avatar_url.empty())
this->setAvatarUrl(QString::fromStdString(uri));
}
#include "moc_SingleImagePackModel.cpp"

View file

@ -123,3 +123,5 @@ TrayIcon::setUnreadCount(int count)
{
qGuiApp->setBadgeNumber(count);
}
#include "moc_TrayIcon.cpp"

View file

@ -103,3 +103,5 @@ UserDirectoryModel::displaySearchResults(std::vector<mtx::responses::User> resul
endInsertRows();
canFetchMore_ = false;
}
#include "moc_UserDirectoryModel.cpp"

View file

@ -2332,3 +2332,5 @@ UserSettingsModel::UserSettingsModel(QObject *p)
emit dataChanged(index(ExpireEvents), index(ExpireEvents), {Value});
});
}
#include "moc_UserSettingsPage.cpp"

View file

@ -228,3 +228,5 @@ operator>>(const QDBusArgument &arg, QImage &image)
return arg;
}
#include "moc_NhekoDBusApi.cpp"

View file

@ -2,8 +2,7 @@
//
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef NHEKODBUSAPI_H
#define NHEKODBUSAPI_H
#pragma once
#include <QDBusArgument>
#include <QIcon>
@ -99,5 +98,3 @@ const QDBusArgument &
operator>>(const QDBusArgument &arg, QImage &);
#define NHEKO_DBUS_SERVICE_NAME "im.nheko.Nheko"
#endif // NHEKODBUSAPI_H

View file

@ -117,3 +117,5 @@ NhekoDBusBackend::bringWindowToTop() const
MainWindow::instance()->show();
MainWindow::instance()->raise();
}
#include "moc_NhekoDBusBackend.cpp"

View file

@ -2,8 +2,7 @@
//
// SPDX-License-Identifier: GPL-3.0-or-later
#ifndef NHEKODBUSBACKEND_H
#define NHEKODBUSBACKEND_H
#pragma once
#include <QDBusMessage>
#include <QObject>
@ -47,5 +46,3 @@ private:
RoomlistModel *m_parent;
};
#endif // NHEKODBUSBACKEND_H

View file

@ -90,3 +90,5 @@ Dock::setUnreadCount(const int count)
qGuiApp->setBadgeNumber(count);
}
#endif
#include "moc_Dock.cpp"

View file

@ -15287,3 +15287,5 @@ constexpr
std::u16string_view(u"flag: Wales"),
emoji::Emoji::Category::Flags},
};
#include "moc_Provider.cpp"

View file

@ -987,3 +987,5 @@ DeviceVerificationFlow::send(T msg)
mtx::events::to_string(mtx::events::to_device_content_to_type<T>),
state().toStdString());
}
#include "moc_DeviceVerificationFlow.cpp"

View file

@ -1770,3 +1770,5 @@ download_cross_signing_keys()
}
} // namespace olm
#include "moc_Olm.cpp"

View file

@ -355,3 +355,5 @@ SelfVerificationStatus::invalidate()
return;
}
}
#include "moc_SelfVerificationStatus.cpp"

View file

@ -169,3 +169,5 @@ VerificationManager::verifyOneOfDevices(QString userid, std::vector<QString> dev
this->dvList[flow->transactionId()] = flow;
emit newDeviceVerificationRequest(flow.data());
}
#include "moc_VerificationManager.cpp"

View file

@ -53,3 +53,5 @@ NotificationsManager::removeNotifications(const QString &roomId_,
}
}
}
#include "moc_Manager.cpp"

View file

@ -936,3 +936,5 @@ CommunitiesModel::updateSpaceStatus(QString space,
}
}
}
#include "moc_CommunitiesModel.cpp"

View file

@ -138,3 +138,5 @@ DelegateChooser::DelegateIncubator::statusChanged(QQmlIncubator::Status status)
nhlog::ui()->error("Error instantiating delegate: {}", e.toString().toStdString());
}
}
#include "moc_DelegateChooser.cpp"

View file

@ -369,3 +369,5 @@ EventDelegateChooserAttachedType::polishChooser()
}
}
}
#include "moc_EventDelegateChooser.cpp"

View file

@ -941,3 +941,5 @@ EventStore::fetchMore()
emit oldMessagesRetrieved(std::move(res));
});
}
#include "moc_EventStore.cpp"

View file

@ -1495,3 +1495,5 @@ InputBar::reaction(const QString &reactedEvent, const QString &reactionKey)
room->redactEvent(selfReactedEvent);
}
}
#include "moc_InputBar.cpp"

View file

@ -91,3 +91,5 @@ Permissions::canPingRoom()
return pl.user_level(http::client()->user_id().to_string()) >=
pl.notification_level(mtx::events::state::notification_keys::room);
}
#include "moc_Permissions.cpp"

View file

@ -75,3 +75,5 @@ PresenceEmitter::userStatus(QString id) const
else
return pullPresence(id)->status;
}
#include "moc_PresenceEmitter.cpp"

View file

@ -3,3 +3,5 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#include "Reaction.h"
#include "moc_Reaction.cpp"

View file

@ -1288,3 +1288,5 @@ RoomPreview::inviterUserId() const
return QString();
}
#include "moc_RoomlistModel.cpp"

View file

@ -252,3 +252,5 @@ TimelineFilter::filterAcceptsRow(int source_row, const QModelIndex &) const
return true;
}
}
#include "moc_TimelineFilter.cpp"

View file

@ -3373,3 +3373,5 @@ TimelineModel::parentSpace()
return parentSummary.get();
}
#include "moc_TimelineModel.cpp"

View file

@ -600,3 +600,4 @@ TimelineViewManager::processIgnoredUsers(const mtx::responses::AccountData &data
break;
}
}
#include "moc_TimelineViewManager.cpp"

View file

@ -123,3 +123,5 @@ EventExpiry::setExpireStateEvents(bool val)
this->event.exclude_state_events = !val;
emit expireEventsAfterCountChanged();
}
#include "moc_EventExpiry.cpp"

View file

@ -104,3 +104,5 @@ HiddenEvents::save()
}
});
}
#include "moc_HiddenEvents.cpp"

View file

@ -208,3 +208,5 @@ MxcAnimatedImage::updatePaintNode(QSGNode *oldNode, QQuickItem::UpdatePaintNodeD
return n;
}
#include "moc_MxcAnimatedImage.cpp"

View file

@ -172,3 +172,5 @@ MxcMediaProxy::startDownload(bool onlyCached)
}
});
}
#include "moc_MxcMediaProxy.cpp"

View file

@ -28,3 +28,5 @@ NhekoCursorShape::setCursorShape(Qt::CursorShape cursorShape)
setCursor(cursorShape);
emit cursorShapeChanged();
}
#include "moc_NhekoCursorShape.cpp"

View file

@ -40,3 +40,5 @@ NhekoDropArea::dropEvent(QDropEvent *event)
}
}
}
#include "moc_NhekoDropArea.cpp"

View file

@ -2,6 +2,8 @@
//
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <QQuickItem>
class NhekoDropArea : public QQuickItem

View file

@ -212,3 +212,5 @@ Nheko::setWindowRole([[maybe_unused]] QWindow *win, [[maybe_unused]] QString new
role.data());
#endif
}
#include "moc_NhekoGlobalObject.cpp"

View file

@ -811,3 +811,5 @@ RoomSettings::applyAllowedFromModel()
this->allowedRoomsModified_ = true;
emit allowedRoomsModifiedChanged();
}
#include "moc_RoomSettings.cpp"

View file

@ -95,3 +95,5 @@ RoomSummary::promptJoin()
else
ChatPage::instance()->joinRoomVia(roomIdOrAlias, vias, true, reason_);
}
#include "moc_RoomSummary.cpp"

View file

@ -84,3 +84,5 @@ Theme::Theme(QStringView theme)
error_ = QColor(0xdd, 0x3d, 0x3d);
}
}
#include "moc_Theme.cpp"

View file

@ -285,3 +285,5 @@ UIA::submit3pidToken(const QString &token)
this->submit_url.clear();
});
}
#include "moc_UIA.cpp"

View file

@ -627,3 +627,5 @@ UserProfile::openGlobalProfile()
{
emit manager->openGlobalUserProfile(userid_);
}
#include "moc_UserProfile.cpp"

View file

@ -393,3 +393,5 @@ CallDevices::frameRates(const std::string &, const std::string &) const
}
#endif
#include "moc_CallDevices.cpp"

View file

@ -1172,3 +1172,5 @@ getTurnURIs(const mtx::responses::TurnServer &turnServer)
return ret;
}
}
#include "moc_CallManager.cpp"

View file

@ -511,3 +511,5 @@ ScreenCastPortal::openPipeWireRemote()
}
#endif
#include "moc_ScreenCastPortal.cpp"

View file

@ -1305,3 +1305,5 @@ WebRTCSession::end()
}
#endif
#include "moc_WebRTCSession.cpp"