2116577db18c3e4f3650014b2740fe2601ae89a7
[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   if(argsHash.contains(longName)) qWarning() << "Warning: Multiple definition of argument" << longName;
63   if(arg.shortName != 0 && !lnameOfShortArg(arg.shortName).isNull())
64     qWarning().nospace() << "Warning: Redefining shortName '" << arg.shortName << "' for " << longName << " previously defined for " << lnameOfShortArg(arg.shortName);
65   argsHash.insert(longName, arg);
66 }
67
68 bool CliParser::addLongArg(const CliParserArg::CliArgType type, const QString &name, const QString &value) {
69   if(argsHash.contains(name)){
70     if(type == CliParserArg::CliArgOption && argsHash.value(name).type == type) {
71       argsHash[name].value = escapedValue(value);
72       return true;
73     }
74     else if (type == CliParserArg::CliArgSwitch && argsHash.value(name).type == type) {
75       argsHash[name].boolValue = true;
76       return true;
77     }
78   }
79   qWarning() << "Warning: Unrecognized argument:" << name;
80   return false;
81 }
82
83 bool CliParser::addShortArg(const CliParserArg::CliArgType type, const char shortName, const QString &value) {
84   QString longName = lnameOfShortArg(shortName);
85   if(!longName.isNull()) {
86     if(type == CliParserArg::CliArgOption && argsHash.value(longName).type == type) {
87       argsHash[longName].value = escapedValue(value);
88       return true;
89     }
90     else if (type == CliParserArg::CliArgSwitch) {
91       if(argsHash.value(longName).type == type) {
92         argsHash[longName].boolValue = true;
93         return true;
94       }
95       // arg is an option but detected as a switch -> argument is missing
96       else {
97         qWarning().nospace() << "Warning: '" << shortName << "' is an option which needs an argument";
98         return false;
99       }
100     }
101   }
102   qWarning().nospace() << "Warning: Unrecognized argument: '" << shortName << "'";
103   return false;
104 }
105
106 QString CliParser::escapedValue(const QString &value) {
107   QString escapedValue = value;
108   if(escapedValue.startsWith("~"))
109     escapedValue.replace(0, 1, QDir::homePath());
110
111   return escapedValue;
112 }
113
114 bool CliParser::init(const QStringList &args) {
115   argsRaw = args;
116   QStringList::const_iterator currentArg;
117   for (currentArg = argsRaw.constBegin(); currentArg != argsRaw.constEnd(); ++currentArg) {
118     if(currentArg->startsWith("--")) {
119       // long
120       QString name;
121       if(currentArg->contains("=")) {
122         // option
123         QStringList tmp = currentArg->mid(2).split("=");
124         name = tmp.at(0);
125         QString value;
126         // this is needed to allow --option=""
127         if(tmp.at(1).isNull()) value = QString("");
128         else value = tmp.at(1);
129         if(!addLongArg(CliParserArg::CliArgOption, name, value)) return false;
130       }
131       else {
132         // switch
133         name = currentArg->mid(2);
134         if(!addLongArg(CliParserArg::CliArgSwitch, name)) return false;
135       }
136     }
137     else if(currentArg->startsWith("-")) {
138       // short
139       char name;
140       QStringList::const_iterator nextArg = currentArg+1;
141       // if next arg is a short/long option/switch the current arg is one too
142       if(nextArg == argsRaw.constEnd() || nextArg->startsWith("-")) {
143         // switch
144         for (int i = 0; i < currentArg->mid(1).toAscii().size(); i++) {
145           name = currentArg->mid(1).toAscii().at(i);
146           if(!addShortArg(CliParserArg::CliArgSwitch, name)) return false;
147         }
148       }
149       // if next arg is is no option/switch it's an argument to a shortoption
150       else {
151         // option
152         // short options are not freely mixable with other shortargs
153         if(currentArg->mid(1).toAscii().size() > 1) {
154           qWarning() << "Warning: Shortoptions may not be combined with other shortoptions or switches";
155           return false;
156         }
157         QString value;
158         bool skipNext = false;
159         if(nextArg != argsRaw.constEnd()) {
160           value = nextArg->toLocal8Bit();
161           skipNext = true;
162         }
163         else value = currentArg->toLocal8Bit();
164         name = currentArg->mid(1).toAscii().at(0);
165         // we took one argument as argument to an option so skip it next time
166         if(skipNext) currentArg++;
167         if(!addShortArg(CliParserArg::CliArgOption, name, value)) return false;
168       }
169     }
170     else {
171       // we don't support plain arguments without -/--
172       if(currentArg->toLatin1() != argsRaw.at(0)) return false;
173     }
174   }
175   return true;
176 }
177
178 void CliParser::usage() {
179   qWarning() << "Usage:" << QFileInfo(argsRaw.at(0)).completeBaseName() << "[arguments]";
180
181   // get size of longName field
182   QStringList keys = argsHash.keys();
183   uint lnameFieldSize = 0;
184   foreach (QString key, keys) {
185     uint size = 0;
186     if(argsHash.value(key).type == CliParserArg::CliArgOption)
187       size += key.size()*2;
188     else
189       size += key.size();
190     // this is for " --...=[....] "
191     size += 8;
192     if(size > lnameFieldSize) lnameFieldSize = size;
193   }
194
195   QHash<QString, CliParserArg>::const_iterator arg;
196   for(arg = argsHash.constBegin(); arg != argsHash.constEnd(); ++arg) {
197     QString output;
198     QString lnameField;
199
200     if(arg.value().shortName) {
201       output.append(" -").append(arg.value().shortName).append(",");
202     }
203     else output.append("    ");
204     lnameField.append(" --").append(arg.key());
205     if(arg.value().type == CliParserArg::CliArgOption) {
206       lnameField.append("=[").append(arg.key().toUpper()).append("]");
207     }
208     output.append(lnameField.leftJustified(lnameFieldSize));
209     if(!arg.value().help.isEmpty()) {
210       output.append(arg.value().help);
211     }
212     if(arg.value().type == CliParserArg::CliArgOption && !arg.value().def.isNull()) {
213       output.append(". Default is: ").append(arg.value().def);
214     }
215     qWarning() << output.toLatin1();
216   }
217 }
218
219 QString CliParser::value(const QString &longName) {
220   if(argsHash.contains(longName) && argsHash.value(longName).type == CliParserArg::CliArgOption) {
221     if(!argsHash.value(longName).value.isNull())
222       return argsHash.value(longName).value;
223     else
224       return argsHash.value(longName).def;
225   }
226   else {
227     qWarning() << "Warning: Requested value of not defined argument" << longName << "or argument is a switch";
228     return QString();
229   }
230 }
231
232 bool CliParser::isSet(const QString &longName) {
233   if(argsHash.contains(longName)) {
234     if(argsHash.value(longName).type == CliParserArg::CliArgOption) return !argsHash.value(longName).value.isNull();
235     else return argsHash.value(longName).boolValue;
236   }
237   else {
238     qWarning() << "Warning: Requested isSet of not defined argument" << longName;
239     return false;
240   }
241 }
242
243 QString CliParser::lnameOfShortArg(const char arg) {
244   QHash<QString, CliParserArg>::const_iterator cur;
245   for (cur = argsHash.constBegin(); cur != argsHash.constEnd(); ++cur) {
246     if(cur.value().shortName == arg) return cur.key();
247   }
248   return QString();
249 }
250
251 #endif