keepassxc

Форк
0
/
Command.cpp 
210 строк · 8.8 Кб
1
/*
2
 *  Copyright (C) 2019 KeePassXC Team <team@keepassxc.org>
3
 *
4
 *  This program is free software: you can redistribute it and/or modify
5
 *  it under the terms of the GNU General Public License as published by
6
 *  the Free Software Foundation, either version 2 or (at your option)
7
 *  version 3 of the License.
8
 *
9
 *  This program is distributed in the hope that it will be useful,
10
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 *  GNU General Public License for more details.
13
 *
14
 *  You should have received a copy of the GNU General Public License
15
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
 */
17

18
#include "Add.h"
19
#include "AddGroup.h"
20
#include "Analyze.h"
21
#include "AttachmentExport.h"
22
#include "AttachmentImport.h"
23
#include "AttachmentRemove.h"
24
#include "Clip.h"
25
#include "Close.h"
26
#include "DatabaseCreate.h"
27
#include "DatabaseEdit.h"
28
#include "DatabaseInfo.h"
29
#include "Diceware.h"
30
#include "Edit.h"
31
#include "Estimate.h"
32
#include "Exit.h"
33
#include "Export.h"
34
#include "Generate.h"
35
#include "Help.h"
36
#include "Import.h"
37
#include "List.h"
38
#include "Merge.h"
39
#include "Move.h"
40
#include "Open.h"
41
#include "Remove.h"
42
#include "RemoveGroup.h"
43
#include "Search.h"
44
#include "Show.h"
45
#include "Utils.h"
46

47
#include <QCommandLineParser>
48
#include <QFileInfo>
49
#include <QRegularExpression>
50

51
const QCommandLineOption Command::HelpOption = QCommandLineOption(QStringList()
52
#ifdef Q_OS_WIN
53
                                                                      << QStringLiteral("?")
54
#endif
55
                                                                      << QStringLiteral("h") << QStringLiteral("help"),
56
                                                                  QObject::tr("Display this help."));
57

58
const QCommandLineOption Command::QuietOption =
59
    QCommandLineOption(QStringList() << "q"
60
                                     << "quiet",
61
                       QObject::tr("Silence password prompt and other secondary outputs."));
62

63
const QCommandLineOption Command::KeyFileOption = QCommandLineOption(QStringList() << "k"
64
                                                                                   << "key-file",
65
                                                                     QObject::tr("Key file of the database."),
66
                                                                     QObject::tr("path"));
67

68
const QCommandLineOption Command::NoPasswordOption =
69
    QCommandLineOption(QStringList() << "no-password", QObject::tr("Deactivate password key for the database."));
70

71
const QCommandLineOption Command::YubiKeyOption =
72
    QCommandLineOption(QStringList() << "y"
73
                                     << "yubikey",
74
                       QObject::tr("Yubikey slot and optional serial used to access the database (e.g., 1:7370001)."),
75
                       QObject::tr("slot[:serial]"));
76

77
namespace
78
{
79

80
    QSharedPointer<QCommandLineParser> buildParser(Command* command)
81
    {
82
        auto parser = QSharedPointer<QCommandLineParser>(new QCommandLineParser());
83
        parser->setApplicationDescription(command->description);
84
        for (const CommandLineArgument& positionalArgument : command->positionalArguments) {
85
            parser->addPositionalArgument(
86
                positionalArgument.name, positionalArgument.description, positionalArgument.syntax);
87
        }
88
        for (const CommandLineArgument& optionalArgument : command->optionalArguments) {
89
            parser->addPositionalArgument(optionalArgument.name, optionalArgument.description, optionalArgument.syntax);
90
        }
91
        for (const QCommandLineOption& option : command->options) {
92
            parser->addOption(option);
93
        }
94
        parser->addOption(Command::HelpOption);
95
        return parser;
96
    }
97

98
} // namespace
99

100
Command::Command()
101
    : currentDatabase(nullptr)
102
{
103
    options.append(Command::QuietOption);
104
}
105

106
Command::~Command() = default;
107

108
QString Command::getDescriptionLine()
109
{
110
    QString response = name;
111
    QString space(" ");
112
    QString spaces = space.repeated(20 - name.length());
113
    response = response.append(spaces);
114
    response = response.append(description);
115
    response = response.append("\n");
116
    return response;
117
}
118

119
QString Command::getHelpText()
120
{
121
    auto help = buildParser(this)->helpText();
122
    // Fix spacing of options parameter
123
    help.replace(QStringLiteral("[options]"), name + QStringLiteral(" [options]"));
124
    // Remove application directory from command line example
125
    auto appname = QFileInfo(QCoreApplication::applicationFilePath()).fileName();
126
    auto regex = QRegularExpression(QStringLiteral(" .*%1").arg(QRegularExpression::escape(appname)));
127
    help.replace(regex, appname.prepend(" "));
128

129
    return help;
130
}
131

