1 | // Copyright (C) 2019 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 <QCoreApplication> |
5 | #include <QFile> |
6 | #include <QTextStream> |
7 | |
8 | #include <QtQml/private/qqmljslexer_p.h> |
9 | #include <QtQml/private/qqmljsparser_p.h> |
10 | #include <QtQml/private/qqmljsengine_p.h> |
11 | #include <QtQml/private/qqmljsastvisitor_p.h> |
12 | #include <QtQml/private/qqmljsast_p.h> |
13 | #include <QtQmlDom/private/qqmldomitem_p.h> |
14 | #include <QtQmlDom/private/qqmldomexternalitems_p.h> |
15 | #include <QtQmlDom/private/qqmldomtop_p.h> |
16 | #include <QtQmlDom/private/qqmldomoutwriter_p.h> |
17 | |
18 | #if QT_CONFIG(commandlineparser) |
19 | # include <QCommandLineParser> |
20 | #endif |
21 | |
22 | #include <QtQmlToolingSettings/private/qqmltoolingsettings_p.h> |
23 | |
24 | |
25 | using namespace QQmlJS::Dom; |
26 | |
27 | struct Options |
28 | { |
29 | bool verbose = false; |
30 | bool inplace = false; |
31 | bool force = false; |
32 | bool tabs = false; |
33 | bool valid = false; |
34 | bool normalize = false; |
35 | bool ignoreSettings = false; |
36 | bool writeDefaultSettings = false; |
37 | bool objectsSpacing = false; |
38 | bool functionsSpacing = false; |
39 | |
40 | int indentWidth = 4; |
41 | bool indentWidthSet = false; |
42 | QString newline = "native" ; |
43 | |
44 | QStringList files; |
45 | QStringList arguments; |
46 | QStringList errors; |
47 | }; |
48 | |
49 | // TODO refactor |
50 | // Move out to the LineWriterOptions class / helper |
51 | static LineWriterOptions composeLwOptions(const Options &options, QStringView code) |
52 | { |
53 | LineWriterOptions lwOptions; |
54 | lwOptions.formatOptions.indentSize = options.indentWidth; |
55 | lwOptions.formatOptions.useTabs = options.tabs; |
56 | lwOptions.updateOptions = LineWriterOptions::Update::None; |
57 | if (options.newline == "native" ) { |
58 | // find out current line endings... |
59 | int newlineIndex = code.indexOf(c: QChar(u'\n')); |
60 | int crIndex = code.indexOf(c: QChar(u'\r')); |
61 | if (newlineIndex >= 0) { |
62 | if (crIndex >= 0) { |
63 | if (crIndex + 1 == newlineIndex) |
64 | lwOptions.lineEndings = LineWriterOptions::LineEndings::Windows; |
65 | else |
66 | qWarning().noquote() << "Invalid line ending in file, using default" ; |
67 | |
68 | } else { |
69 | lwOptions.lineEndings = LineWriterOptions::LineEndings::Unix; |
70 | } |
71 | } else if (crIndex >= 0) { |
72 | lwOptions.lineEndings = LineWriterOptions::LineEndings::OldMacOs; |
73 | } else { |
74 | qWarning().noquote() << "Unknown line ending in file, using default" ; |
75 | } |
76 | } else if (options.newline == "macos" ) { |
77 | lwOptions.lineEndings = LineWriterOptions::LineEndings::OldMacOs; |
78 | } else if (options.newline == "windows" ) { |
79 | lwOptions.lineEndings = LineWriterOptions::LineEndings::Windows; |
80 | } else if (options.newline == "unix" ) { |
81 | lwOptions.lineEndings = LineWriterOptions::LineEndings::Unix; |
82 | } else { |
83 | qWarning().noquote() << "Unknown line ending type" << options.newline << ", using default" ; |
84 | } |
85 | |
86 | if (options.normalize) |
87 | lwOptions.attributesSequence = LineWriterOptions::AttributesSequence::Normalize; |
88 | else |
89 | lwOptions.attributesSequence = LineWriterOptions::AttributesSequence::Preserve; |
90 | |
91 | lwOptions.objectsSpacing = options.objectsSpacing; |
92 | lwOptions.functionsSpacing = options.functionsSpacing; |
93 | return lwOptions; |
94 | } |
95 | |
96 | static void logParsingErrors(const DomItem &fileItem, const QString &filename) |
97 | { |
98 | fileItem.iterateErrors( |
99 | visitor: [](const DomItem &, const ErrorMessage &msg) { |
100 | errorToQDebug(msg); |
101 | return true; |
102 | }, |
103 | iterate: true); |
104 | qWarning().noquote() << "Failed to parse" << filename; |
105 | } |
106 | |
107 | // TODO |
108 | // refactor this workaround. ExternalOWningItem is not recognized as an owning type |
109 | // in ownerAs. |
110 | static std::shared_ptr<ExternalOwningItem> getFileItemOwner(const DomItem &fileItem) |
111 | { |
112 | std::shared_ptr<ExternalOwningItem> filePtr = nullptr; |
113 | switch (fileItem.internalKind()) { |
114 | case DomType::JsFile: |
115 | filePtr = fileItem.ownerAs<JsFile>(); |
116 | break; |
117 | default: |
118 | filePtr = fileItem.ownerAs<QmlFile>(); |
119 | break; |
120 | } |
121 | return filePtr; |
122 | } |
123 | |
124 | // TODO refactor |
125 | // Introduce better encapsulation and separation of concerns and move to DOM API |
126 | // returns a DomItem corresponding to the loaded file and bool indicating the validity of the file |
127 | static std::pair<DomItem, bool> parse(const QString &filename) |
128 | { |
129 | auto envPtr = |
130 | DomEnvironment::create(loadPaths: QStringList(), |
131 | options: QQmlJS::Dom::DomEnvironment::Option::SingleThreaded |
132 | | QQmlJS::Dom::DomEnvironment::Option::NoDependencies); |
133 | // placeholder for a node |
134 | // containing metadata (ExternalItemInfo) about the loaded file |
135 | DomItem fMetadataItem; |
136 | envPtr->loadFile(file: FileToLoad::fromFileSystem(environment: envPtr, canonicalPath: filename), |
137 | // callback called when everything is loaded that receives the |
138 | // loaded external file pair (path, oldValue, newValue) |
139 | callback: [&fMetadataItem](Path, const DomItem &, const DomItem &extItemInfo) { |
140 | fMetadataItem = extItemInfo; |
141 | }); |
142 | auto fItem = fMetadataItem.fileObject(); |
143 | auto filePtr = getFileItemOwner(fileItem: fItem); |
144 | return { fItem, filePtr && filePtr->isValid() }; |
145 | } |
146 | |
147 | static bool parseFile(const QString &filename, const Options &options) |
148 | { |
149 | const auto [fileItem, validFile] = parse(filename); |
150 | if (!validFile) { |
151 | logParsingErrors(fileItem, filename); |
152 | return false; |
153 | } |
154 | |
155 | // Turn AST back into source code |
156 | if (options.verbose) |
157 | qWarning().noquote() << "Dumping" << filename; |
158 | |
159 | const auto &code = getFileItemOwner(fileItem)->code(); |
160 | auto lwOptions = composeLwOptions(options, code); |
161 | WriteOutChecks checks = WriteOutCheck::Default; |
162 | //Disable writeOutChecks for some usecases |
163 | if (options.force || |
164 | code.size() > 32000 || |
165 | fileItem.internalKind() == DomType::JsFile) { |
166 | checks = WriteOutCheck::None; |
167 | } |
168 | |
169 | bool res = false; |
170 | if (options.inplace) { |
171 | if (options.verbose) |
172 | qWarning().noquote() << "Writing to file" << filename; |
173 | FileWriter fw; |
174 | const unsigned numberOfBackupFiles = 0; |
175 | res = fileItem.writeOut(path: filename, nBackups: numberOfBackupFiles, opt: lwOptions, fw: &fw, extraChecks: checks); |
176 | } else { |
177 | QFile out; |
178 | if (out.open(stdout, ioFlags: QIODevice::WriteOnly)) { |
179 | LineWriter lw([&out](QStringView s) { out.write(data: s.toUtf8()); }, filename, lwOptions); |
180 | OutWriter ow(lw); |
181 | res = fileItem.writeOutForFile(ow, extraChecks: checks); |
182 | ow.flush(); |
183 | } else { |
184 | res = false; |
185 | } |
186 | } |
187 | return res; |
188 | } |
189 | |
190 | Options buildCommandLineOptions(const QCoreApplication &app) |
191 | { |
192 | #if QT_CONFIG(commandlineparser) |
193 | QCommandLineParser parser; |
194 | parser.setApplicationDescription("Formats QML files according to the QML Coding Conventions." ); |
195 | parser.addHelpOption(); |
196 | parser.addVersionOption(); |
197 | |
198 | parser.addOption( |
199 | commandLineOption: QCommandLineOption({ "V" , "verbose" }, |
200 | QStringLiteral("Verbose mode. Outputs more detailed information." ))); |
201 | |
202 | QCommandLineOption writeDefaultsOption( |
203 | QStringList() << "write-defaults" , |
204 | QLatin1String("Writes defaults settings to .qmlformat.ini and exits (Warning: This " |
205 | "will overwrite any existing settings and comments!)" )); |
206 | parser.addOption(commandLineOption: writeDefaultsOption); |
207 | |
208 | QCommandLineOption ignoreSettings(QStringList() << "ignore-settings" , |
209 | QLatin1String("Ignores all settings files and only takes " |
210 | "command line options into consideration" )); |
211 | parser.addOption(commandLineOption: ignoreSettings); |
212 | |
213 | parser.addOption(commandLineOption: QCommandLineOption( |
214 | { "i" , "inplace" }, |
215 | QStringLiteral("Edit file in-place instead of outputting to stdout." ))); |
216 | |
217 | parser.addOption(commandLineOption: QCommandLineOption({ "f" , "force" }, |
218 | QStringLiteral("Continue even if an error has occurred." ))); |
219 | |
220 | parser.addOption( |
221 | commandLineOption: QCommandLineOption({ "t" , "tabs" }, QStringLiteral("Use tabs instead of spaces." ))); |
222 | |
223 | parser.addOption(commandLineOption: QCommandLineOption({ "w" , "indent-width" }, |
224 | QStringLiteral("How many spaces are used when indenting." ), |
225 | "width" , "4" )); |
226 | |
227 | parser.addOption(commandLineOption: QCommandLineOption({ "n" , "normalize" }, |
228 | QStringLiteral("Reorders the attributes of the objects " |
229 | "according to the QML Coding Guidelines." ))); |
230 | |
231 | parser.addOption(commandLineOption: QCommandLineOption( |
232 | { "F" , "files" }, QStringLiteral("Format all files listed in file, in-place" ), "file" )); |
233 | |
234 | parser.addOption(commandLineOption: QCommandLineOption( |
235 | { "l" , "newline" }, |
236 | QStringLiteral("Override the new line format to use (native macos unix windows)." ), |
237 | "newline" , "native" )); |
238 | |
239 | parser.addOption(commandLineOption: QCommandLineOption(QStringList() << "objects-spacing" , QStringLiteral("Ensure spaces between objects (only works with normalize option)." ))); |
240 | |
241 | parser.addOption(commandLineOption: QCommandLineOption(QStringList() << "functions-spacing" , QStringLiteral("Ensure spaces between functions (only works with normalize option)." ))); |
242 | |
243 | parser.addPositionalArgument(name: "filenames" , description: "files to be processed by qmlformat" ); |
244 | |
245 | parser.process(app); |
246 | |
247 | if (parser.isSet(option: writeDefaultsOption)) { |
248 | Options options; |
249 | options.writeDefaultSettings = true; |
250 | options.valid = true; |
251 | return options; |
252 | } |
253 | |
254 | bool indentWidthOkay = false; |
255 | const int indentWidth = parser.value(name: "indent-width" ).toInt(ok: &indentWidthOkay); |
256 | if (!indentWidthOkay) { |
257 | Options options; |
258 | options.errors.push_back(t: "Error: Invalid value passed to -w" ); |
259 | return options; |
260 | } |
261 | |
262 | QStringList files; |
263 | if (!parser.value(name: "files" ).isEmpty()) { |
264 | QFile file(parser.value(name: "files" )); |
265 | if (file.open(flags: QIODevice::Text | QIODevice::ReadOnly)) { |
266 | QTextStream in(&file); |
267 | while (!in.atEnd()) { |
268 | QString file = in.readLine(); |
269 | |
270 | if (file.isEmpty()) |
271 | continue; |
272 | |
273 | files.push_back(t: file); |
274 | } |
275 | } |
276 | } |
277 | |
278 | Options options; |
279 | options.verbose = parser.isSet(name: "verbose" ); |
280 | options.inplace = parser.isSet(name: "inplace" ); |
281 | options.force = parser.isSet(name: "force" ); |
282 | options.tabs = parser.isSet(name: "tabs" ); |
283 | options.normalize = parser.isSet(name: "normalize" ); |
284 | options.ignoreSettings = parser.isSet(name: "ignore-settings" ); |
285 | options.objectsSpacing = parser.isSet(name: "objects-spacing" ); |
286 | options.functionsSpacing = parser.isSet(name: "functions-spacing" ); |
287 | options.valid = true; |
288 | |
289 | options.indentWidth = indentWidth; |
290 | options.indentWidthSet = parser.isSet(name: "indent-width" ); |
291 | options.newline = parser.value(name: "newline" ); |
292 | options.files = files; |
293 | options.arguments = parser.positionalArguments(); |
294 | return options; |
295 | #else |
296 | return Options {}; |
297 | #endif |
298 | } |
299 | |
300 | int main(int argc, char *argv[]) |
301 | { |
302 | QCoreApplication app(argc, argv); |
303 | QCoreApplication::setApplicationName("qmlformat" ); |
304 | QCoreApplication::setApplicationVersion(QT_VERSION_STR); |
305 | |
306 | QQmlToolingSettings settings(QLatin1String("qmlformat" )); |
307 | |
308 | const QString &useTabsSetting = QStringLiteral("UseTabs" ); |
309 | settings.addOption(name: useTabsSetting); |
310 | |
311 | const QString &indentWidthSetting = QStringLiteral("IndentWidth" ); |
312 | settings.addOption(name: indentWidthSetting, defaultValue: 4); |
313 | |
314 | const QString &normalizeSetting = QStringLiteral("NormalizeOrder" ); |
315 | settings.addOption(name: normalizeSetting); |
316 | |
317 | const QString &newlineSetting = QStringLiteral("NewlineType" ); |
318 | settings.addOption(name: newlineSetting, QStringLiteral("native" )); |
319 | |
320 | const QString &objectsSpacingSetting = QStringLiteral("ObjectsSpacing" ); |
321 | settings.addOption(name: objectsSpacingSetting); |
322 | |
323 | const QString &functionsSpacingSetting = QStringLiteral("FunctionsSpacing" ); |
324 | settings.addOption(name: functionsSpacingSetting); |
325 | |
326 | const auto options = buildCommandLineOptions(app); |
327 | if (!options.valid) { |
328 | for (const auto &error : options.errors) { |
329 | qWarning().noquote() << error; |
330 | } |
331 | |
332 | return -1; |
333 | } |
334 | |
335 | if (options.writeDefaultSettings) |
336 | return settings.writeDefaults() ? 0 : -1; |
337 | |
338 | auto getSettings = [&](const QString &file, Options options) { |
339 | // Perform formatting inplace if --files option is set. |
340 | if (!options.files.isEmpty()) |
341 | options.inplace = true; |
342 | |
343 | if (options.ignoreSettings || !settings.search(path: file)) |
344 | return options; |
345 | |
346 | Options perFileOptions = options; |
347 | |
348 | // Allow for tab settings to be overwritten by the command line |
349 | if (!options.indentWidthSet) { |
350 | if (settings.isSet(name: indentWidthSetting)) |
351 | perFileOptions.indentWidth = settings.value(name: indentWidthSetting).toInt(); |
352 | if (settings.isSet(name: useTabsSetting)) |
353 | perFileOptions.tabs = settings.value(name: useTabsSetting).toBool(); |
354 | } |
355 | |
356 | if (settings.isSet(name: normalizeSetting)) |
357 | perFileOptions.normalize = settings.value(name: normalizeSetting).toBool(); |
358 | |
359 | if (settings.isSet(name: newlineSetting)) |
360 | perFileOptions.newline = settings.value(name: newlineSetting).toString(); |
361 | |
362 | if (settings.isSet(name: objectsSpacingSetting)) |
363 | perFileOptions.objectsSpacing = settings.value(name: objectsSpacingSetting).toBool(); |
364 | |
365 | if (settings.isSet(name: functionsSpacingSetting)) |
366 | perFileOptions.functionsSpacing = settings.value(name: functionsSpacingSetting).toBool(); |
367 | |
368 | return perFileOptions; |
369 | }; |
370 | |
371 | bool success = true; |
372 | if (!options.files.isEmpty()) { |
373 | if (!options.arguments.isEmpty()) |
374 | qWarning() << "Warning: Positional arguments are ignored when -F is used" ; |
375 | |
376 | for (const QString &file : options.files) { |
377 | Q_ASSERT(!file.isEmpty()); |
378 | |
379 | if (!parseFile(filename: file, options: getSettings(file, options))) |
380 | success = false; |
381 | } |
382 | } else { |
383 | for (const QString &file : options.arguments) { |
384 | if (!parseFile(filename: file, options: getSettings(file, options))) |
385 | success = false; |
386 | } |
387 | } |
388 | |
389 | return success ? 0 : 1; |
390 | } |
391 | |