The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

357 lines
10KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. The code included in this file is provided under the terms of the ISC license
  8. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  9. To use, copy, modify, and/or distribute this software for any purpose with or
  10. without fee is hereby granted provided that the above copyright notice and
  11. this permission notice appear in all copies.
  12. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  13. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  14. DISCLAIMED.
  15. ==============================================================================
  16. */
  17. namespace juce
  18. {
  19. static inline File resolveFilename (const String& name)
  20. {
  21. return File::getCurrentWorkingDirectory().getChildFile (name.unquoted());
  22. }
  23. static inline void checkFileExists (const File& f)
  24. {
  25. if (! f.exists())
  26. ConsoleApplication::fail ("Could not find file: " + f.getFullPathName());
  27. }
  28. static inline void checkFolderExists (const File& f)
  29. {
  30. if (! f.isDirectory())
  31. ConsoleApplication::fail ("Could not find folder: " + f.getFullPathName());
  32. }
  33. File ArgumentList::Argument::resolveAsFile() const
  34. {
  35. return resolveFilename (text);
  36. }
  37. File ArgumentList::Argument::resolveAsExistingFile() const
  38. {
  39. auto f = resolveAsFile();
  40. checkFileExists (f);
  41. return f;
  42. }
  43. File ArgumentList::Argument::resolveAsExistingFolder() const
  44. {
  45. auto f = resolveAsFile();
  46. if (! f.isDirectory())
  47. ConsoleApplication::fail ("Could not find folder: " + f.getFullPathName());
  48. return f;
  49. }
  50. static inline bool isShortOptionFormat (StringRef s) { return s[0] == '-' && s[1] != '-'; }
  51. static inline bool isLongOptionFormat (StringRef s) { return s[0] == '-' && s[1] == '-' && s[2] != '-'; }
  52. static inline bool isOptionFormat (StringRef s) { return s[0] == '-'; }
  53. bool ArgumentList::Argument::isLongOption() const { return isLongOptionFormat (text); }
  54. bool ArgumentList::Argument::isShortOption() const { return isShortOptionFormat (text); }
  55. bool ArgumentList::Argument::isOption() const { return isOptionFormat (text); }
  56. bool ArgumentList::Argument::isLongOption (const String& option) const
  57. {
  58. if (! isLongOptionFormat (option))
  59. {
  60. jassert (! isShortOptionFormat (option)); // this will always fail to match
  61. return isLongOption ("--" + option);
  62. }
  63. return text.upToFirstOccurrenceOf ("=", false, false) == option;
  64. }
  65. String ArgumentList::Argument::getLongOptionValue() const
  66. {
  67. if (isLongOption())
  68. if (auto equalsIndex = text.indexOfChar ('='))
  69. return text.substring (equalsIndex + 1);
  70. return {};
  71. }
  72. bool ArgumentList::Argument::isShortOption (char option) const
  73. {
  74. jassert (option != '-'); // this is probably not what you intended to pass in
  75. return isShortOption() && text.containsChar (option);
  76. }
  77. bool ArgumentList::Argument::operator== (StringRef wildcard) const
  78. {
  79. for (auto& o : StringArray::fromTokens (wildcard, "|", {}))
  80. {
  81. if (text == o)
  82. return true;
  83. if (isShortOptionFormat (o) && o.length() == 2 && isShortOption ((char) o[1]))
  84. return true;
  85. if (isLongOptionFormat (o) && isLongOption (o))
  86. return true;
  87. }
  88. return false;
  89. }
  90. bool ArgumentList::Argument::operator!= (StringRef s) const { return ! operator== (s); }
  91. //==============================================================================
  92. ArgumentList::ArgumentList (String exeName, StringArray args)
  93. : executableName (std::move (exeName))
  94. {
  95. args.trim();
  96. args.removeEmptyStrings();
  97. for (auto& a : args)
  98. arguments.add ({ a });
  99. }
  100. ArgumentList::ArgumentList (int argc, char* argv[])
  101. : ArgumentList (argv[0], StringArray (argv + 1, argc - 1))
  102. {
  103. }
  104. ArgumentList::ArgumentList (const String& exeName, const String& args)
  105. : ArgumentList (exeName, StringArray::fromTokens (args, true))
  106. {
  107. }
  108. int ArgumentList::size() const { return arguments.size(); }
  109. ArgumentList::Argument ArgumentList::operator[] (int index) const { return arguments[index]; }
  110. void ArgumentList::checkMinNumArguments (int expectedMinNumberOfArgs) const
  111. {
  112. if (size() < expectedMinNumberOfArgs)
  113. ConsoleApplication::fail ("Not enough arguments!");
  114. }
  115. int ArgumentList::indexOfOption (StringRef option) const
  116. {
  117. jassert (option == String (option).trim()); // passing non-trimmed strings will always fail to find a match!
  118. for (int i = 0; i < arguments.size(); ++i)
  119. if (arguments.getReference(i) == option)
  120. return i;
  121. return -1;
  122. }
  123. bool ArgumentList::containsOption (StringRef option) const
  124. {
  125. return indexOfOption (option) >= 0;
  126. }
  127. void ArgumentList::failIfOptionIsMissing (StringRef option) const
  128. {
  129. if (! containsOption (option))
  130. ConsoleApplication::fail ("Expected the option " + option);
  131. }
  132. String ArgumentList::getValueForOption (StringRef option) const
  133. {
  134. jassert (isOptionFormat (option)); // the thing you're searching for must be an option
  135. for (int i = 0; i < arguments.size(); ++i)
  136. {
  137. auto& arg = arguments.getReference(i);
  138. if (arg == option)
  139. {
  140. if (arg.isShortOption())
  141. {
  142. if (i < arguments.size() - 1 && ! arguments.getReference (i + 1).isOption())
  143. return arguments.getReference (i + 1).text;
  144. return {};
  145. }
  146. if (arg.isLongOption())
  147. return arg.getLongOptionValue();
  148. }
  149. }
  150. return {};
  151. }
  152. File ArgumentList::getFileForOption (StringRef option) const
  153. {
  154. auto text = getValueForOption (option);
  155. if (text.isEmpty())
  156. {
  157. failIfOptionIsMissing (option);
  158. ConsoleApplication::fail ("Expected a filename after the " + option + " option");
  159. }
  160. return resolveFilename (text);
  161. }
  162. File ArgumentList::getExistingFileForOption (StringRef option) const
  163. {
  164. auto file = getFileForOption (option);
  165. checkFileExists (file);
  166. return file;
  167. }
  168. File ArgumentList::getExistingFolderForOption (StringRef option) const
  169. {
  170. auto file = getFileForOption (option);
  171. checkFolderExists (file);
  172. return file;
  173. }
  174. //==============================================================================
  175. struct ConsoleAppFailureCode
  176. {
  177. String errorMessage;
  178. int returnCode;
  179. };
  180. void ConsoleApplication::fail (String errorMessage, int returnCode)
  181. {
  182. throw ConsoleAppFailureCode { std::move (errorMessage), returnCode };
  183. }
  184. int ConsoleApplication::invokeCatchingFailures (std::function<int()>&& f)
  185. {
  186. int returnCode = 0;
  187. try
  188. {
  189. returnCode = f();
  190. }
  191. catch (const ConsoleAppFailureCode& error)
  192. {
  193. std::cout << error.errorMessage << std::endl;
  194. returnCode = error.returnCode;
  195. }
  196. return returnCode;
  197. }
  198. const ConsoleApplication::Command* ConsoleApplication::findCommand (const ArgumentList& args, bool optionMustBeFirstArg) const
  199. {
  200. for (auto& c : commands)
  201. {
  202. auto index = args.indexOfOption (c.commandOption);
  203. if (optionMustBeFirstArg ? (index == 0) : (index >= 0))
  204. return &c;
  205. }
  206. if (commandIfNoOthersRecognised >= 0)
  207. return &commands[(size_t) commandIfNoOthersRecognised];
  208. return {};
  209. }
  210. int ConsoleApplication::findAndRunCommand (const ArgumentList& args, bool optionMustBeFirstArg) const
  211. {
  212. if (auto c = findCommand (args, optionMustBeFirstArg))
  213. return invokeCatchingFailures ([=] { c->command (args); return 0; });
  214. fail ("Unrecognised arguments");
  215. return 0;
  216. }
  217. int ConsoleApplication::findAndRunCommand (int argc, char* argv[]) const
  218. {
  219. return findAndRunCommand (ArgumentList (argc, argv));
  220. }
  221. void ConsoleApplication::addCommand (Command c)
  222. {
  223. commands.emplace_back (std::move (c));
  224. }
  225. void ConsoleApplication::addDefaultCommand (Command c)
  226. {
  227. commandIfNoOthersRecognised = (int) commands.size();
  228. addCommand (std::move (c));
  229. }
  230. void ConsoleApplication::addHelpCommand (String arg, String helpMessage, bool makeDefaultCommand)
  231. {
  232. Command c { arg, arg, "Prints the list of commands", {},
  233. [this, helpMessage] (const ArgumentList& args)
  234. {
  235. std::cout << helpMessage << std::endl;
  236. printCommandList (args);
  237. }};
  238. if (makeDefaultCommand)
  239. addDefaultCommand (std::move (c));
  240. else
  241. addCommand (std::move (c));
  242. }
  243. void ConsoleApplication::addVersionCommand (String arg, String versionText)
  244. {
  245. addCommand ({ arg, arg, "Prints the current version number", {},
  246. [versionText] (const ArgumentList&)
  247. {
  248. std::cout << versionText << std::endl;
  249. }});
  250. }
  251. const std::vector<ConsoleApplication::Command>& ConsoleApplication::getCommands() const
  252. {
  253. return commands;
  254. }
  255. void ConsoleApplication::printCommandList (const ArgumentList& args) const
  256. {
  257. auto exeName = args.executableName.fromLastOccurrenceOf ("/", false, false)
  258. .fromLastOccurrenceOf ("\\", false, false);
  259. StringArray namesAndArgs;
  260. int descriptionIndent = 0;
  261. for (auto& c : commands)
  262. {
  263. auto nameAndArgs = exeName + " " + c.argumentDescription;
  264. namesAndArgs.add (nameAndArgs);
  265. descriptionIndent = std::max (descriptionIndent, nameAndArgs.length());
  266. }
  267. descriptionIndent = std::min (descriptionIndent + 1, 40);
  268. for (size_t i = 0; i < commands.size(); ++i)
  269. {
  270. auto nameAndArgs = namesAndArgs[(int) i];
  271. std::cout << ' ';
  272. if (nameAndArgs.length() > descriptionIndent)
  273. std::cout << nameAndArgs << std::endl << String::repeatedString (" ", descriptionIndent + 1);
  274. else
  275. std::cout << nameAndArgs.paddedRight (' ', descriptionIndent);
  276. std::cout << commands[i].shortDescription << std::endl;
  277. }
  278. std::cout << std::endl;
  279. }
  280. } // namespace juce