a5b72234dd7bdbe772ff83265e7013a8f14d225e
[quassel.git] / src / common / cliparser.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel IRC Team                         *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
5  *   This program is free software; you can redistribute it and/or modify  *
6  *   it under the terms of the GNU General Public License as published by  *
7  *   the Free Software Foundation; either version 2 of the License, or     *
8  *   (at your option) version 3.                                           *
9  *                                                                         *
10  *   This program is distributed in the hope that it will be useful,       *
11  *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
12  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
13  *   GNU General Public License for more details.                          *
14  *                                                                         *
15  *   You should have received a copy of the GNU General Public License     *
16  *   along with this program; if not, write to the                         *
17  *   Free Software Foundation, Inc.,                                       *
18  *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
19  ***************************************************************************/
20 #include "cliparser.h"
21
22 #include <QDir>
23 #include <QDebug>
24 #include <QString>
25 #include <QFileInfo>
26
27 #ifdef HAVE_KDE
28 #  include <KCmdLineArgs>
29 #endif
30
31 CliParser::CliParser() {
32
33 }
34
35 #ifdef HAVE_KDE
36 void CliParser::addArgument(const QString &longName, const CliParserArg &arg) {
37   if(arg.shortName != 0) {
38     _cmdLineOptions.add(QByteArray().append(arg.shortName));
39   }
40   _cmdLineOptions.add(longName.toUtf8(), ki18n(arg.help.toUtf8()), arg.def.toUtf8());
41 }
42
43 bool CliParser::init(const QStringList &) {
44   KCmdLineArgs::addCmdLineOptions(_cmdLineOptions);
45   return true;
46 }
47
48 QString CliParser::value(const QString &longName) {
49   return KCmdLineArgs::parsedArgs()->getOption(longName.toUtf8());
50 }
51
52 bool CliParser::isSet(const QString &longName) {
53   return KCmdLineArgs::parsedArgs()->isSet(longName.toUtf8());
54 }
55
56 void CliParser::usage() {
57   KCmdLineArgs::usage();
58 }
59
60 #else
61 void CliParser::addArgument(const QString &longName_, const CliParserArg &arg) {
62   QString longName = longName_;
63   longName.remove(QRegExp("\\s*<.*>\\s*")); // KCmdLineArgs takes args of the form "arg <defval>"
64   if(argsHash.contains(longName)) qWarning() << "Warning: Multiple definition of argument" << longName;
65   if(arg.shortName != 0 && !lnameOfShortArg(arg.shortName).isNull())
66     qWarning().nospace() << "Warning: Redefining shortName '" << arg.shortName << "' for " << longName << " previously defined for " << lnameOfShortArg(arg.shortName);
67   argsHash.insert(longName, arg);
68 }
69
70 bool CliParser::addLongArg(const CliParserArg::CliArgType type, const QString &name, const QString &value) {
71   if(argsHash.contains(name)){
72     if(type == CliParserArg::CliArgOption && argsHash.value(name).type == type) {
73       argsHash[name].value = escapedValue(value);
74       return true;
75     }
76     else if (type == CliParserArg::CliArgSwitch && argsHash.value(name).type == type) {
77       argsHash[name].boolValue = true;
78       return true;
79     }
80   }
81   qWarning() << "Warning: Unrecognized argument:" << name;
82   return false;
83 }
84
85 bool CliParser::addShortArg(const CliParserArg::CliArgType type, const char shortName, const QString &value) {
86   QString longName = lnameOfShortArg(shortName);
87   if(!longName.isNull()) {
88     if(type == CliParserArg::CliArgOption && argsHash.value(longName).type == type) {
89       argsHash[longName].value = escapedValue(value);
90       return true;
91     }
92     else if (type == CliParserArg::CliArgSwitch) {
93       if(argsHash.value(longName).type == type) {
94         argsHash[longName].boolValue = true;
95         return true;
96       }
97       // arg is an option but detected as a switch -> argument is missing
98       else {
99         qWarning().nospace() << "Warning: '" << shortName << "' is an option which needs an argument";
100         return false;
101       }
102     }
103   }
104   qWarning().nospace() << "Warning: Unrecognized argument: '" << shortName << "'";
105   return false;
106 }
107
108 QString CliParser::escapedValue(const QString &value) {
109   QString escapedValue = value;
110   if(escapedValue.startsWith("~"))
111     escapedValue.replace(0, 1, QDir::homePath());
112
113   return escapedValue;
114 }
115
116 bool CliParser::init(const QStringList &args) {
117   argsRaw = args;
118   QStringList::const_iterator currentArg;
119   for (currentArg = argsRaw.constBegin(); currentArg != argsRaw.constEnd(); ++currentArg) {
120     if(currentArg->startsWith("--")) {
121       // long
122       QString name;
123       if(currentArg->contains("=")) {
124         // option
125         QStringList tmp = currentArg->mid(2).split("=");
126         name = tmp.at(0);
127         QString value;
128         // this is needed to allow --option=""
129         if(tmp.at(1).isNull()) value = QString("");
130         else value = tmp.at(1);
131         if(!addLongArg(CliParserArg::CliArgOption, name, value)) return false;
132       }
133       else {
134         // switch
135         name = currentArg->mid(2);
136         if(!addLongArg(CliParserArg::CliArgSwitch, name)) return false;
137       }
138     }
139     else if(currentArg->startsWith("-")) {
140       // short
141       char name;
142       QStringList::const_iterator nextArg = currentArg+1;
143       // if next arg is a short/long option/switch the current arg is one too
144       if(nextArg == argsRaw.constEnd() || nextArg->startsWith("-")) {
145         // switch
146         for (int i = 0; i < currentArg->mid(1).toAscii().size(); i++) {
147           name = currentArg->mid(1).toAscii().at(i);
148           if(!addShortArg(CliParserArg::CliArgSwitch, name)) return false;
149         }
150       }
151       // if next arg is is no option/switch it's an argument to a shortoption
152       else {
153         // option
154         // short options are not freely mixable with other shortargs
155         if(currentArg->mid(1).toAscii().size() > 1) {
156           qWarning() << "Warning: Shortoptions may not be combined with other shortoptions or switches";
157           return false;
158         }
159         QString value;
160         bool skipNext = false;
161         if(nextArg != argsRaw.constEnd()) {
162           value = nextArg->toLocal8Bit();
163           skipNext = true;
164         }
165         else value = currentArg->toLocal8Bit();
166         name = currentArg->mid(1).toAscii().at(0);
167         // we took one argument as argument to an option so skip it next time
168         if(skipNext) currentArg++;
169         if(!addShortArg(CliParserArg::CliArgOption, name, value)) return false;
170       }
171     }
172     else {
173       // we don't support plain arguments without -/--
174       if(currentArg->toLatin1() != argsRaw.at(0)) return false;
175     }
176   }
177   return true;
178 }
179
180 void CliParser::usage() {
181   qWarning() << "Usage:" << QFileInfo(argsRaw.at(0)).completeBaseName() << "[arguments]";
182
183   // get size of longName field
184   QStringList keys = argsHash.keys();
185   uint lnameFieldSize = 0;
186   foreach (QString key, keys) {
187     uint size = 0;
188     if(argsHash.value(key).type == CliParserArg::CliArgOption)
189       size += key.size()*2;
190     else
191       size += key.size();
192     // this is for " --...=[....] "
193     size += 8;
194     if(size > lnameFieldSize) lnameFieldSize = size;
195   }
196
197   QHash<QString, CliParserArg>::const_iterator arg;
198   for(arg = argsHash.constBegin(); arg != argsHash.constEnd(); ++arg) {
199     QString output;
200     QString lnameField;
201
202     if(arg.value().shortName) {
203       output.append(" -").append(arg.value().shortName).append(",");
204     }
205     else output.append("    ");
206     lnameField.append(" --").append(arg.key());
207     if(arg.value().type == CliParserArg::CliArgOption) {
208       lnameField.append("=[").append(arg.key().toUpper()).append("]");
209     }
210     output.append(lnameField.leftJustified(lnameFieldSize));
211     if(!arg.value().help.isEmpty()) {
212       output.append(arg.value().help);
213     }
214     if(arg.value().type == CliParserArg::CliArgOption && !arg.value().def.isNull()) {
215       output.append(". Default is: ").append(arg.value().def);
216     }
217     qWarning() << output.toLatin1();
218   }
219 }
220
221 QString CliParser::value(const QString &longName) {
222   if(argsHash.contains(longName) && argsHash.value(longName).type == CliParserArg::CliArgOption) {
223     if(!argsHash.value(longName).value.isNull())
224       return argsHash.value(longName).value;
225     else
226       return argsHash.value(longName).def;
227   }
228   else {
229     qWarning() << "Warning: Requested value of not defined argument" << longName << "or argument is a switch";
230     return QString();
231   }
232 }
233
234 bool CliParser::isSet(const QString &longName) {
235   if(argsHash.contains(longName)) {
236     if(argsHash.value(longName).type == CliParserArg::CliArgOption) return !argsHash.value(longName).value.isNull();
237     else return argsHash.value(longName).boolValue;
238   }
239   else {
240     qWarning() << "Warning: Requested isSet of not defined argument" << longName;
241     return false;
242   }
243 }
244
245 QString CliParser::lnameOfShortArg(const char arg) {
246   QHash<QString, CliParserArg>::const_iterator cur;
247   for (cur = argsHash.constBegin(); cur != argsHash.constEnd(); ++cur) {
248     if(cur.value().shortName == arg) return cur.key();
249   }
250   return QString();
251 }
252
253 #endif