File: mu-command-handler.hh

package info (click to toggle)
maildir-utils 1.12.14-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 4,996 kB
  • sloc: cpp: 56,429; lisp: 11,218; sh: 895; ansic: 889; makefile: 126; pascal: 12; python: 4
file content (298 lines) | stat: -rw-r--r-- 8,186 bytes parent folder | download
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
/*
** Copyright (C) 2020-2023 Dirk-Jan C. Binnema <djcb@djcbsoftware.nl>
**
** This program is free software; you can redistribute it and/or modify it
** under the terms of the GNU General Public License as published by the
** Free Software Foundation; either version 3, or (at your option) any
** later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software Foundation,
** Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**
*/
#ifndef MU_COMMAND_HANDLER_HH__
#define MU_COMMAND_HANDLER_HH__

#include <vector>
#include <string>
#include <ostream>
#include <stdexcept>
#include <unordered_map>
#include <functional>
#include <algorithm>

#include "utils/mu-error.hh"
#include "utils/mu-sexp.hh"
#include "utils/mu-option.hh"

namespace Mu {

///
/// Commands are s-expressions with the follow properties:

/// 1) a command is a list with a command-name as its first argument
/// 2) the rest of the parameters are pairs of colon-prefixed symbol and a value of some
///    type (ie. 'keyword arguments')
/// 3) each command is described by its CommandInfo structure, which defines the type
/// 4) calls to the command must include all required parameters
/// 5) all parameters must be of the specified type; however the symbol 'nil' is allowed
///    for specify a non-required parameter to be absent; this is for convenience on the
///    call side.

struct Command: public Sexp {

	static Result<Command> make(Sexp&& sexp) try {
		return Ok(Command{std::move(sexp)});
	} catch (const Error& e) {
		return Err(e);
	}

	static Result<Command> make_parse(const std::string& cmdstr) try {
		if (auto&& sexp{Sexp::parse(cmdstr)}; !sexp)
			return Err(sexp.error());
		else
			return Ok(Command(std::move(*sexp)));
	} catch (const Error& e) {
		return Err(e);
	}

	/**
	 * Get name of the command (first element) in a command exp
	 *
	 * @return name
	 */
	const std::string& name() const {
		return cbegin()->symbol().name;
	}

	/**
	 * Find the argument with the given name.
	 *
	 * @param arg name
	 *
	 * @return iterator point at the argument, or cend
	 */
	const_iterator find_arg(const std::string& arg) const {
		return find_prop(arg, cbegin() + 1, cend());
	}

	/**
	 * Get a string argument
	 *
	 * @param name of the argument
	 *
	 * @return ref to string, or Nothing if not found
	 */
	Option<const std::string&> string_arg(const std::string& name) const {
		if (auto&& val{arg_val(name, Sexp::Type::String)}; !val)
			return Nothing;
		else
			return val->string();
	}

	/**
	 * Get a string-vec argument
	 *
	 * @param name of the argument
	 *
	 * @return ref to string-vec, or Nothing if not found or some error.
	 */
	Option<std::vector<std::string>> string_vec_arg(const std::string& name) const;

	/**
	 * Get a symbol argument
	 *
	 * @param name of the argument
	 *
	 * @return ref to symbol name, or Nothing if not found
	 */
	Option<const std::string&> symbol_arg(const std::string& name) const {
		if (auto&& val{arg_val(name, Sexp::Type::Symbol)}; !val)
			return Nothing;
		else
			return val->symbol().name;
	}

	/**
	 * Get a number argument
	 *
	 * @param name of the argument
	 *
	 * @return number or Nothing if not found
	 */
	Option<int> number_arg(const std::string& name) const {
		if (auto&& val{arg_val(name, Sexp::Type::Number)}; !val)
			return Nothing;
		else
			return static_cast<int>(val->number());
	}

	/*
	 * helpers
	 */

	/**
	 * Get a boolean argument
	 *
	 * @param name of the argument
	 *
	 * @return true if there's a non-nil symbol value for the given
	 * name; false otherwise.
	 */
	Option<bool> bool_arg(const std::string& name) const {
		if (auto&& symb{symbol_arg(name)}; !symb)
			return Nothing;
		else
			return symb.value() == "nil" ? false : true;
	}

