Do not delete saved chats if we fail to serialize properly.

This commit is contained in:
Adam Treat 2023-10-07 13:54:38 -04:00 committed by AT
parent 9fb135e020
commit 35f9cdb70a

View File

@ -84,13 +84,16 @@ void ChatSaver::saveChats(const QVector<Chat *> &chats)
const QString savePath = MySettings::globalInstance()->modelPath(); const QString savePath = MySettings::globalInstance()->modelPath();
for (Chat *chat : chats) { for (Chat *chat : chats) {
QString fileName = "gpt4all-" + chat->id() + ".chat"; QString fileName = "gpt4all-" + chat->id() + ".chat";
QFile file(savePath + "/" + fileName); QString filePath = savePath + "/" + fileName;
bool success = file.open(QIODevice::WriteOnly); QFile originalFile(filePath);
QFile tempFile(filePath + ".tmp"); // Temporary file
bool success = tempFile.open(QIODevice::WriteOnly);
if (!success) { if (!success) {
qWarning() << "ERROR: Couldn't save chat to file:" << file.fileName(); qWarning() << "ERROR: Couldn't save chat to temporary file:" << tempFile.fileName();
continue; continue;
} }
QDataStream out(&file); QDataStream out(&tempFile);
out << (quint32)CHAT_FORMAT_MAGIC; out << (quint32)CHAT_FORMAT_MAGIC;
out << (qint32)CHAT_FORMAT_VERSION; out << (qint32)CHAT_FORMAT_VERSION;
@ -98,11 +101,16 @@ void ChatSaver::saveChats(const QVector<Chat *> &chats)
qDebug() << "serializing chat" << fileName; qDebug() << "serializing chat" << fileName;
if (!chat->serialize(out, CHAT_FORMAT_VERSION)) { if (!chat->serialize(out, CHAT_FORMAT_VERSION)) {
qWarning() << "ERROR: Couldn't serialize chat to file:" << file.fileName(); qWarning() << "ERROR: Couldn't serialize chat to file:" << tempFile.fileName();
file.remove(); tempFile.remove();
continue;
} }
file.close();
if (originalFile.exists())
originalFile.remove();
tempFile.rename(filePath);
} }
qint64 elapsedTime = timer.elapsed(); qint64 elapsedTime = timer.elapsed();
qDebug() << "serializing chats took:" << elapsedTime << "ms"; qDebug() << "serializing chats took:" << elapsedTime << "ms";
emit saveChatsFinished(); emit saveChatsFinished();