1// Copyright (C) 2018 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3
4#include <qfile.h>
5#include <qjsonarray.h>
6#include <qjsondocument.h>
7#include <qjsonobject.h>
8#include <qhashfunctions.h>
9#include <qstringlist.h>
10#include <cstdlib>
11
12static bool readFromDevice(QIODevice *device, QJsonArray *allMetaObjects)
13{
14 const QByteArray contents = device->readAll();
15 if (contents.isEmpty())
16 return true;
17
18 QJsonParseError error {};
19 QJsonDocument metaObjects = QJsonDocument::fromJson(json: contents, error: &error);
20 if (error.error != QJsonParseError::NoError) {
21 fprintf(stderr, format: "%s at %d\n", error.errorString().toUtf8().constData(), error.offset);
22 return false;
23 }
24
25 allMetaObjects->append(value: metaObjects.object());
26 return true;
27}
28
29int collectJson(const QStringList &jsonFiles, const QString &outputFile, bool skipStdIn)
30{
31 QHashSeed::setDeterministicGlobalSeed();
32
33 QFile output;
34 if (outputFile.isEmpty()) {
35 if (!output.open(stdout, ioFlags: QIODevice::WriteOnly)) {
36 fprintf(stderr, format: "Error opening stdout for writing\n");
37 return EXIT_FAILURE;
38 }
39 } else {
40 output.setFileName(outputFile);
41 if (!output.open(flags: QIODevice::WriteOnly)) {
42 fprintf(stderr, format: "Error opening %s for writing\n", qPrintable(outputFile));
43 return EXIT_FAILURE;
44 }
45 }
46
47 QJsonArray allMetaObjects;
48 if (jsonFiles.isEmpty() && !skipStdIn) {
49 QFile f;
50 if (!f.open(stdin, ioFlags: QIODevice::ReadOnly)) {
51 fprintf(stderr, format: "Error opening stdin for reading\n");
52 return EXIT_FAILURE;
53 }
54
55 if (!readFromDevice(device: &f, allMetaObjects: &allMetaObjects)) {
56 fprintf(stderr, format: "Error parsing data from stdin\n");
57 return EXIT_FAILURE;
58 }
59 }
60
61 QStringList jsonFilesSorted = jsonFiles;
62 jsonFilesSorted.sort();
63 for (const QString &jsonFile : std::as_const(t&: jsonFilesSorted)) {
64 QFile f(jsonFile);
65 if (!f.open(flags: QIODevice::ReadOnly)) {
66 fprintf(stderr, format: "Error opening %s for reading\n", qPrintable(jsonFile));
67 return EXIT_FAILURE;
68 }
69
70 if (!readFromDevice(device: &f, allMetaObjects: &allMetaObjects)) {
71 fprintf(stderr, format: "Error parsing %s\n", qPrintable(jsonFile));
72 return EXIT_FAILURE;
73 }
74 }
75
76 QJsonDocument doc(allMetaObjects);
77 output.write(data: doc.toJson());
78
79 return EXIT_SUCCESS;
80}
81

source code of qtbase/src/tools/moc/collectjson.cpp