132
QSharedPointer<QCommandLineParser> Command::getCommandLineParser(const QStringList& arguments)
133
{
134
    auto& err = Utils::STDERR;
135
    QSharedPointer<QCommandLineParser> parser = buildParser(this);
136

137
    if (!parser->parse(arguments)) {
138
        err << parser->errorText() << "\n\n";
139
        err << getHelpText();
140
        return {};
141
    }
142
    if (parser->positionalArguments().size() < positionalArguments.size()) {
143
        err << QObject::tr("Missing positional argument(s).") << "\n\n";
144
        err << getHelpText();
145
        return {};
146
    }
147
    if (parser->positionalArguments().size() > (positionalArguments.size() + optionalArguments.size())) {
148
        err << QObject::tr("Too many arguments provided.") << "\n\n";
149
        err << getHelpText();
150
        return {};
151
    }
152
    if (parser->isSet(HelpOption)) {
153
        err << getHelpText();
154
        return {};
155
    }
156
    return parser;
157
}
158

159
namespace Commands
160
{
161
    QMap<QString, QSharedPointer<Command>> s_commands;
162

163
    void setupCommands(bool interactive)
164
    {
165
        s_commands.clear();
166

167
        s_commands.insert(QStringLiteral("add"), QSharedPointer<Command>(new Add()));
168
        s_commands.insert(QStringLiteral("analyze"), QSharedPointer<Command>(new Analyze()));
169
        s_commands.insert(QStringLiteral("attachment-export"), QSharedPointer<Command>(new AttachmentExport()));
170
        s_commands.insert(QStringLiteral("attachment-import"), QSharedPointer<Command>(new AttachmentImport()));
171
        s_commands.insert(QStringLiteral("attachment-rm"), QSharedPointer<Command>(new AttachmentRemove()));
172
        s_commands.insert(QStringLiteral("clip"), QSharedPointer<Command>(new Clip()));
173
        s_commands.insert(QStringLiteral("close"), QSharedPointer<Command>(new Close()));
174
        s_commands.insert(QStringLiteral("db-create"), QSharedPointer<Command>(new DatabaseCreate()));
175
        s_commands.insert(QStringLiteral("db-edit"), QSharedPointer<Command>(new DatabaseEdit()));
176
        s_commands.insert(QStringLiteral("db-info"), QSharedPointer<Command>(new DatabaseInfo()));
177
        s_commands.insert(QStringLiteral("diceware"), QSharedPointer<Command>(new Diceware()));
178
        s_commands.insert(QStringLiteral("edit"), QSharedPointer<Command>(new Edit()));
179
        s_commands.insert(QStringLiteral("estimate"), QSharedPointer<Command>(new Estimate()));
180
        s_commands.insert(QStringLiteral("generate"), QSharedPointer<Command>(new Generate()));
181
        s_commands.insert(QStringLiteral("help"), QSharedPointer<Command>(new Help()));
182
        s_commands.insert(QStringLiteral("ls"), QSharedPointer<Command>(new List()));
183
        s_commands.insert(QStringLiteral("merge"), QSharedPointer<Command>(new Merge()));
184
        s_commands.insert(QStringLiteral("mkdir"), QSharedPointer<Command>(new AddGroup()));
185
        s_commands.insert(QStringLiteral("mv"), QSharedPointer<Command>(new Move()));
186
        s_commands.insert(QStringLiteral("open"), QSharedPointer<Command>(new Open()));
187
        s_commands.insert(QStringLiteral("rm"), QSharedPointer<Command>(new Remove()));
188
        s_commands.insert(QStringLiteral("rmdir"), QSharedPointer<Command>(new RemoveGroup()));
189
        s_commands.insert(QStringLiteral("search"), QSharedPointer<Command>(new Search()));
190
        s_commands.insert(QStringLiteral("show"), QSharedPointer<Command>(new Show()));
191

192
        if (interactive) {
193
            s_commands.insert(QStringLiteral("exit"), QSharedPointer<Command>(new Exit("exit")));
194
            s_commands.insert(QStringLiteral("quit"), QSharedPointer<Command>(new Exit("quit")));
195
        } else {
196
            s_commands.insert(QStringLiteral("export"), QSharedPointer<Command>(new Export()));
197
            s_commands.insert(QStringLiteral("import"), QSharedPointer<Command>(new Import()));
198
        }
199
    }
200

201
    QList<QSharedPointer<Command>> getCommands()
202
    {
203
        return s_commands.values();
204
    }
205

206
    QSharedPointer<Command> getCommand(const QString& commandName)
207
    {
208
        return s_commands.value(commandName);
209
    }
210
} // namespace Commands
211

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.