aboutsummaryrefslogtreecommitdiffstats
path: root/src/qmldom/qqmldomfilewriter.cpp
blob: 82f2aca49608c7ad28119909c14524db1424f21d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
// Copyright (C) 2021 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "qqmldomfilewriter_p.h"
#include <QtCore/QRandomGenerator>
#include <QtCore/QScopeGuard>

QT_BEGIN_NAMESPACE
namespace QQmlJS {
namespace Dom {

FileWriter::Status FileWriter::write(const QString &tFile, function_ref<bool(QTextStream &)> write,
                                     int nBk)
{
    if (shouldRemoveTempFile)
        tempFile.remove();
    tempFile.close();
    shouldRemoveTempFile = false;
    Q_ASSERT(status != Status::ShouldWrite);
    status = Status::ShouldWrite;
    targetFile = tFile;
    newBkFiles.clear();
    warnings.clear();

    int i = 0;
    const int maxAttempts = 20;
    for (; i < maxAttempts; ++i) {
        tempFile.setFileName(targetFile
                             + QString::number(QRandomGenerator::global()->generate(), 16).mid(0, 8)
                             + QStringLiteral(u".tmp"));
        if (tempFile.open(QIODevice::ReadWrite | QIODevice::NewOnly))
            break;
    }
    if (i == maxAttempts) {
        warnings.append(tr("Could not create temp file for %1").arg(targetFile));
        status = FileWriter::Status::SkippedDueToFailure;
        return status;
    }
    shouldRemoveTempFile = true;
    bool success = false;
    QTextStream inF(&tempFile);
    QT_TRY
    {
        auto cleanup = qScopeGuard([this, &inF, &success, nBk] {
            inF.flush();
            tempFile.flush();
            tempFile.close();
            if (success) {
                if (QFile::exists(targetFile)) {
                    // compareFiles
                    if (tempFile.open(QIODevice::ReadOnly)) {
                        auto closeTmpF = qScopeGuard([this] { tempFile.close(); });
                        QFile oldF(targetFile);
                        if (oldF.open(QIODevice::ReadOnly)) {
                            bool same = true;
                            while (!tempFile.atEnd() && !oldF.atEnd()) {
                                QByteArray l1 = tempFile.readLine();
                                QByteArray l2 = oldF.readLine();
                                if (l1 != l2)
                                    same = false;
                            }
                            if (tempFile.atEnd() && oldF.atEnd() && same) {
                                tempFile.remove();
                                shouldRemoveTempFile = false;
                                status = Status::SkippedEqual;
                                return;
                            }
                        }
                    }
                }
                // move to target
                int i = 0;
                const int maxAttempts = 10;
                for (; i < maxAttempts; ++i) {
                    if (QFile::exists(targetFile)) {
                        // make place for targetFile
                        QString bkFileName;
                        if (nBk < 1) {
                            QFile::remove(targetFile);
                        } else if (nBk == 1) {
                            QString bkFileName = targetFile + QStringLiteral(u"~");
                            QFile::remove(bkFileName);
                            QFile::rename(targetFile, bkFileName);
                        } else {
                            // f~ is the oldest, further backups at f1~ .. f<nBk>~
                            // keeping an empty place for the "next" backup
                            // f~ is never overwritten
                            int iBk = 0;
                            QString bkFileName = targetFile + QStringLiteral(u"~");
                            while (++iBk < nBk) {
                                if (QFile::exists(bkFileName))
                                    bkFileName = targetFile + QString::number(iBk)
                                            + QStringLiteral(u"~");
                            }
                            if (iBk == nBk)
                                QFile::remove(targetFile + QStringLiteral(u"1~"));
                            else
                                QFile::remove(targetFile + QString::number(++iBk)
                                              + QStringLiteral(u"~"));
                            QFile::remove(bkFileName);
                            QFile::rename(targetFile, bkFileName);
                        }
                        if (!bkFileName.isEmpty() && QFile::rename(targetFile, bkFileName))
                            newBkFiles.append(bkFileName);
                    }
                    if (tempFile.rename(targetFile)) {
                        status = Status::DidWrite;
                        shouldRemoveTempFile = false;
                        return;
                    }
                }
                warnings.append(
                        tr("Rename of file %1 to %2 failed").arg(tempFile.fileName(), targetFile));
                status = Status::SkippedDueToFailure;
            } else {
                warnings.append(tr("Error while writing"));
            }
        });
        success = write(inF);
    }
    QT_CATCH(...)
    {
        warnings.append(tr("Exception trying to write file %1").arg(targetFile));
        status = FileWriter::Status::SkippedDueToFailure;
    }
    if (status == Status::ShouldWrite)
        status = Status::SkippedDueToFailure;
    return status;
}

} // namespace Dom
} // namespace QQmlJS
QT_END_NAMESPACE

#include "moc_qqmldomfilewriter_p.cpp"