	/**
	 * Treat any argument as a boolean
	 *
	 * @param name name of the argument
	 *
	 * @return false if the argument is absent or the symbol false;
	 * otherwise true.
	 */
	bool boolean_arg(const std::string& name) const {
		auto&& it{find_arg(name)};
		return (it == cend() || std::next(it)->nilp()) ? false : true;
	}

private:
	explicit Command(Sexp&& s){
		*this = std::move(static_cast<Command&&>(s));
		if (!listp() || empty() || !cbegin()->symbolp() ||
		    !plistp(cbegin() + 1, cend()))
			throw Error(Error::Code::Command,
				    "expected command, got '{}'", to_string());
	}


	Option<const Sexp&> arg_val(const std::string& name, Sexp::Type type) const {
		if (auto&& it{find_arg(name)}; it == cend()) {
			//std::cerr << "--> %s name found " << name << '\n';
			return Nothing;
		} else if (auto&& val{it + 1}; val->type() != type) {
			//std::cerr << "--> type " << Sexp::type_name(it->type()) << '\n';
			return Nothing;
		} else
			return *val;
	}
};

struct CommandHandler {

	/// Information about a function argument
	struct ArgInfo {
		ArgInfo(Sexp::Type typearg, bool requiredarg, std::string&& docarg)
			: type{typearg}, required{requiredarg}, docstring{std::move(docarg)} {}
		const Sexp::Type  type;      /**< Sexp::Type of the argument */
		const bool        required;  /**< Is this argument required? */
		const std::string docstring; /**< Documentation */
	};

	/// The arguments for a function, which maps their names to the information.
	using ArgMap = std::unordered_map<std::string, ArgInfo>;

	// A handler function
	using Handler = std::function<void(const Command&)>;

	/// Information about some command
	struct CommandInfo {
		CommandInfo(ArgMap&& argmaparg, std::string&& docarg, Handler&& handlerarg)
			: args{std::move(argmaparg)}, docstring{std::move(docarg)},
			  handler{std::move(handlerarg)} {}
		const ArgMap      args;
		const std::string docstring;
		const Handler     handler;

		/**
		 * Get a sorted list of argument names, for display. Required args come
		 * first, then alphabetical.
		 *
		 * @return vec with the sorted names.
		 */ /* LCOV_EXCL_START */
		std::vector<std::string> sorted_argnames() const {
			// sort args -- by required, then alphabetical.
			std::vector<std::string> names;
			for (auto&& arg : args)
				names.emplace_back(arg.first);
			std::sort(names.begin(), names.end(), [&](const auto& name1, const auto& name2) {
				const auto& arg1{args.find(name1)->second};
				const auto& arg2{args.find(name2)->second};
				if (arg1.required != arg2.required)
					return arg1.required;
				else
					return name1 < name2;
			});
			return names;
		}
		/* LCOV_EXCL_STOP */

	};

	/// All commands, mapping their name to information about them.
	using CommandInfoMap = std::unordered_map<std::string, CommandInfo>;

	CommandHandler(const CommandInfoMap& cmap): cmap_{cmap} {}
	CommandHandler(CommandInfoMap&& cmap):      cmap_{std::move(cmap)} {}

	const CommandInfoMap& info_map() const { return cmap_; }

	/**
	 * Invoke some command
	 *
	 * A command uses keyword arguments, e.g. something like: (foo :bar 1
	 *    :cuux "fnorb")
	 *
	 * @param cmd a Sexp describing a command call
	 * @param validate whether to validate before invoking. Useful during
	 * development.
	 *
	 * Return Ok() or some Error
	 */
	Result<void> invoke(const Command& cmd, bool validate=true) const;

private:
	const CommandInfoMap cmap_;
};

/* LCOV_EXCL_START */
static inline std::ostream&
operator<<(std::ostream& os, const CommandHandler::ArgInfo& info)
{
	os << info.type << " (" << (info.required ? "required" : "optional") << ")";

	return os;
}
/* LCOV_EXCL_STOP */

static inline std::ostream&
operator<<(std::ostream& os, const CommandHandler::CommandInfo& info)
{
	for (auto&& arg : info.args)
		os << "  " << arg.first << " " << arg.second << '\n'
		   << "    " << arg.second.docstring << "\n";

	return os;
}

static inline std::ostream&
operator<<(std::ostream& os, const CommandHandler::CommandInfoMap& map)
{
	for (auto&& c : map)
		os << c.first << '\n' << c.second;

	return os;
}

} // namespace Mu

#endif /* MU_COMMAND_HANDLER_HH__ */