File indexing completed on 2024-04-28 16:44:28

0001 /*
0002  *  SPDX-FileCopyrightText: 2002 David Faure <faure@kde.org>
0003  *  SPDX-FileCopyrightText: 2008 Pino Toscano <pino@kde.org>
0004  *
0005  *  SPDX-License-Identifier: LGPL-2.0-or-later
0006  */
0007 
0008 #include <KAboutData>
0009 #include <KLocalizedString>
0010 
0011 #include <QCommandLineOption>
0012 #include <QCommandLineParser>
0013 #include <QCoreApplication>
0014 #include <QFile>
0015 #include <QMimeDatabase>
0016 #include <QMimeType>
0017 
0018 #include <stdio.h>
0019 
0020 int main(int argc, char *argv[])
0021 {
0022     QCoreApplication app(argc, argv);
0023 
0024     KLocalizedString::setApplicationDomain("kmimetypefinder5");
0025 
0026     KAboutData aboutData(QLatin1String("kmimetypefinder"), i18n("MIME Type Finder"), QLatin1String(PROJECT_VERSION));
0027     aboutData.setShortDescription(i18n("Gives the MIME type for a given file"));
0028     KAboutData::setApplicationData(aboutData);
0029 
0030     QCommandLineParser parser;
0031     aboutData.setupCommandLine(&parser);
0032     parser.addOption(
0033         QCommandLineOption(QStringList() << QLatin1String("c") << QLatin1String("content"), i18n("Use only the file content for determining the MIME type.")));
0034     parser.addOption(QCommandLineOption(QStringList() << QLatin1String("f") << QLatin1String("filename-only"),
0035                                         i18n("Whether use the file name only for determining the MIME type. Not used if -c is specified.")));
0036     parser.addPositionalArgument(QLatin1String("filename"), i18n("The filename to test. '-' to read from stdin."));
0037 
0038     parser.process(app);
0039     aboutData.processCommandLine(&parser);
0040 
0041     if (parser.positionalArguments().count() < 1) {
0042         printf("No filename specified\n");
0043         return 1;
0044     }
0045     const QString fileName = parser.positionalArguments().at(0);
0046     QMimeDatabase db;
0047     QMimeType mime;
0048     if (fileName == QLatin1String("-")) {
0049         QFile qstdin;
0050         qstdin.open(stdin, QIODevice::ReadOnly);
0051         const QByteArray data = qstdin.readAll();
0052         mime = db.mimeTypeForData(data);
0053     } else if (parser.isSet(QStringLiteral("c"))) {
0054         mime = db.mimeTypeForFile(fileName, QMimeDatabase::MatchContent);
0055     } else if (parser.isSet(QStringLiteral("f"))) {
0056         mime = db.mimeTypeForFile(fileName, QMimeDatabase::MatchExtension);
0057     } else {
0058         mime = db.mimeTypeForFile(fileName);
0059     }
0060     if (!mime.isDefault()) {
0061         printf("%s\n", mime.name().toLatin1().constData());
0062     } else {
0063         return 1; // error
0064     }
0065 
0066     return 0;
0067 }