1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtXmlPatterns module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include <QtCore/QDir>
43 #include <QtCore/QtDebug>
44 #include <QtCore/QFile>
45 #include <QtCore/QFileInfo>
46 #include <QtCore/QStringList>
47 #include <QtCore/QTextCodec>
48 #include <QtCore/QTextStream>
49 #include <QtCore/QUrl>
50 #include <QtCore/QVariant>
51 #include <QtCore/QVector>
52 #include <QtCore/QCoreApplication>
54 #include <QtXmlPatterns/QXmlFormatter>
55 #include <QtXmlPatterns/QXmlItem>
56 #include <QtXmlPatterns/QXmlQuery>
57 #include <QtXmlPatterns/QXmlSerializer>
59 #include "private/qautoptr_p.h"
60 #include "qapplicationargument_p.h"
61 #include "qapplicationargumentparser_p.h"
63 #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE)
64 /* Needed for opening stdout with _fdopen & friends. io.h seems to not be
65 * needed on MinGW though. */
74 /* The two Q_DECLARE_METATYPE macros must appear before the code
75 * on a couple of HPUX platforms. */
80 Represents the name and value found in "-param name=value".
82 typedef QPair<QString, QString> Parameter;
83 Q_DECLARE_METATYPE(Parameter)
88 For the -output switch.
90 Q_DECLARE_METATYPE(QIODevice *)
93 \class PatternistApplicationParser
94 \brief Subclass to handle -param name=value
99 class PatternistApplicationParser : public QApplicationArgumentParser
102 inline PatternistApplicationParser(int argc, char **argv,
103 const QXmlNamePool &np) : QApplicationArgumentParser(argc, argv)
112 virtual ~PatternistApplicationParser()
114 /* QFile::~QFile() nor QFile::close() frees the handle when
115 * we use QFile::open() so we have to do it manually.
117 * "If stream is NULL, the invalid parameter handler is invoked," so
118 * lets try to avoid that. */
125 virtual QVariant convertToValue(const QApplicationArgument &arg,
126 const QString &input) const
128 if(arg.name() == QLatin1String("param"))
130 const int assign = input.indexOf(QLatin1Char('='));
134 message(QXmlPatternistCLI::tr("Each binding must contain an equal sign."));
138 const QString name(input.left(assign));
139 const QString value(input.mid(assign + 1));
141 if(!QXmlName::isNCName(name))
143 message(QXmlPatternistCLI::tr("The variable name must be a valid NCName, which %1 isn't.").arg(name));
147 /* The value.isNull() check ensures we can bind variables whose value is an empty string. */
148 return QVariant::fromValue(Parameter(name, value.isNull() ? QString(QLatin1String("")) : value ));
150 else if(arg.name() == QLatin1String("output"))
152 QFile *const f = new QFile(input);
154 if(f->open(QIODevice::WriteOnly))
155 return QVariant::fromValue(static_cast<QIODevice *>(f));
158 message(QXmlPatternistCLI::tr("Failed to open file %1 for writing: %2").arg(f->fileName(), f->errorString()));
162 else if(arg.name() == QLatin1String("initial-template"))
164 const QXmlName name(QXmlName::fromClarkName(input, m_namePool));
167 message(QXmlPatternistCLI::tr("%1 is an invalid Clark Name").arg(input));
171 return QVariant::fromValue(name);
174 return QApplicationArgumentParser::convertToValue(arg, input);
177 virtual QString typeToName(const QApplicationArgument &argument) const
179 if(argument.name() == QLatin1String("param"))
180 return QLatin1String("name=value");
181 else if(argument.name() == QLatin1String("output"))
182 return QLatin1String("local file");
184 return QApplicationArgumentParser::typeToName(argument);
187 virtual QVariant defaultValue(const QApplicationArgument &argument) const
189 if(argument.name() == QLatin1String("output"))
191 QFile *const out = new QFile();
194 /* If we don't open stdout in "binary" mode on Windows, it will translate
195 * 0xA into 0xD 0xA. */
196 _setmode(_fileno(stdout), _O_BINARY);
197 m_stdout = _wfdopen(_fileno(stdout), L"wb");
198 out->open(m_stdout, QIODevice::WriteOnly);
200 out->open(stdout, QIODevice::WriteOnly);
203 return QVariant::fromValue(static_cast<QIODevice *>(out));
206 return QApplicationArgumentParser::defaultValue(argument);
210 QXmlNamePool m_namePool;
212 mutable FILE * m_stdout;
216 static inline QUrl finalizeURI(const QApplicationArgumentParser &parser,
217 const QApplicationArgument &isURI,
218 const QApplicationArgument &arg)
222 const QString stringURI(parser.value(arg).toString());
224 if(parser.has(isURI))
225 userURI = QUrl::fromEncoded(stringURI.toLatin1());
227 userURI = QUrl::fromLocalFile(stringURI);
230 return QUrl::fromLocalFile(QDir::current().absolutePath() + QLatin1Char('/')).resolved(userURI);
233 int main(int argc, char **argv)
238 * We start from 2, because QApplicationArgumentParser
245 const QCoreApplication app(argc, argv);
246 QCoreApplication::setApplicationName(QLatin1String("xmlpatterns"));
248 QXmlNamePool namePool;
249 PatternistApplicationParser parser(argc, argv, namePool);
250 parser.setApplicationDescription(QLatin1String("A tool for running XQuery queries."));
251 parser.setApplicationVersion(QLatin1String("0.1"));
253 QApplicationArgument param(QLatin1String("param"),
254 QXmlPatternistCLI::tr("Binds an external variable. The value is directly available using the variable reference: $name."),
255 qMetaTypeId<Parameter>());
256 param.setMaximumOccurrence(-1);
257 parser.addArgument(param);
259 const QApplicationArgument noformat(QLatin1String("no-format"),
260 QXmlPatternistCLI::tr("By default output is formatted for readability. When specified, strict serialization is performed."));
261 parser.addArgument(noformat);
263 const QApplicationArgument isURI(QLatin1String("is-uri"),
264 QXmlPatternistCLI::tr("If specified, all filenames on the command line are interpreted as URIs instead of a local filenames."));
265 parser.addArgument(isURI);
267 const QApplicationArgument initialTemplateName(QLatin1String("initial-template"),
268 QXmlPatternistCLI::tr("The name of the initial template to call as a Clark Name."),
270 parser.addArgument(initialTemplateName);
272 /* The temporary object is required to compile with g++ 3.3. */
273 QApplicationArgument queryURI = QApplicationArgument(QLatin1String("query/stylesheet"),
274 QXmlPatternistCLI::tr("A local filename pointing to the query to run. If the name ends with .xsl it's assumed "
275 "to be an XSL-T stylesheet. If it ends with .xq, it's assumed to be an XQuery query. (In "
276 "other cases it's also assumed to be an XQuery query, but that interpretation may "
277 "change in a future release of Qt.)"),
279 queryURI.setMinimumOccurrence(1);
280 queryURI.setNameless(true);
281 parser.addArgument(queryURI);
283 QApplicationArgument focus = QApplicationArgument(QLatin1String("focus"),
284 QXmlPatternistCLI::tr("The document to use as focus. Mandatory "
285 "in case a stylesheet is used. This option is "
286 "also affected by the is-uris option."),
288 focus.setMinimumOccurrence(0);
289 focus.setNameless(true);
290 parser.addArgument(focus);
292 QApplicationArgument output(QLatin1String("output"),
293 QXmlPatternistCLI::tr("A local file to which the output should be written. "
294 "The file is overwritten, or if not exist, created. "
295 "If absent, stdout is used."),
296 qMetaTypeId<QIODevice *>());
297 parser.addArgument(output);
300 return parser.exitCode();
302 /* Get the query URI. */
303 const QUrl effectiveURI(finalizeURI(parser, isURI, queryURI));
305 QXmlQuery::QueryLanguage lang;
307 if(effectiveURI.toString().endsWith(QLatin1String(".xsl")))
308 lang = QXmlQuery::XSLT20;
310 lang = QXmlQuery::XQuery10;
312 if(lang == QXmlQuery::XQuery10 && parser.has(initialTemplateName))
314 parser.message(QXmlPatternistCLI::tr("An initial template name cannot be specified when running an XQuery."));
315 return QApplicationArgumentParser::ParseError;
318 QXmlQuery query(lang, namePool);
320 query.setInitialTemplateName(qvariant_cast<QXmlName>(parser.value(initialTemplateName)));
322 /* Bind external variables. */
324 const QVariantList parameters(parser.values(param));
325 const int len = parameters.count();
327 /* For tracking duplicates. */
328 QSet<QString> usedParameters;
330 for(int i = 0; i < len; ++i)
332 const Parameter p(qvariant_cast<Parameter>(parameters.at(i)));
334 if(usedParameters.contains(p.first))
336 parser.message(QXmlPatternistCLI::tr("Each parameter must be unique, %1 is specified at least twice.").arg(p.first));
337 return QApplicationArgumentParser::ParseError;
341 usedParameters.insert(p.first);
342 query.bindVariable(p.first, QXmlItem(p.second));
347 if(parser.has(focus))
349 if(!query.setFocus(finalizeURI(parser, isURI, focus)))
352 else if(lang == QXmlQuery::XSLT20 && !parser.has(initialTemplateName))
354 parser.message(QXmlPatternistCLI::tr("When a stylesheet is used, a "
355 "document must be specified as a focus, or an "
356 "initial template name must be specified, or both."));
357 return QApplicationArgumentParser::ParseError;
360 query.setQuery(effectiveURI);
362 const QPatternist::AutoPtr<QIODevice> outDevice(qvariant_cast<QIODevice *>(parser.value(output)));
364 Q_ASSERT(outDevice->isWritable());
368 typedef QPatternist::AutoPtr<QAbstractXmlReceiver> RecPtr;
371 if(parser.has(noformat))
372 receiver = RecPtr(new QXmlSerializer(query, outDevice.data()));
374 receiver = RecPtr(new QXmlFormatter(query, outDevice.data()));
376 const bool success = query.evaluateTo(receiver.data());
379 return parser.exitCode();