summaryrefslogtreecommitdiffstats
path: root/lib/cli/clicommand.cpp
blob: cfdce094665fb3240e555d888b89277f8d372a7c (plain)
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#include "cli/clicommand.hpp"
#include "base/logger.hpp"
#include "base/console.hpp"
#include "base/type.hpp"
#include "base/serializer.hpp"
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/program_options.hpp>
#include <algorithm>
#include <iostream>

using namespace icinga;
namespace po = boost::program_options;

std::vector<String> icinga::GetBashCompletionSuggestions(const String& type, const String& word)
{
	std::vector<String> result;

#ifndef _WIN32
	String bashArg = "compgen -A " + Utility::EscapeShellArg(type) + " " + Utility::EscapeShellArg(word);
	String cmd = "bash -c " + Utility::EscapeShellArg(bashArg);

	FILE *fp = popen(cmd.CStr(), "r");

	char line[4096];
	while (fgets(line, sizeof(line), fp)) {
		String wline = line;
		boost::algorithm::trim_right_if(wline, boost::is_any_of("\r\n"));
		result.push_back(wline);
	}

	pclose(fp);

	/* Append a slash if there's only one suggestion and it's a directory */
	if ((type == "file" || type == "directory") && result.size() == 1) {
		String path = result[0];

		struct stat statbuf;
		if (lstat(path.CStr(), &statbuf) >= 0) {
			if (S_ISDIR(statbuf.st_mode)) {
				result.clear(),
				result.push_back(path + "/");
			}
		}
	}
#endif /* _WIN32 */

	return result;
}

std::vector<String> icinga::GetFieldCompletionSuggestions(const Type::Ptr& type, const String& word)
{
	std::vector<String> result;

	for (int i = 0; i < type->GetFieldCount(); i++) {
		Field field = type->GetFieldInfo(i);

		if (field.Attributes & FANoUserView)
			continue;

		if (strcmp(field.TypeName, "int") != 0 && strcmp(field.TypeName, "double") != 0
			&& strcmp(field.TypeName, "bool") != 0 && strcmp(field.TypeName, "String") != 0)
			continue;

		String fname = field.Name;

		String suggestion = fname + "=";

		if (suggestion.Find(word) == 0)
			result.push_back(suggestion);
	}

	return result;
}

int CLICommand::GetMinArguments() const
{
	return 0;
}

int CLICommand::GetMaxArguments() const
{
	return GetMinArguments();
}

bool CLICommand::IsHidden() const
{
	return false;
}

bool CLICommand::IsDeprecated() const
{
	return false;
}

std::mutex& CLICommand::GetRegistryMutex()
{
	static std::mutex mtx;
	return mtx;
}

std::map<std::vector<String>, CLICommand::Ptr>& CLICommand::GetRegistry()
{
	static std::map<std::vector<String>, CLICommand::Ptr> registry;
	return registry;
}

CLICommand::Ptr CLICommand::GetByName(const std::vector<String>& name)
{
	std::unique_lock<std::mutex> lock(GetRegistryMutex());

	auto it = GetRegistry().find(name);

	if (it == GetRegistry().end())
		return nullptr;

	return it->second;
}

void CLICommand::Register(const std::vector<String>& name, const CLICommand::Ptr& function)
{
	std::unique_lock<std::mutex> lock(GetRegistryMutex());
	GetRegistry()[name] = function;
}

void CLICommand::Unregister(const std::vector<String>& name)
{
	std::unique_lock<std::mutex> lock(GetRegistryMutex());
	GetRegistry().erase(name);
}

std::vector<String> CLICommand::GetArgumentSuggestions(const String& argument, const String& word) const
{
	return std::vector<String>();
}

std::vector<String> CLICommand::GetPositionalSuggestions(const String& word) const
{
	return std::vector<String>();
}

void CLICommand::InitParameters(boost::program_options::options_description& visibleDesc,
	boost::program_options::options_description& hiddenDesc) const
{ }

ImpersonationLevel CLICommand::GetImpersonationLevel() const
{
	return ImpersonateIcinga;
}

bool CLICommand::ParseCommand(int argc, char **argv, po::options_description& visibleDesc,
	po::options_description& hiddenDesc,
	po::positional_options_description& positionalDesc,
	po::variables_map& vm, String& cmdname, CLICommand::Ptr& command, bool autocomplete)
{
	std::unique_lock<std::mutex> lock(GetRegistryMutex());

	typedef std::map<std::vector<String>, CLICommand::Ptr>::value_type CLIKeyValue;

	std::vector<String> best_match;
	int arg_end = 0;
	bool tried_command = false;

	for (const CLIKeyValue& kv : GetRegistry()) {
		const std::vector<String>& vname = kv.first;

		std::vector<String>::size_type i;
		int k;
		for (i = 0, k = 1; i < vname.size() && k < argc; i++, k++) {
			if (strncmp(argv[k], "-", 1) == 0 || strncmp(argv[k], "--", 2) == 0) {
				i--;
				continue;
			}

			tried_command = true;

			if (vname[i] != argv[k])
				break;

			if (i >= best_match.size())
				best_match.push_back(vname[i]);

			if (i == vname.size() - 1) {
				cmdname = boost::algorithm::join(vname, " ");
				command = kv.second;
				arg_end = k;
				goto found_command;
			}
		}
	}

found_command:
	lock.unlock();

	if (command) {
		po::options_description vdesc("Command options");
		command->InitParameters(vdesc, hiddenDesc);
		visibleDesc.add(vdesc);
	}

	if (autocomplete || (tried_command && !command))
		return true;

	po::options_description adesc;
	adesc.add(visibleDesc);
	adesc.add(hiddenDesc);

	if (command && command->IsDeprecated()) {
		std::cerr << ConsoleColorTag(Console_ForegroundRed | Console_Bold)
			<< "Warning: CLI command '" << cmdname << "' is DEPRECATED! Please read the Changelog."
			<< ConsoleColorTag(Console_Normal) << std::endl << std::endl;
	}

	po::store(po::command_line_parser(argc - arg_end, argv + arg_end).options(adesc).positional(positionalDesc).run(), vm);
	po::notify(vm);

	return true;
}

