-
Notifications
You must be signed in to change notification settings - Fork 63
/
Tool.hh
334 lines (274 loc) · 9.91 KB
/
Tool.hh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
//
// Tool.hh
//
// Copyright (c) 2017 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma once
#include "fleece/Fleece.hh"
#include "StringUtil.hh"
#include "ArgumentTokenizer.hh"
#include <functional>
#include <iostream>
#include <string>
#include <deque>
#include <algorithm>
#include <climits>
#ifdef CMAKE
#include "config.h"
#else
#define TOOLS_VERSION_STRING "0.0.0"
#endif
class Tool {
public:
Tool(const char* name);
virtual ~Tool();
static Tool* instance;
/** Entry point for a Tool. */
virtual int main(int argc, const char * argv[]) {
try {
if (getenv("CLICOLOR"))
enableColor();
_toolPath = std::string(argv[0]);
std::vector<std::string> args;
for(int i = 1; i < argc; ++i)
args.push_back(argv[i]);
_argTokenizer.reset(args);
return run();
} catch (const exit_error &x) {
return x.status;
} catch (const fail_error &) {
return 1;
} catch (const std::exception &x) {
errorOccurred(litecore::format("Uncaught C++ exception: %s", x.what()));
return 1;
} catch (...) {
errorOccurred("Uncaught unknown C++ exception");
return 1;
}
}
Tool(const Tool &parent)
:_verbose(parent._verbose)
,_toolPath(parent._toolPath)
,_argTokenizer(parent._argTokenizer)
,_name(parent._name)
{ }
Tool(const Tool &parent, const char *commandLine)
:_verbose(parent._verbose)
,_toolPath(parent._toolPath)
,_name(parent._name)
{
_argTokenizer.reset(commandLine);
}
const std::string& name() const {return _name;}
void setName(const std::string &name) {_name = name;}
virtual void usage() = 0;
int verbose() const {return _verbose;}
void setVerbose(int level) {_verbose = level;}
#pragma mark - ERRORS / FAILURE:
// A placeholder exception thrown by fail() and caught in run() or a CLI loop
class fail_error : public std::runtime_error {
public:
fail_error() :runtime_error("fail called") { }
};
// A placeholder exception to exit the tool or subcommand
class exit_error : public std::runtime_error {
public:
exit_error(int s) :runtime_error("(exiting)"), status(s) { }
int const status;
};
static void exit(int status) {
throw exit_error(status);
}
void errorOccurred(const std::string &what){
std::cerr << "Error";
if (!islower(what[0]))
std::cerr << ":";
std::cerr << " " << what << "\n";
++_errorCount;
if (_failOnError)
fail();
}
[[noreturn]] static void fail() {
throw fail_error();
}
[[noreturn]] void fail(const std::string &message) {
errorOccurred(message);
fail();
}
[[noreturn]] virtual void failMisuse(const std::string &message) {
std::cerr << "Error: " << message << "\n";
usage();
fail();
}
#pragma mark - I/O:
/** Interactively reads a command from the terminal, preceded by the prompt.
If it returns true, the command has been parsed into the argument buffer just like the
initial command line.
If it returns false, the user has decided to end the session (probably by hitting ^D.) */
bool readLine(const char *prompt);
/** Reads a password from the terminal without echoing it. */
std::string readPassword(const char *prompt);
/** Reads the contents of a file into memory. */
fleece::alloc_slice readFile(const std::string &path);
/** Called during readLine when the user hits the Tab key.*/
virtual void addLineCompletions(ArgumentTokenizer&, std::function<void(const std::string&)>) { }
enum TerminalType {
kTTY,
kColorTTY,
kIDE,
kColorIDE,
kFile,
kOther,
};
TerminalType terminalType();
int terminalWidth();
std::string ansi(const char *command);
std::string ansiBold() {return ansi("1");}
std::string ansiDim() {return ansi("2");}
std::string ansiItalic() {return ansi("3");}
std::string ansiUnderline() {return ansi("4");}
std::string ansiRed() {return ansi("31");}
std::string ansiReset() {return ansi("0");}
std::string bold(const char *str) {return ansiBold() + str + ansiReset();}
std::string it(const char *str) {return ansiItalic() + str + ansiReset();}
std::string spaces(int n) {return std::string(std::max(n, 1), ' ');}
int parseInt(std::string_view, int minVal = INT_MIN, int maxVal = INT_MAX);
protected:
/** Top-level action, called after flags are processed.
Return value will be returned as the exit status of the process. */
virtual int run() =0;
#pragma mark - ARGUMENT HANDLING:
typedef litecore::function_ref<void()> FlagHandler;
struct FlagSpec {const char *flag; FlagHandler handler;};
bool hasArgs() const {
return _argTokenizer.hasArgument();
}
/** Returns the next argument without consuming it, or "" if there are no remaining args. */
std::string peekNextArg() {
return _argTokenizer.argument();
}
/** Returns & consumes the next arg, or fails if there are none. */
std::string nextArg(const char *what) {
if (!_argTokenizer.hasArgument())
failMisuse(litecore::format("Missing argument: expected %s", what));
std::string arg = _argTokenizer.argument();
_argTokenizer.next();
return arg;
}
int nextIntArg(const char *what, int minVal = INT_MIN, int maxVal = INT_MAX);
/** If the next arg matches the given string, consumes it and returns true. */
bool matchArg(const char *matchArg) {
if (_argTokenizer.argument() != matchArg)
return false;
_argTokenizer.next();
return true;
}
std::string restOfInput(const char *what) {
if (!_argTokenizer.hasArgument())
failMisuse(litecore::format("Missing argument: expected %s", what));
return _argTokenizer.restOfInput();
}
/** Call when there are no more arguments to read. Will fail if there are any args left. */
void endOfArgs() {
if (_argTokenizer.hasArgument())
fail(litecore::format("Unexpected extra arguments, starting with '%s'",
_argTokenizer.argument().c_str()));
}
/** Returns the final argument.
Side effect: rewinds args back to the beginning. */
std::string lastArg() {
std::string arg;
while (hasArgs())
arg = nextArg("");
rewindArgs();
return arg;
}
/** Un-reads all arguments, returning back to the beginning. */
void rewindArgs() {
_argTokenizer.rewind();
}
/** Consumes arguments as long as they begin with "-".
Each argument is looked up in the list of FlagSpecs and the matching one's handler is
called. If there is no match, fails. */
virtual void processFlags(std::initializer_list<FlagSpec> specs) {
while(true) {
std::string flag = peekNextArg();
if (flag.empty() || !litecore::hasPrefix(flag, "-") || flag.size() > 20)
return;
_argTokenizer.next();
if (flag == "--")
return; // marks end of flags
bool handled;
try {
handled = processFlag(flag, specs);
} catch (std::exception const& x) {
fail("in flag " + flag + ": " + x.what());
}
if (!handled) {
// Flags all subcommands accept:
if (flag == "--help") {
usage();
exit(0);
} else if (flag == "--verbose" || flag == "-v") {
++_verbose;
} else if (flag == "--color") {
enableColor();
} else if (flag == "--version") {
std::cout << _name << " " << TOOLS_VERSION_STRING << std::endl << std::endl;
exit(0);
} else {
fail(std::string("Unknown flag ") + flag);
}
}
}
}
/** Subroutine of processFlags; looks up one flag and calls its handler, or returns false. */
virtual bool processFlag(const std::string &flag,
const std::initializer_list<FlagSpec> &specs)
{
for (auto &spec : specs) {
if (flag == std::string(spec.flag)) {
spec.handler();
return true;
}
}
return false;
}
void verboseFlag() {
++_verbose;
}
bool _failOnError {false};
unsigned _errorCount {0};
static void fixUpPath(std::string &path) {
#ifndef _MSC_VER
if (litecore::hasPrefix(path, "~/")) {
path.erase(path.begin(), path.begin()+1);
path.insert(0, getenv("HOME"));
}
#endif
}
static std::string fixedUpPath(std::string path) {
fixUpPath(path);
return path;
}
protected:
int _verbose {0};
private:
void enableColor();
static void initReadLine();
std::string _toolPath;
std::string _name;
ArgumentTokenizer _argTokenizer;
};