summaryrefslogtreecommitdiffstats
path: root/src/winrtrunner/main.cpp
blob: bf4e8fabf5cb1f254827a8d5008ce38b01bd9273 (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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtCore/QCommandLineParser>
#include <QtCore/QCoreApplication>
#include <QtCore/QDir>
#include <QtCore/QRegExp>
#include <QtCore/QStringList>
#include <QtCore/QMap>
#include <QtCore/QLoggingCategory>

#include <iostream>

#include "runner.h"

QT_USE_NAMESPACE

int main(int argc, char *argv[])
{
    // If logging rules are set via env variable, we pass these to the application we are running.
    // winrtrunner behaves different from other applications in the regard that its logging rules
    // have to be enabled explicitly. Setting "*=true" will not enable extended logging. Reason is
    // CI setting "*=true" if an auto test fails and additional winrtrunner output might just
    // confuse users.
    const QByteArray loggingRules = qgetenv("QT_LOGGING_RULES");
    const QList<QByteArray> rules = loggingRules.split(';');
    QRegExp runnerExp(QLatin1String("^qt\\.winrtrunner.*\\s*=\\s*true\\s*$"));
    bool runnerRuleFound = false;
    for (const QByteArray &rule : rules) {
        if (runnerExp.indexIn(QLatin1String(rule)) != -1) {
            runnerRuleFound = true;
            break;
        }
    }
    if (!runnerRuleFound)
        qunsetenv("QT_LOGGING_RULES");
    QCoreApplication a(argc, argv);
    QCommandLineParser parser;
    parser.setApplicationDescription(QLatin1String("winrtrunner installs, runs, and collects test "
                                                   "results for packages made with Qt."));
    parser.addPositionalArgument(QStringLiteral("package [arguments]"),
                                 QLatin1String("The executable or package manifest to act upon. "
                                               "Arguments after the package name will be passed "
                                               "to the application when it starts."));

    QCommandLineOption testOption(QStringLiteral("test"),
                                  QLatin1String("Install, start, collect output, stop (if needed), "
                                                "and uninstall the package. This is the "
                                                "default action of winrtrunner."));
    parser.addOption(testOption);

    QCommandLineOption startOption(QStringLiteral("start"),
                                   QLatin1String("Start the package. The package is installed if "
                                                 "it is not already installed. Pass --install to "
                                                 "force reinstallation."));
    parser.addOption(startOption);

    QCommandLineOption debugOption(QStringLiteral("debug"),
                                   QLatin1String("Start the package with the debugger attached. "
                                                 "The package is installed if it is not already "
                                                 "installed. Pass --install to force "
                                                 "reinstallation."),
                                   QLatin1Literal("debugger"));
    parser.addOption(debugOption);

    QCommandLineOption debuggerArgumentsOption(QStringLiteral("debugger-arguments"),
                                               QLatin1String("Arguments that are passed to the "
                                                             "debugger when --debug is used. If no "
                                                             "debugger was provided this option is "
                                                             "ignored."),
                                               QLatin1String("arguments"));
    parser.addOption(debuggerArgumentsOption);

    QCommandLineOption suspendOption(QStringLiteral("suspend"),
                                     QLatin1String("Suspend a running package. When combined "
                                                   "with --stop or --test, the app will be "
                                                   "suspended before being terminated."));
    parser.addOption(suspendOption);

    QCommandLineOption stopOption(QStringLiteral("stop"),
                                  QLatin1String("Terminate a running package. Can be be "
                                                "combined with --start and --suspend."));
    parser.addOption(stopOption);

    QCommandLineOption waitOption(QStringLiteral("wait"),
                                  QLatin1String("If the package is running, waits the given "
                                                "number of seconds before continuing to the next "
                                                "task. Passing 0 causes the runner to wait "
                                                "indefinitely."),
                                  QStringLiteral("seconds"));
    parser.addOption(waitOption);

    QCommandLineOption installOption(QStringLiteral("install"),
                                     QStringLiteral("(Re)installs the package."));
    parser.addOption(installOption);

    QCommandLineOption removeOption(QStringLiteral("remove"),
                                    QStringLiteral("Uninstalls the package."));
    parser.addOption(removeOption);

    QCommandLineOption deviceOption(QStringLiteral("device"),
                                    QLatin1String("Specifies the device to target as a device name "
                                                  "or index. Use --list-devices to find available "
                                                  "devices. The default device is the first device "
                                                  "found for the active run profile."),
                                    QStringLiteral("name|index"));
    parser.addOption(deviceOption);

    QCommandLineOption profileOption(QStringLiteral("profile"),
                                     QStringLiteral("Force a particular run profile."),
                                     QStringLiteral("name"));
    parser.addOption(profileOption);

    QCommandLineOption listDevicesOption(QStringLiteral("list-devices"),
                                         QLatin1String("List the available devices "
                                                       "(for use with --device)."));
    parser.addOption(listDevicesOption);

    QCommandLineOption verbosityOption(QStringLiteral("verbose"),
                                       QLatin1String("The verbosity level of the message output "
                                                     "(0 - silent, 1 - info, 2 - debug). Defaults to 1."),
                                       QStringLiteral("level"), QStringLiteral("1"));
    parser.addOption(verbosityOption);

    QCommandLineOption ignoreErrorsOption(QStringLiteral("ignore-errors"),
                                          QStringLiteral("Always exit with code 0, regardless of the error state."));
    parser.addOption(ignoreErrorsOption);

    QCommandLineOption loopbackExemptOption(QStringLiteral("loopbackexempt"),
                                            QLatin1String("Enables localhost communication for clients,"
                                                          "servers or both. Adding this possibility "
                                                          "for servers needs elevated rights and "
                                                          "might ask for these in a dialog."
                                                          "Possible values: client, server, clientserver"),
                                            QStringLiteral("mode"));
    parser.addOption(loopbackExemptOption);

    parser.addHelpOption();
    parser.setSingleDashWordOptionMode(QCommandLineParser::ParseAsLongOptions);
    QStringList arguments = QCoreApplication::arguments();
    parser.parse(arguments);

    QStringList filterRules = QStringList() // Default logging rules
            << QStringLiteral("qt.winrtrunner.warning=true")
            << QStringLiteral("qt.winrtrunner.critical=true")
            << QStringLiteral("qt.winrtrunner.app=true");
    if (parser.isSet(verbosityOption)) {
        bool ok;
        uint verbosity = parser.value(verbosityOption).toUInt(&ok);
        if (!ok || verbosity > 2) {
            qCCritical(lcWinRtRunner) << "Incorrect value specified for verbosity.";
            parser.showHelp(1);
        }
        switch (verbosity) {
        case 2: // Enable debug print
            filterRules.append(QStringLiteral("qt.winrtrunner.debug=true"));
            break;
        case 1: // Remove warnings
            filterRules.removeFirst();
            // fall through
        case 0: // Silent
            filterRules.removeFirst();
            // fall through
        default: // Impossible
            break;
        }
    }
    bool loopbackExemptClient = false;
    bool loopbackExemptServer = false;
    if (parser.isSet(loopbackExemptOption)) {
        const QString value = parser.value(loopbackExemptOption);
        if (value == QStringLiteral("client")) {
            loopbackExemptClient = true;
        } else if (value == QStringLiteral("server")) {
            loopbackExemptServer = true;
        } else if (value == QStringLiteral("clientserver")) {
            loopbackExemptClient = true;
            loopbackExemptServer = true;
        } else {
            qCCritical(lcWinRtRunner) << "Incorrect value specified for loopbackexempt.";
            parser.showHelp(1);
        }
    }
    QLoggingCategory::setFilterRules(filterRules.join(QLatin1Char('\n')));

    if (parser.isSet(listDevicesOption)) {
        std::wcout << "Available devices:\n";
        const QMap<QString, QStringList> deviceNames = Runner::deviceNames();
        for (auto it = deviceNames.cbegin(), end = deviceNames.cend(); it != end; ++it) {
            std::wcout << reinterpret_cast<const wchar_t *>(it.key().utf16()) << ":\n";
            int index = 0;
            for (const QString &device : it.value()) {
                std::wcout << "  " << index++ << ' '
                           << reinterpret_cast<const wchar_t *>(device.utf16()) << '\n';
            }
        }
        std::wcout << std::endl;
        return 0;
    }

    // Process front-end args
    if (parser.positionalArguments().count() < 1)
        parser.showHelp(parser.isSet(QStringLiteral("help")) ? 0 : 1);
    const QString app = parser.positionalArguments().first();
    const int appArgsPos = arguments.indexOf(app) + 1;
    const QStringList mainArgs = arguments.mid(0, appArgsPos);
    QStringList appArgs = arguments.mid(appArgsPos);
    parser.process(mainArgs);

    // Exit codes:
    // 1 - Bad arguments
    // 2 - Bad package or no backend available
    // 3 - Installation failed
    // 4 - Removal failed
    // 5 - Start failed
    // 6 - Suspend failed
    // 7 - Stop failed
    // 8 - Test setup failed
    // 9 - Test results retrieval failed
    // 10 - Enabling debugging failed
    // In "test" mode, the exit code of the app is returned

    bool ignoreErrors = parser.isSet(ignoreErrorsOption);
    bool testEnabled = parser.isSet(testOption);
    bool startEnabled = testEnabled || parser.isSet(startOption) || parser.isSet(debugOption);
    bool suspendEnabled = parser.isSet(suspendOption);
    bool waitEnabled = testEnabled || parser.isSet(waitOption);
    bool stopEnabled = !testEnabled && parser.isSet(stopOption); // test and stop are mutually exclusive
    bool installEnabled = testEnabled || startEnabled || parser.isSet(installOption);
    bool removeBeforeInstall = testEnabled || parser.isSet(installOption);
    bool removeEnabled = testEnabled || parser.isSet(removeOption);
    // Default to test mode if no conflicting arguments were passed
    if (!testEnabled && !installEnabled && !startEnabled && !stopEnabled && !suspendEnabled && !removeEnabled)
        testEnabled = installEnabled = removeBeforeInstall = startEnabled = waitEnabled = stopEnabled = removeEnabled = true;

    int waitTime = parser.value(waitOption).toInt();
    if (!waitTime && testEnabled)
        waitTime = 300; // The maximum wait period for test cases is 300 seconds (5 minutes)

    // Set up runner
    Runner runner(app, appArgs, parser.value(profileOption), parser.value(deviceOption));
    if (!runner.isValid())
        return ignoreErrors ? 0 : 2;

    if (testEnabled && !runner.setupTest()) {
        qCDebug(lcWinRtRunner) << "Test setup failed, exiting with code 8.";
        return ignoreErrors ? 0 : 8;
    }

    if (installEnabled && !runner.install(removeBeforeInstall)) {
        qCDebug(lcWinRtRunner) << "Installation failed, exiting with code 3.";
        return ignoreErrors ? 0 : 3;
    }

    if (loopbackExemptClient && !runner.setLoopbackExemptClientEnabled(true)) {
        qCDebug(lcWinRtRunner) << "Could not enable loopback exemption for client, "
                                  "exiting with code 3.";
        return ignoreErrors ? 0 : 3;
    }

    if (loopbackExemptServer && !runner.setLoopbackExemptServerEnabled(true)) {
        qCDebug(lcWinRtRunner) << "Could not enable loopback exemption for server, "
                                  "exiting with code 3.";
        return ignoreErrors ? 0 : 3;
    }

    if (!loggingRules.isNull() && !runner.setLoggingRules(loggingRules)) {
        qCDebug(lcWinRtRunner) << "Could not set logging rules, exiting with code 3.";
        return ignoreErrors ? 0 : 3;
    }

    if (parser.isSet(debugOption)) {
        const QString &debuggerExecutable = parser.value(debugOption);
        const QString &debuggerArguments = parser.value(debuggerArgumentsOption);
        qCDebug(lcWinRtRunner) << "Debugger:         " << debuggerExecutable;
        qCDebug(lcWinRtRunner) << "Debugger Options: " << debuggerArguments;
        if (debuggerExecutable.isEmpty()
                || !runner.enableDebugging(debuggerExecutable, debuggerArguments)) {
            qCDebug(lcWinRtRunner) << "Failed to enable debugging, exiting with code 10.";
            return ignoreErrors ? 0 : 10;
        }
    }

    bool startFailed = startEnabled && !runner.start();

    if (parser.isSet(debugOption) && !runner.disableDebugging())
        qCDebug(lcWinRtRunner) << "Failed to disable debugging";

    if (startFailed) {
        qCDebug(lcWinRtRunner) << "Start failed, exiting with code 5.";
        return ignoreErrors ? 0 : 5;
    }

    qint64 pid = runner.pid();
    if (pid != -1)
        qCWarning(lcWinRtRunner) << "App started with process ID" << pid;

    if (waitEnabled)
        runner.wait(waitTime);

    if (loopbackExemptClient)
        runner.setLoopbackExemptClientEnabled(false);

    if (loopbackExemptServer)
        runner.setLoopbackExemptServerEnabled(false);

    if (suspendEnabled && !runner.suspend()) {
        qCDebug(lcWinRtRunner) << "Suspend failed, exiting with code 6.";
        return ignoreErrors ? 0 : 6;
    }

    if (stopEnabled && !runner.stop()) {
        qCDebug(lcWinRtRunner) << "Stop failed, exiting with code 7.";
        return ignoreErrors ? 0 : 7;
    }

    if (testEnabled && !runner.collectTest()) {
        qCDebug(lcWinRtRunner) << "Collect test failed, exiting with code 9.";
        return ignoreErrors ? 0 : 9;
    }

    if (removeEnabled && !runner.remove()) {
        qCDebug(lcWinRtRunner) << "Remove failed, exiting with code 4.";
        return ignoreErrors ? 0 : 4;
    }

    if (stopEnabled) {
        int exitCode = runner.exitCode();
        if (exitCode == -1)
            return 0; // Exit code unknown; not necessarily an error
        qCWarning(lcWinRtRunner) <<  "App exited with code" << exitCode;
        return ignoreErrors ? 0 : exitCode;
    }

    return 0;
}