File indexing completed on 2024-05-12 05:12:40

0001 /*
0002     Copyright (C) 2012  Kevin Krammer <krammer@kde.org>
0003 
0004     This program is free software; you can redistribute it and/or modify
0005     it under the terms of the GNU General Public License as published by
0006     the Free Software Foundation; either version 2 of the License, or
0007     (at your option) any later version.
0008 
0009     This program is distributed in the hope that it will be useful,
0010     but WITHOUT ANY WARRANTY; without even the implied warranty of
0011     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0012     GNU General Public License for more details.
0013 
0014     You should have received a copy of the GNU General Public License along
0015     with this program; if not, write to the Free Software Foundation, Inc.,
0016     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
0017 */
0018 
0019 #include "commandrunner.h"
0020 
0021 #include "abstractcommand.h"
0022 #include "commandfactory.h"
0023 #include "errorreporter.h"
0024 
0025 #include <QCoreApplication>
0026 
0027 #include <iostream>
0028 
0029 CommandRunner::CommandRunner(const QStringList *args)
0030     : mCommand(nullptr),
0031       mParsedArgs(args)
0032 {
0033 }
0034 
0035 CommandRunner::~CommandRunner()
0036 {
0037     delete mCommand;
0038 }
0039 
0040 int CommandRunner::start()
0041 {
0042     CommandFactory factory(mParsedArgs);
0043     mCommand = factory.createCommand();
0044     Q_ASSERT(mCommand != nullptr);
0045 
0046     connect(mCommand, &AbstractCommand::error, this, &CommandRunner::onCommandError);
0047 
0048     if (mCommand->init(*mParsedArgs) == AbstractCommand::InvalidUsage) {
0049         delete mCommand;
0050         mCommand = nullptr;
0051         return AbstractCommand::InvalidUsage;
0052     }
0053 
0054     mExitCode = AbstractCommand::NoError;       // no errors reported yet
0055 
0056     connect(mCommand, &AbstractCommand::finished, this, &CommandRunner::onCommandFinished);
0057 
0058     QMetaObject::invokeMethod(mCommand, "start", Qt::QueuedConnection);
0059 
0060     return AbstractCommand::NoError;
0061 }
0062 
0063 void CommandRunner::onCommandFinished(int exitCode)
0064 {
0065     // If no exit code is emplicitly specified, use the accumulated
0066     // exit code from the processing loop.
0067     if (exitCode == AbstractCommand::DefaultError) exitCode = mExitCode;
0068     QCoreApplication::exit(exitCode);
0069 }
0070 
0071 void CommandRunner::onCommandError(const QString &error)
0072 {
0073     ErrorReporter::error(error);
0074     // Set the eventual exit code to RuntimeError, but only if
0075     // it is not already set.
0076     if (mExitCode == AbstractCommand::NoError) mExitCode = AbstractCommand::RuntimeError;
0077 }