From 35f9cdb70ac95d9adad315600e14b0539e2bd906 Mon Sep 17 00:00:00 2001 From: Adam Treat Date: Sat, 7 Oct 2023 13:54:38 -0400 Subject: [PATCH] Do not delete saved chats if we fail to serialize properly. --- gpt4all-chat/chatlistmodel.cpp | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/gpt4all-chat/chatlistmodel.cpp b/gpt4all-chat/chatlistmodel.cpp index 062ebdd9..9283239e 100644 --- a/gpt4all-chat/chatlistmodel.cpp +++ b/gpt4all-chat/chatlistmodel.cpp @@ -84,13 +84,16 @@ void ChatSaver::saveChats(const QVector &chats) const QString savePath = MySettings::globalInstance()->modelPath(); for (Chat *chat : chats) { QString fileName = "gpt4all-" + chat->id() + ".chat"; - QFile file(savePath + "/" + fileName); - bool success = file.open(QIODevice::WriteOnly); + QString filePath = savePath + "/" + fileName; + QFile originalFile(filePath); + QFile tempFile(filePath + ".tmp"); // Temporary file + + bool success = tempFile.open(QIODevice::WriteOnly); if (!success) { - qWarning() << "ERROR: Couldn't save chat to file:" << file.fileName(); + qWarning() << "ERROR: Couldn't save chat to temporary file:" << tempFile.fileName(); continue; } - QDataStream out(&file); + QDataStream out(&tempFile); out << (quint32)CHAT_FORMAT_MAGIC; out << (qint32)CHAT_FORMAT_VERSION; @@ -98,11 +101,16 @@ void ChatSaver::saveChats(const QVector &chats) qDebug() << "serializing chat" << fileName; if (!chat->serialize(out, CHAT_FORMAT_VERSION)) { - qWarning() << "ERROR: Couldn't serialize chat to file:" << file.fileName(); - file.remove(); + qWarning() << "ERROR: Couldn't serialize chat to file:" << tempFile.fileName(); + tempFile.remove(); + continue; } - file.close(); + + if (originalFile.exists()) + originalFile.remove(); + tempFile.rename(filePath); } + qint64 elapsedTime = timer.elapsed(); qDebug() << "serializing chats took:" << elapsedTime << "ms"; emit saveChatsFinished();