void CLICommand::ShowCommands(int argc, char **argv, po::options_description *visibleDesc,
	po::options_description *hiddenDesc,
	ArgumentCompletionCallback globalArgCompletionCallback,
	bool autocomplete, int autoindex)
{
	std::unique_lock<std::mutex> lock(GetRegistryMutex());

	typedef std::map<std::vector<String>, CLICommand::Ptr>::value_type CLIKeyValue;

	std::vector<String> best_match;
	int arg_begin = 0;
	CLICommand::Ptr command;

	for (const CLIKeyValue& kv : GetRegistry()) {
		const std::vector<String>& vname = kv.first;

		arg_begin = 0;

		std::vector<String>::size_type i;
		int k;
		for (i = 0, k = 1; i < vname.size() && k < argc; i++, k++) {
			if (strcmp(argv[k], "--no-stack-rlimit") == 0 || strcmp(argv[k], "--autocomplete") == 0 || strcmp(argv[k], "--scm") == 0) {
				i--;
				arg_begin++;
				continue;
			}

			if (autocomplete && static_cast<int>(i) >= autoindex - 1)
				break;

			if (vname[i] != argv[k])
				break;

			if (i >= best_match.size()) {
				best_match.push_back(vname[i]);
			}

			if (i == vname.size() - 1) {
				command = kv.second;
				break;
			}
		}
	}

	String aword;

	if (autocomplete) {
		if (autoindex < argc)
			aword = argv[autoindex];

		if (autoindex - 1 > static_cast<int>(best_match.size()) && !command)
			return;
	} else
		std::cout << "Supported commands: " << std::endl;

	for (const CLIKeyValue& kv : GetRegistry()) {
		const std::vector<String>& vname = kv.first;

		if (vname.size() < best_match.size() || kv.second->IsHidden())
			continue;

		bool match = true;

		for (std::vector<String>::size_type i = 0; i < best_match.size(); i++) {
			if (vname[i] != best_match[i]) {
				match = false;
				break;
			}
		}

		if (!match)
			continue;

		if (autocomplete) {
			String cname;

			if (autoindex - 1 < static_cast<int>(vname.size())) {
				cname = vname[autoindex - 1];

				if (cname.Find(aword) == 0)
					std::cout << cname << "\n";
			}
		} else {
			std::cout << "  * " << boost::algorithm::join(vname, " ")
				<< " (" << kv.second->GetShortDescription() << ")"
				<< (kv.second->IsDeprecated() ? " (DEPRECATED)" : "") << std::endl;
		}
	}

	if (!autocomplete)
		std::cout << std::endl;

	if (command && autocomplete) {
		String aname, prefix, pword;
		const po::option_description *odesc;

		if (autoindex - 2 >= 0 && strcmp(argv[autoindex - 1], "=") == 0 && strstr(argv[autoindex - 2], "--") == argv[autoindex - 2]) {
			aname = argv[autoindex - 2] + 2;
			pword = aword;
		} else if (autoindex - 1 >= 0 && argv[autoindex - 1][0] == '-' && argv[autoindex - 1][1] == '-') {
			aname = argv[autoindex - 1] + 2;
			pword = aword;

			if (pword == "=")
				pword = "";
		} else if (autoindex - 1 >= 0 && argv[autoindex - 1][0] == '-' && argv[autoindex - 1][1] != '-') {
			aname = argv[autoindex - 1];
			pword = aword;

			if (pword == "=")
				pword = "";
		} else if (aword.GetLength() > 1 && aword[0] == '-' && aword[1] != '-') {
			aname = aword.SubStr(0, 2);
			prefix = aname;
			pword = aword.SubStr(2);
		} else {
			goto complete_option;
		}

		odesc = visibleDesc->find_nothrow(aname, false);

		if (!odesc)
			return;

		if (odesc->semantic()->min_tokens() == 0)
			goto complete_option;

		for (const String& suggestion : globalArgCompletionCallback(odesc->long_name(), pword)) {
			std::cout << prefix << suggestion << "\n";
		}

		for (const String& suggestion : command->GetArgumentSuggestions(odesc->long_name(), pword)) {
			std::cout << prefix << suggestion << "\n";
		}

		return;

complete_option:
		for (const boost::shared_ptr<po::option_description>& odesc : visibleDesc->options()) {
			String cname = "--" + odesc->long_name();

			if (cname.Find(aword) == 0)
				std::cout << cname << "\n";
		}

		for (const String& suggestion : command->GetPositionalSuggestions(aword)) {
			std::cout << suggestion << "\n";
		}
	}

	return;
}