-
-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathCommandLine.cpp
More file actions
681 lines (551 loc) · 25 KB
/
CommandLine.cpp
File metadata and controls
681 lines (551 loc) · 25 KB
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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
/*==============================================================================
Copyright 2018 by Tracktion Corporation.
For more information visit www.tracktion.com
You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
pluginval IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================*/
#include "CommandLine.h"
#include "Validator.h"
#include "CrashHandler.h"
#include "PluginTests.h"
#if JUCE_MAC
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#endif
#include <magic_enum/magic_enum.hpp>
//==============================================================================
static void exitWithError (const juce::String& error)
{
std::cout << error << std::endl << std::endl;
juce::JUCEApplication::getInstance()->setApplicationReturnValue (1);
juce::JUCEApplication::getInstance()->quit();
}
static void hideDockIcon()
{
#if JUCE_MAC
juce::Process::setDockIconVisible (false);
#endif
}
inline std::mutex& getCoutMutex()
{
static std::mutex m;
return m;
}
inline void logLine (const juce::String& m)
{
const std::scoped_lock sl (getCoutMutex());
std::cout << m << std::endl;
}
inline void logAndFlush (const juce::String& m)
{
const std::scoped_lock sl (getCoutMutex());
std::cout << m << std::flush;
}
//==============================================================================
#if JUCE_MAC
static void kill9WithSomeMercy (int signal)
{
juce::Logger::writeToLog ("pluginval received " + juce::String(::strsignal(signal)) + ", exiting immediately");
// Use std::_Exit here instead of kill as kill doesn't seem to set the exit code of the process so is picked up as a "pass" in the host process
std::_Exit (SIGKILL);
}
// Avoid showing the macOS crash dialog, which can cause the process to hang
static void setupSignalHandling()
{
const int signals[] = { SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGABRT };
for (int i = 0; i < juce::numElementsInArray (signals); ++i)
{
::signal (signals[i], kill9WithSomeMercy);
::siginterrupt (signals[i], 1);
}
}
#endif
//==============================================================================
//==============================================================================
CommandLineValidator::CommandLineValidator()
{
#if JUCE_MAC
setupSignalHandling();
#endif
}
CommandLineValidator::~CommandLineValidator()
{
}
void CommandLineValidator::validate (const juce::String& fileOrID, PluginTests::Options options)
{
validator = std::make_unique<ValidationPass> (fileOrID, options, ValidationType::inProcess,
[] (auto id)
{
logLine ("Started validating: " + id);
},
[] (auto, uint32_t exitCode)
{
if (exitCode > 0)
exitWithError ("*** FAILED");
else
juce::JUCEApplication::getInstance()->quit();
},
[] (auto m)
{
logAndFlush (m);
});
}
//==============================================================================
//==============================================================================
namespace
{
juce::ArgumentList::Argument getArgumentAfterOption (const juce::ArgumentList& args, juce::StringRef option)
{
for (int i = 0; i < args.size() - 1; ++i)
if (args[i] == option)
return args[i + 1];
return {};
}
juce::var getOptionValue (const juce::ArgumentList& args, juce::StringRef option, juce::var defaultValue, juce::StringRef errorMessage)
{
if (args.containsOption (option))
{
const auto nextArg = getArgumentAfterOption (args, option);
if (nextArg.isShortOption() || nextArg.isLongOption())
juce::ConsoleApplication::fail (errorMessage, -1);
return nextArg.text;
}
return defaultValue;
}
int getStrictnessLevel (const juce::ArgumentList& args)
{
return juce::jlimit (1, 10, (int) getOptionValue (args, "--strictness-level", 5, "Missing strictness level argument! (Must be between 1 - 10)"));
}
juce::int64 getRandomSeed (const juce::ArgumentList& args)
{
const juce::String seedString = getOptionValue (args, "--random-seed", "0", "Missing random seed argument!").toString();
if (! seedString.containsOnly ("x-0123456789acbdef"))
juce::ConsoleApplication::fail ("Invalid random seed argument!", -1);
if (seedString.startsWith ("0x"))
return seedString.getHexValue64();
return seedString.getLargeIntValue();
}
juce::int64 getTimeout (const juce::ArgumentList& args)
{
return getOptionValue (args, "--timeout-ms", 30000, "Missing timeout-ms level argument!");
}
int getNumRepeats (const juce::ArgumentList& args)
{
return juce::jmax (1, (int) getOptionValue (args, "--repeat", 1, "Missing repeat argument! (Must be greater than 0)"));
}
juce::File getDataFile (const juce::ArgumentList& args)
{
return getOptionValue (args, "--data-file", {}, "Missing data-file path argument!").toString();
}
juce::File getOutputDir (const juce::ArgumentList& args)
{
return getOptionValue (args, "--output-dir", {}, "Missing output-dir path argument!").toString();
}
juce::String getOutputFilename (const juce::ArgumentList& args)
{
return getOptionValue (args, "--output-filename", {}, "Missing output-filename path argument!").toString();
}
std::vector<double> getSampleRates (const juce::ArgumentList& args)
{
juce::StringArray input = juce::StringArray::fromTokens (getOptionValue (args,
"--sample-rates",
juce::String ("44100,48000,96000"),
"Missing sample rate list argument!")
.toString(),
",",
"\"");
std::vector<double> output;
for (juce::String sr : input)
output.push_back (sr.getDoubleValue());
return output;
}
std::vector<int> getBlockSizes (const juce::ArgumentList& args)
{
juce::StringArray input = juce::StringArray::fromTokens (getOptionValue (args,
"--block-sizes",
juce::String ("64,128,256,512,1024"),
"Missing block size list argument!")
.toString(),
",",
"\"");
std::vector<int> output;
for (juce::String sr : input)
output.push_back (sr.getIntValue());
return output;
}
juce::StringArray getDisabledTests (const juce::ArgumentList& args)
{
const auto value = getOptionValue (args, "--disabled-tests", {}, "Missing disabled-tests path argument!").toString();
if (juce::File::isAbsolutePath (value))
{
const juce::File disabledTestsFile (value);
juce::StringArray disabledTests;
disabledTestsFile.readLines (disabledTests);
return disabledTests;
}
return juce::StringArray::fromTokens (value, ",", "");
}
bool isPluginArgument (juce::String arg)
{
juce::AudioPluginFormatManager formatManager;
#if JUCE_VERSION >= 0x08000B
juce::addDefaultFormatsToManager (formatManager);
#else
formatManager.addDefaultFormats();
#endif
for (auto format : formatManager.getFormats())
if (format->fileMightContainThisPluginType (arg))
return true;
// The above will check if the file actually exists which isn't really what we want for CLI parsing
if (auto f = juce::File::createFileWithoutCheckingPath (arg);
f.hasFileExtension (".vst3")
#if JUCE_PLUGINHOST_VST
|| f.hasFileExtension (".dll")
#endif
)
return true;
return false;
}
}
//==============================================================================
struct Option
{
const char* name;
bool requiresValue;
};
static juce::String getEnvironmentVariableName (Option opt)
{
return juce::String (opt.name).trimCharactersAtStart ("-").replace ("-", "_").toUpperCase();
}
static Option possibleOptions[] =
{
{ "--strictness-level", true },
{ "--random-seed", true },
{ "--timeout-ms", true },
{ "--verbose", true },
{ "--skip-gui-tests", false },
{ "--data-file", true },
{ "--output-dir", true },
{ "--output-filename", true },
{ "--repeat", true },
{ "--randomise", false },
{ "--sample-rates", true },
{ "--block-sizes", true },
{ "--rtcheck", false },
};
static juce::StringArray mergeEnvironmentVariables (juce::StringArray args, std::function<juce::String (const juce::String& name, const juce::String& defaultValue)> environmentVariableProvider = [] (const juce::String& name, const juce::String& defaultValue) { return juce::SystemStats::getEnvironmentVariable (name, defaultValue); })
{
for (auto arg : possibleOptions)
{
auto envVarName = getEnvironmentVariableName (arg);
auto envVarValue = environmentVariableProvider (envVarName, {});
if (envVarValue.isNotEmpty())
{
const int index = args.indexOf (arg.name);
if (index != -1)
{
std::cout << "Skipping environment variable " << envVarName << " due to " << arg.name << " set" << std::endl;
continue;
}
if (arg.requiresValue)
args.insert (0, envVarValue);
args.insert (0, arg.name);
}
}
return args;
}
//==============================================================================
//==============================================================================
static juce::String getHelpMessage()
{
const juce::String appName (juce::JUCEApplication::getInstance()->getApplicationName());
const juce::String juceVersion (juce::SystemStats::getJUCEVersion());
return juce::String (R"(//==============================================================================
)" + appName + R"(
)" + juceVersion + R"(
Description:
Validate plugins to test compatibility with hosts and verify plugin API conformance
Usage:
--version
Print pluginval version.
--validate [pathToPlugin]
Validates the plugin at the given path.
N.B. the "--validate" flag is optional if the path is the last argument.
This enables you to validate a plugin with simply "pluginval path_to_plugin".
--sample-rates [list of comma separated sample rates]
If specified, sets the list of sample rates at which tests will be executed
(default=44100,48000,96000)
--block-sizes [list of comma separated block sizes]
If specified, sets the list of block sizes at which tests will be executed
(default=64,128,256,512,1024)
--random-seed [hex or int]
Sets the random seed to use for the tests. Useful for replicating test
environments.
--data-file [pathToFile]
If specified, sets a path to a data file which can be used by tests to
configure themselves. This can be useful for things like known audio output.
--strictness-level [1-10]
Sets the strictness level to use. A minimum level of 5 (also the default)
is recommended for compatibility.
Higher levels include longer, more thorough tests such as fuzzing.
--strictness-help [level]
Lists all tests that run at the given strictness level (default: 5).
--timeout-ms [numMilliseconds]
Sets a timout which will stop validation with an error if no output from any
test has happened for this number of ms.
By default this is 30s but can be set to "-1" (must be quoted) to never timeout.
--rtcheck [empty, disabled, enabled or relaxed]
Turns on real-time safety checks using rtcheck (macOS and Linux only).
relaxed mode doesn't run the checks for the first processing block as a lot of plugins
use this to allocate or initialise thread-locals (which can allocate)
--repeat [num repeats]
If specified repeats the tests a given number of times. Note that this does
not delete and re-instantiate the plugin for each repeat.
--randomise
If specified, the tests are run in a random order per repeat.
--skip-gui-tests
If specified, avoids tests that create GUI windows, which can cause problems
on headless CI systems.
--disabled-tests [pathToFile]
If specified, sets a path to a file that should have the names of disabled
tests on each row.
--output-dir [pathToDir]
If specified, sets a directory to store the log files. This can be useful
for continuous integration.
--output-filename [filename]
If specified, sets a filename for the log files (within 'output-dir' or
(lacking that) the current directory.
By default, the name is constructed from the plugin metainformation
--verbose
If specified, outputs additional logging information. It can be useful to
turn this off when building with CI to avoid huge log files.
Exit code:
0 if all tests complete successfully
1 if there are any errors
Additionally, you can specify any of the command line options as environment
variables by removing prefix dashes, converting internal dashes to underscores
and capitalising all letters, a.g.
"--skip-gui-tests" > "SKIP_GUI_TESTS=1"
"--timeout-ms 30000" > "TIMEOUT_MS=30000"
Specifying specific command-line options will override any environment variables
set for that option.
)");
}
static juce::String getVersionText()
{
return juce::String ("pluginval") + " - " + VERSION;
}
static void printStrictnessHelp (int level)
{
level = juce::jlimit (1, 10, level);
std::cout << "Tests at strictness level " << level << ":\n\n";
auto& allTests = PluginTest::getAllTests();
std::vector<PluginTest*> sortedTests;
for (auto* test : allTests)
sortedTests.push_back (test);
std::sort (sortedTests.begin(), sortedTests.end(),
[] (const PluginTest* a, const PluginTest* b)
{ return a->strictnessLevel < b->strictnessLevel; });
for (auto* test : sortedTests)
{
if (test->strictnessLevel > level)
continue;
auto descriptions = test->getDescription (level);
for (const auto& desc : descriptions)
{
std::cout << " " << desc.title;
if (desc.description.isNotEmpty())
std::cout << ": " << desc.description;
std::cout << "\n";
}
}
std::cout << std::endl;
}
static int getNumTestFailures (juce::UnitTestRunner& testRunner)
{
int numFailures = 0;
for (int i = 0; i < testRunner.getNumResults(); ++i)
if (auto result = testRunner.getResult (i))
numFailures += result->failures;
return numFailures;
}
static void runUnitTests()
{
juce::UnitTestRunner testRunner;
testRunner.runTestsInCategory ("pluginval");
const int numFailures = getNumTestFailures (testRunner);
if (numFailures > 0)
juce::ConsoleApplication::fail (juce::String (numFailures) + " tests failed!!!");
}
//==============================================================================
static juce::ArgumentList createCommandLineArgs (juce::String commandLine)
{
if (commandLine.contains ("strictnessLevel"))
{
std::cout << "!!! WARNING:\n\t\"strictnessLevel\" is deprecated and will be removed in a future version.\n"
<< "\tPlease use --strictness-level instead\n\n";
}
commandLine = commandLine.replace ("strictnessLevel", "strictness-level")
.replace ("-NSDocumentRevisionsDebugMode YES", "")
.trim();
const auto exe = juce::File::getSpecialLocation (juce::File::currentExecutableFile);
juce::StringArray args;
args.addTokens (commandLine, true);
args = mergeEnvironmentVariables (args);
args.trim();
for (auto& s : args)
s = s.unquoted();
// If only a plugin path is supplied as the last arg, add an implicit --validate
// option for it so the rest of the CLI works
juce::ArgumentList argList (exe.getFullPathName(), args);
if (argList.size() > 0)
{
const bool hasValidateOrOtherCommand = argList.containsOption ("--validate")
|| argList.containsOption ("--help|-h")
|| argList.containsOption ("--version")
|| argList.containsOption ("--run-tests");
if (! hasValidateOrOtherCommand)
if (isPluginArgument (argList.arguments.getLast().text))
argList.arguments.insert (argList.arguments.size() - 1, { "--validate" });
}
return argList;
}
static void performCommandLine (CommandLineValidator& validator, const juce::ArgumentList& args)
{
hideDockIcon();
juce::ConsoleApplication cli;
cli.addVersionCommand ("--version", getVersionText());
cli.addHelpCommand ("--help|-h", getHelpMessage(), true);
cli.addCommand ({ "--validate",
"--validate [pathToPlugin]",
"Validates the file (or IDs for AUs).", juce::String(),
[&validator] (const auto& validatorArgs)
{
auto [fileOrIDToValidate, options] = parseCommandLine (validatorArgs);
validator.validate (fileOrIDToValidate, options);
}});
cli.addCommand ({ "--run-tests",
"--run-tests",
"Runs the internal unit tests.", juce::String(),
[] (const auto&) { runUnitTests(); }});
cli.addCommand ({ "--strictness-help",
"--strictness-help [level]",
"Lists all tests that run at the given strictness level.", juce::String(),
[] (const auto& args)
{
int level = 5;
auto arg = getArgumentAfterOption (args, "--strictness-help");
if (arg.text.isNotEmpty() && ! arg.isShortOption() && ! arg.isLongOption())
level = arg.text.getIntValue();
printStrictnessHelp (level);
}});
if (const auto retValue = cli.findAndRunCommand (args); retValue != 0)
{
juce::JUCEApplication::getInstance()->setApplicationReturnValue (retValue);
juce::JUCEApplication::getInstance()->quit();
}
// --validate runs async so will quit itself when done
if (! args.containsOption ("--validate"))
juce::JUCEApplication::getInstance()->quit();
}
//==============================================================================
void performCommandLine (CommandLineValidator& validator, const juce::String& commandLine)
{
performCommandLine (validator, createCommandLineArgs (commandLine));
}
bool shouldPerformCommandLine (const juce::String& commandLine)
{
const auto args = createCommandLineArgs (commandLine);
return args.containsOption ("--help|-h")
|| args.containsOption ("--version")
|| args.containsOption ("--validate")
|| args.containsOption ("--run-tests")
|| args.containsOption ("--strictness-help");
}
//==============================================================================
//==============================================================================
std::pair<juce::String, PluginTests::Options> parseCommandLine (const juce::ArgumentList& args)
{
auto fileOrID = getOptionValue (args, "--validate", "", "Expected a plugin path for the --validate option").toString();
// in the case of a path (vs. ID), grab the full path
// getCurrentWorkingDirectory is needed to handle relative paths
// It preserves absolute paths and first checks for ~ on Mac/Windows
if (fileOrID.contains ("~") || fileOrID.contains ("."))
fileOrID = juce::File::getCurrentWorkingDirectory().getChildFile(fileOrID).getFullPathName();
PluginTests::Options options;
options.strictnessLevel = getStrictnessLevel (args);
options.randomSeed = getRandomSeed (args);
options.timeoutMs = getTimeout (args);
options.verbose = args.containsOption ("--verbose");
options.numRepeats = getNumRepeats (args);
options.randomiseTestOrder = args.containsOption ("--randomise");
options.dataFile = getDataFile (args);
options.outputDir = getOutputDir (args);
options.outputFilename = getOutputFilename (args);
options.withGUI = ! args.containsOption ("--skip-gui-tests");
options.disabledTests = getDisabledTests (args);
options.sampleRates = getSampleRates (args);
options.blockSizes = getBlockSizes (args);
options.realtimeCheck = magic_enum::enum_cast<RealtimeCheck> (getOptionValue (args, "--rtcheck", "", "Expected one of [disabled, enabled, relaxed]").toString().toStdString())
.value_or (RealtimeCheck::disabled);
return { fileOrID, options };
}
std::pair<juce::String, PluginTests::Options> parseCommandLine (const juce::String& cmd)
{
return parseCommandLine (createCommandLineArgs (cmd));
}
juce::StringArray createCommandLine (juce::String fileOrID, PluginTests::Options options)
{
juce::StringArray args (juce::File::getSpecialLocation (juce::File::currentExecutableFile).getFullPathName());
const PluginTests::Options defaults;
if (options.strictnessLevel != defaults.strictnessLevel)
args.addArray ({ "--strictness-level", juce::String (options.strictnessLevel) });
if (options.randomSeed != defaults.randomSeed)
args.addArray ({ "--random-seed", juce::String (options.randomSeed) });
if (options.timeoutMs != defaults.timeoutMs)
args.addArray ({ "--timeout-ms", juce::String (options.timeoutMs) });
if (options.verbose)
args.add ("--verbose");
if (! options.withGUI)
args.add ("--skip-gui-tests");
if (options.numRepeats != defaults.numRepeats)
args.addArray ({ "--repeat", juce::String (options.numRepeats) });
if (options.randomiseTestOrder)
args.add ("--randomise");
if (options.dataFile != defaults.dataFile)
args.addArray ({ "--data-file", options.dataFile.getFullPathName() });
if (options.outputDir != defaults.outputDir)
args.addArray ({ "--output-dir", options.outputDir.getFullPathName() });
if (options.outputFilename != defaults.outputFilename)
args.addArray ({ "--output-filename", options.outputFilename });
if (options.disabledTests != defaults.disabledTests)
args.addArray ({ "--disabled-tests", options.disabledTests.joinIntoString (",") });
if (! options.sampleRates.empty())
{
juce::StringArray sampleRates;
for (auto rate : options.sampleRates)
sampleRates.add (juce::String (rate));
args.addArray ({ "--sample-rates", sampleRates.joinIntoString (",") });
}
if (! options.blockSizes.empty())
{
juce::StringArray blockSizes;
for (auto size : options.blockSizes)
blockSizes.add (juce::String (size));
args.addArray ({ "--block-sizes", blockSizes.joinIntoString (",") });
}
if (auto rtCheckMode = options.realtimeCheck;
rtCheckMode != RealtimeCheck::disabled)
{
args.addArray ({ "--rtcheck", std::string (magic_enum::enum_name (rtCheckMode)) });
}
args.addArray ({ "--validate", fileOrID });
return args;
}
//==============================================================================
//==============================================================================
#include "CommandLineTests.cpp"