-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathargs.cc
542 lines (502 loc) · 19.4 KB
/
args.cc
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
#include <algorithm>
#include <cassert>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <memory>
#include <ostream>
#include <string_view>
#include <system_error>
#include <absl/strings/numbers.h>
#include <absl/strings/str_format.h>
#include <absl/strings/str_join.h>
#include <absl/strings/str_split.h>
#include <yaml-cpp/yaml.h>
#include "args.h"
#include "rule.h"
namespace ashuffle {
namespace {
namespace fs = ::std::filesystem;
constexpr char kHelpMessage[] =
"usage: ashuffle [-h] [-n] [-v] [[-e PATTERN ...] ...] [-o NUMBER]\n"
" [-f FILENAME] [-q NUMBER] [-g TAG ...] [[-t TWEAK] ...]\n"
"\n"
"Optional Arguments:\n"
" -h,-?,--help Display this help message.\n"
" --by-album Same as '--group-by album date'.\n"
" -e,--exclude Specify things to remove from shuffle (think\n"
" blacklist). A PATTERN should follow the exclude\n"
" flag.\n"
" --exclude-from Read exclude rules from the given file. Rules\n"
" should be given in the YAML format described in\n"
" the included readme.md\n"
" -f,--file Use MPD URI's found in 'file' instead of using the\n"
" entire MPD library. You can supply `-` instead of a\n"
" filename to retrive URI's from standard in. This\n"
" can be used to pipe song URI's from another program\n"
" into ashuffle.\n"
" -g,--group-by Shuffle songs grouped by the given tags. For\n"
" example 'album' could be used as the tag, and an\n"
" entire album's worth of songs would be queued\n"
" instead of one song at a time.\n"
" --host Specify a hostname or IP address to connect to.\n"
" Defaults to `localhost`.\n"
" --log-file Path to write log output to. Defaults to stderr.\n"
" -n,--no-check When reading URIs from a file, don't check to\n"
" ensure that the URIs match the given exclude rules.\n"
" This option is most helpful when shuffling songs\n"
" with -f, that aren't in the MPD library.\n"
" -o,--only Instead of continuously adding songs, just add\n"
" 'NUMBER' songs and then exit.\n"
" -p,--port Specify a port number to connect to. Defaults to\n"
" `6600`.\n"
" -q,--queue-buffer Specify to keep a buffer of `n` songs queued after\n"
" the currently playing song. This is to support MPD\n"
" features like crossfade that don't work if there\n"
" are no more songs in the queue.\n"
" -t,--tweak Tweak an infrequently used ashuffle option. See\n"
" `readme.md` for a list of available options.\n"
" -v,--version Print the version of ashuffle, and then exit.\n"
"See included `readme.md` file for PATTERN syntax.\n";
// Parse the given string as a boolean. Produces an empty option if no value
// can be parsed.
std::optional<bool> ParseBool(std::string val) {
std::transform(val.begin(), val.end(), val.begin(),
[](unsigned char c) { return std::tolower(c); });
if (val == "yes" || val == "true" || val == "on" || val == "1") {
return true;
}
if (val == "no" || val == "false" || val == "off" || val == "0") {
return false;
}
return std::nullopt;
}
class Parser {
public:
enum Status {
kInProgress,
kDone,
};
// Consume consumes the given argument and updates the state of the parser.
// Consume returns the status of the parser, either "In Progress" or
// Final. Once a final status is reached, future calls to Consume will
// ignore the given argument. Note: Finish can be called before the final
// state is reached, so waiting for the parser to reach a final state
// is not a reasonable approach. Just feed in arguments, and then call
// Finish once all arguments have been consumed.
Status Consume(std::string_view);
// Finish completes the parse and returns the parsed Options struct, or
// a parser error.
std::variant<Options, ParseError> Finish();
// Constructs an empty parser. The given tagger is used to resolve
// exclusion rule field names.
Parser(const mpd::TagParser& tag_parser)
: state_(kNone), tag_parser_(tag_parser){};
private:
enum State {
kError, // (final) Error state
kExcludeFile, // Expecting file path to exclude file.
kFile, // Expecting file path
kFinal, // (final) Final state
kGroup, // (generic) Expecting tag for group.
kGroupBegin, // Expecting first tag for group.
kHost, // Expecting hostname
kLogFile, // Expecting file path to log file.
kNone, // (generic) Default state, and initial state.
kPort, // Expecting port
kQueue, // Expecting --only value
kQueueBuffer, // Expecting queue buffer size
kRule, // (generic) Expecting rule tag
kRuleBegin, // Expecting first rule tag (not generic)
kRuleValue, // Expecting rule matcher for previous tag
kTest, // Expecting test-only flag name
kTweak, // Expecting a tweak
};
State state_;
// opts_ is modified as tokens are `Consume`d.
Options opts_;
// err_ is set if a parse error occurs.
ParseError err_;
// prev_ is the previous token that was passed to consume. Initially the
// empty token.
std::string prev_;
const mpd::TagParser& tag_parser_;
Rule pending_rule_;
enum mpd_tag_type rule_tag_;
// Returns true if we are in a "Generic" state, where we can transfer
// to any other option.
bool InGenericState();
// Returns true if the parser is in a "Final" state, where no future tokens
// will be accepted.
bool InFinalState();
// Store the currently pending rule in `opts_`, and clear the pending rule.
void FlushRule();
// Actual consume logic is here. It maps an argument to a state update or
// parse error as appropriate.
std::variant<State, ParseError> ConsumeInternal(std::string_view arg);
// Parse a tweak argument specifically (anything when we're in kTweak
// state). Return value has the same semantics as ConsumeInternal.
std::variant<State, ParseError> ParseTweak(std::string_view arg);
// Load the exclude rules from the file at the given path. Returns
// nothing on success, and an ParseError on failure.
std::optional<ParseError> LoadExcludeFile(fs::path path);
};
bool Parser::InGenericState() {
return state_ == kNone || state_ == kRule || state_ == kGroup;
}
bool Parser::InFinalState() { return state_ == kFinal || state_ == kError; }
void Parser::FlushRule() {
assert(!pending_rule_.Empty() &&
"should not be possible to construct empty rule");
opts_.ruleset.emplace_back(std::move(pending_rule_));
pending_rule_ = Rule();
}
Parser::Status Parser::Consume(std::string_view arg) {
if (InFinalState()) {
// Fail if we receive any more tokens after we reach a final
// state.
return kDone;
}
std::variant<Parser::State, ParseError> next_or_err = ConsumeInternal(arg);
if (ParseError* err = std::get_if<ParseError>(&next_or_err);
err != nullptr) {
err_ = *err;
state_ = kError;
return kDone;
}
prev_ = arg;
Parser::State next = std::get<Parser::State>(next_or_err);
// If we're transitioning out of a rule...
if (state_ == kRule && (next != kRule && next != kRuleValue)) {
FlushRule();
}
state_ = next;
return InFinalState() ? kDone : kInProgress;
}
std::variant<Options, ParseError> Parser::Finish() {
if (state_ == kRule) {
// If we're in the middle of parsing a rule, then flush the current
// rule before finishing.
FlushRule();
}
if (!InFinalState()) {
// Finalize the parser if parsing is still in-progress. In a generic
// state (ready to start a new arg), everything is peachy. However, if
// we are expecting some specific value (non-generic), then we should
// fail.
if (InGenericState()) {
state_ = kFinal;
} else if (state_ == kRuleValue) {
err_ = ParseError(
absl::StrFormat("no value supplied for match '%s'", prev_));
state_ = kError;
} else {
err_ = ParseError(
absl::StrFormat("no argument supplied for '%s'", prev_));
state_ = kError;
}
}
if (state_ == kError) {
return err_;
}
return std::exchange(opts_, Options());
}
std::variant<Parser::State, ParseError> Parser::ParseTweak(
std::string_view arg) {
std::vector<std::string> assignment = absl::StrSplit(arg, "=");
// Match on things like 'window-size=' as well.
if (assignment.size() < 2 || assignment[1].empty()) {
return ParseError("tweak must be of the form <name>=<value>");
}
auto& key = assignment[0];
std::vector<std::string> value_parts(assignment.begin() + 1,
assignment.end());
auto value = absl::StrJoin(value_parts, "=");
if (key == "window-size") {
if (!absl::SimpleAtoi(value, &opts_.tweak.window_size)) {
return ParseError(absl::StrFormat(
"couldn't convert window-size value '%s'", value));
}
if (opts_.tweak.window_size < 1) {
return ParseError(absl::StrFormat(
"tweak window-size must be >= 1 (%s given)", value));
}
return kNone;
}
if (key == "play-on-startup") {
auto v = ParseBool(value);
if (!v.has_value()) {
return ParseError(absl::StrFormat(
"play-on-startup must be a boolean value ('%s' given)", value));
}
opts_.tweak.play_on_startup = *v;
return kNone;
}
if (key == "suspend-timeout") {
if (!absl::ParseDuration(value, &opts_.tweak.suspend_timeout)) {
return ParseError(
absl::StrFormat("suspend-timeout must be a duration with units "
"e.g., 250ms ('%s' given)",
value));
}
if (opts_.tweak.suspend_timeout < absl::ZeroDuration()) {
return ParseError(absl::StrFormat(
"suspend-timeout must be a positive duration ('%s' given)",
value));
}
return kNone;
}
if (key == "reconnect-timeout") {
if (!absl::ParseDuration(value, &opts_.tweak.reconnect_timeout)) {
return ParseError(absl::StrFormat(
"reconnect-timeout must be a duration with units "
"e.g., 30s ('%s' given)",
value));
}
if (opts_.tweak.reconnect_timeout < absl::ZeroDuration()) {
return ParseError(absl::StrFormat(
"reconnect-timeout must be a positive duration ('%s' given)",
value));
}
return kNone;
}
if (key == "exit-on-db-update") {
auto v = ParseBool(value);
if (!v.has_value()) {
return ParseError(absl::StrFormat(
"exit-on-db-update must be a boolean value ('%s' given)",
value));
}
opts_.tweak.exit_on_db_update = *v;
return kNone;
}
return ParseError(absl::StrFormat("unrecognized tweak '%s'", arg));
}
std::optional<ParseError> Parser::LoadExcludeFile(fs::path path) {
std::error_code error;
fs::file_status status = fs::status(path, error);
if (error) {
std::stringstream message;
message << "Failed to check status of: " << path << ": " << error
<< std::endl;
return ParseError(message.str());
}
if (!fs::exists(status)) {
return ParseError(absl::StrFormat("Path %s does not exist", path));
}
YAML::Node doc;
try {
doc = YAML::LoadFile(path);
} catch (const YAML::Exception& e) {
return ParseError(absl::StrFormat("Cannot load YAML: %s", e.what()));
}
try {
const YAML::Node rules = doc["rules"];
if (!rules.IsSequence()) {
throw YAML::Exception(rules.Mark(),
"rules key does not contain rule list");
}
for (const YAML::Node& rule : rules) {
if (!rule.IsMap()) {
throw YAML::Exception(rule.Mark(),
"rule is not a tag to value mapping");
}
ashuffle::Rule out;
for (const auto& kv : rule) {
auto raw_tag = kv.first.as<std::string>();
auto raw_value = kv.second.as<std::string>();
std::optional<enum mpd_tag_type> tag =
tag_parser_.Parse(raw_tag);
if (!tag.has_value()) {
throw YAML::Exception(
kv.first.Mark(),
absl::StrFormat("invalid song tag name '%s'", raw_tag));
}
out.AddPattern(*tag, std::move(raw_value));
}
opts_.ruleset.emplace_back(std::move(out));
}
} catch (const YAML::Exception& e) {
return ParseError(
absl::StrFormat("Cannot load rules from %s: %s", path, e.what()));
}
return std::nullopt;
}
std::variant<Parser::State, ParseError> Parser::ConsumeInternal(
std::string_view arg) {
if (arg == "--help" || arg == "-h" || arg == "-?") {
return ParseError(ParseError::Type::kHelp,
"the user requested help to be displayed");
}
if (InGenericState()) {
if (arg == "--version" || arg == "-v") {
return ParseError(ParseError::Type::kVersion,
"the user requested the version to be displayed");
}
if (arg == "--exclude" || arg == "-e") {
return kRuleBegin;
}
if (arg == "--no-check" || arg == "-n") {
opts_.check_uris = false;
return kNone;
}
if (arg == "--queue-buffer" || arg == "-q") {
return kQueueBuffer;
}
if (arg == "--only" || arg == "-o") {
return kQueue;
}
if (arg == "--file" || arg == "-f") {
return kFile;
}
if (arg == "--host") {
return kHost;
}
if (arg == "--port" || arg == "-p") {
return kPort;
}
if (arg == "--test_enable_option_do_not_use") {
return kTest;
}
if (arg == "--group-by" || arg == "-g") {
if (!opts_.group_by.empty()) {
return ParseError(
absl::StrFormat("'%s' can only be provided once", arg));
}
return kGroupBegin;
}
if (arg == "--by-album") {
if (!opts_.group_by.empty()) {
return ParseError(
absl::StrFormat("'%s' can only be provided once", arg));
}
opts_.group_by.push_back(MPD_TAG_ALBUM);
opts_.group_by.push_back(MPD_TAG_DATE);
return kNone;
}
if (arg == "--tweak" || arg == "-t") {
return kTweak;
}
if (arg == "--exclude-from") {
return kExcludeFile;
}
if (arg == "--log-file") {
return kLogFile;
}
}
switch (state_) {
case kExcludeFile:
if (auto error = LoadExcludeFile(arg); error.has_value()) {
return *error;
}
return kNone;
case kTweak:
return ParseTweak(arg);
case kFile:
if (arg == "-") {
opts_.file_in = &std::cin;
} else {
std::string filepath(arg);
opts_.InternalTakeIstream(
std::make_unique<std::ifstream>(filepath));
}
return kNone;
case kHost:
opts_.host = arg;
return kNone;
case kLogFile: {
std::string filepath(arg);
opts_.InternalTakeLog(std::make_unique<std::ofstream>(filepath));
return kNone;
}
case kPort:
if (!absl::SimpleAtoi(arg, &opts_.port)) {
return ParseError(
absl::StrFormat("couldn't convert port value '%s'", arg));
}
return kNone;
case kQueue:
if (!absl::SimpleAtoi(arg, &opts_.queue_only)) {
return ParseError(
absl::StrFormat("couldn't convert only value '%s'", arg));
}
return kNone;
case kQueueBuffer:
if (!absl::SimpleAtoi(arg, &opts_.queue_buffer)) {
return ParseError(absl::StrFormat(
"couldn't convert queue_buffer value '%s'", arg));
}
return kNone;
case kRule:
case kRuleBegin: {
std::optional<enum mpd_tag_type> tag = tag_parser_.Parse(arg);
if (!tag) {
return ParseError(
absl::StrFormat("invalid song tag name '%s'", arg));
}
rule_tag_ = *tag;
return kRuleValue;
}
case kRuleValue:
pending_rule_.AddPattern(rule_tag_, std::string(arg));
return kRule;
case kTest:
if (arg == "print_all_songs_and_exit") {
opts_.test.print_all_songs_and_exit = true;
return kNone;
}
return ParseError(absl::StrFormat("bad test option '%s'", arg));
case kGroup:
case kGroupBegin: {
std::optional<enum mpd_tag_type> tag = tag_parser_.Parse(arg);
if (!tag) {
return ParseError(
absl::StrFormat("invalid tag name '%s'", arg));
}
opts_.group_by.push_back(*tag);
return kGroup;
}
case kFinal:
case kError:
assert(false && "unreachable, should not be possible");
case kNone:
return ParseError(absl::StrFormat("bad option '%s'", arg));
}
assert(false && "unreachable, invalid state");
__builtin_unreachable();
}
} // namespace
std::variant<Options, ParseError> Options::Parse(
const mpd::TagParser& tag_parser, const std::vector<std::string>& args) {
Parser p(tag_parser);
for (std::string_view arg : args) {
if (p.Consume(arg) == Parser::Status::kDone) {
break;
}
}
return p.Finish();
}
std::ostream& DisplayHelp(std::ostream& output) {
output << kHelpMessage;
return output;
}
std::ostream& operator<<(std::ostream& out, const ParseError& e) {
std::string type;
switch (e.type) {
case ParseError::Type::kGeneric:
type = "generic";
break;
case ParseError::Type::kHelp:
type = "help";
break;
case ParseError::Type::kUnknown:
type = "unknown";
break;
case ParseError::Type::kVersion:
type = "version";
break;
}
out << "ParseError(" << type << ", \"" << e.msg << "\")" << std::endl;
return out;
}
} // namespace ashuffle