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.

918 lines
37KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #include "jucer_Headers.h"
  19. #include "jucer_Application.h"
  20. #include "../Utility/Helpers/jucer_TranslationHelpers.h"
  21. #include "jucer_CommandLine.h"
  22. //==============================================================================
  23. const char* preferredLineFeed = "\r\n";
  24. const char* getPreferredLineFeed() { return preferredLineFeed; }
  25. //==============================================================================
  26. namespace
  27. {
  28. static void hideDockIcon()
  29. {
  30. #if JUCE_MAC
  31. Process::setDockIconVisible (false);
  32. #endif
  33. }
  34. static Array<File> findAllSourceFiles (const File& folder)
  35. {
  36. Array<File> files;
  37. for (const auto& di : RangedDirectoryIterator (folder, true, "*.cpp;*.cxx;*.cc;*.c;*.h;*.hpp;*.hxx;*.hpp;*.mm;*.m;*.java;*.dox;*.soul;*.js", File::findFiles))
  38. if (! di.getFile().isSymbolicLink())
  39. files.add (di.getFile());
  40. return files;
  41. }
  42. static void replaceFile (const File& file, const String& newText, const String& message)
  43. {
  44. std::cout << message << file.getFullPathName() << std::endl;
  45. TemporaryFile temp (file);
  46. if (! temp.getFile().replaceWithText (newText, false, false, nullptr))
  47. ConsoleApplication::fail ("!!! ERROR Couldn't write to temp file!");
  48. if (! temp.overwriteTargetFileWithTemporary())
  49. ConsoleApplication::fail ("!!! ERROR Couldn't write to file!");
  50. }
  51. //==============================================================================
  52. struct LoadedProject
  53. {
  54. explicit LoadedProject (const ArgumentList::Argument& fileToLoad)
  55. {
  56. hideDockIcon();
  57. auto projectFile = fileToLoad.resolveAsExistingFile();
  58. if (! projectFile.hasFileExtension (Project::projectFileExtension))
  59. ConsoleApplication::fail (projectFile.getFullPathName() + " isn't a valid jucer project file!");
  60. project.reset (new Project (projectFile));
  61. if (! project->loadFrom (projectFile, true, false))
  62. {
  63. project.reset();
  64. ConsoleApplication::fail ("Failed to load the project file: " + projectFile.getFullPathName());
  65. }
  66. preferredLineFeed = project->getProjectLineFeed().toRawUTF8();
  67. }
  68. void save (bool justSaveResources)
  69. {
  70. if (project != nullptr)
  71. {
  72. if (! justSaveResources)
  73. rescanModulePathsIfNecessary();
  74. auto error = justSaveResources ? project->saveResourcesOnly()
  75. : project->saveProject();
  76. project.reset();
  77. if (error.failed())
  78. ConsoleApplication::fail ("Error when saving: " + error.getErrorMessage());
  79. }
  80. }
  81. void rescanModulePathsIfNecessary()
  82. {
  83. bool scanJUCEPath = false, scanUserPaths = false;
  84. const auto& modules = project->getEnabledModules();
  85. for (auto i = modules.getNumModules(); --i >= 0;)
  86. {
  87. const auto& id = modules.getModuleID (i);
  88. if (isJUCEModule (id) && ! scanJUCEPath)
  89. {
  90. if (modules.shouldUseGlobalPath (id))
  91. scanJUCEPath = true;
  92. }
  93. else if (! scanUserPaths)
  94. {
  95. if (modules.shouldUseGlobalPath (id))
  96. scanUserPaths = true;
  97. }
  98. }
  99. if (scanJUCEPath)
  100. ProjucerApplication::getApp().rescanJUCEPathModules();
  101. if (scanUserPaths)
  102. ProjucerApplication::getApp().rescanUserPathModules();
  103. }
  104. std::unique_ptr<Project> project;
  105. };
  106. //==============================================================================
  107. /* Running a command-line of the form "projucer --resave foobar.jucer" will try to load
  108. that project and re-export all of its targets.
  109. */
  110. static void resaveProject (const ArgumentList& args, bool justSaveResources)
  111. {
  112. args.checkMinNumArguments (2);
  113. LoadedProject proj (args[1]);
  114. std::cout << (justSaveResources ? "Re-saving project resources: "
  115. : "Re-saving file: ")
  116. << proj.project->getFile().getFullPathName() << std::endl;
  117. proj.save (justSaveResources);
  118. }
  119. //==============================================================================
  120. static void getVersion (const ArgumentList& args)
  121. {
  122. args.checkMinNumArguments (2);
  123. LoadedProject proj (args[1]);
  124. std::cout << proj.project->getVersionString() << std::endl;
  125. }
  126. //==============================================================================
  127. static void setVersion (const ArgumentList& args)
  128. {
  129. args.checkMinNumArguments (2);
  130. LoadedProject proj (args[2]);
  131. String version (args[1].text.trim());
  132. std::cout << "Setting project version: " << version << std::endl;
  133. proj.project->setProjectVersion (version);
  134. proj.save (false);
  135. }
  136. //==============================================================================
  137. static void bumpVersion (const ArgumentList& args)
  138. {
  139. args.checkMinNumArguments (2);
  140. LoadedProject proj (args[1]);
  141. String version = proj.project->getVersionString();
  142. version = version.upToLastOccurrenceOf (".", true, false)
  143. + String (version.getTrailingIntValue() + 1);
  144. std::cout << "Bumping project version to: " << version << std::endl;
  145. proj.project->setProjectVersion (version);
  146. proj.save (false);
  147. }
  148. static void gitTag (const ArgumentList& args)
  149. {
  150. args.checkMinNumArguments (2);
  151. LoadedProject proj (args[1]);
  152. String version (proj.project->getVersionString());
  153. if (version.trim().isEmpty())
  154. ConsoleApplication::fail ("Cannot read version number from project!");
  155. StringArray command;
  156. command.add ("git");
  157. command.add ("tag");
  158. command.add ("-a");
  159. command.add (version);
  160. command.add ("-m");
  161. command.add (version.quoted());
  162. std::cout << "Performing command: " << command.joinIntoString(" ") << std::endl;
  163. ChildProcess c;
  164. if (! c.start (command, 0))
  165. ConsoleApplication::fail ("Cannot run git!");
  166. c.waitForProcessToFinish (10000);
  167. if (c.getExitCode() != 0)
  168. ConsoleApplication::fail ("git command failed!");
  169. }
  170. //==============================================================================
  171. static void showStatus (const ArgumentList& args)
  172. {
  173. args.checkMinNumArguments (2);
  174. LoadedProject proj (args[1]);
  175. std::cout << "Project file: " << proj.project->getFile().getFullPathName() << std::endl
  176. << "Name: " << proj.project->getProjectNameString() << std::endl
  177. << "UID: " << proj.project->getProjectUIDString() << std::endl;
  178. auto& modules = proj.project->getEnabledModules();
  179. if (int numModules = modules.getNumModules())
  180. {
  181. std::cout << "Modules:" << std::endl;
  182. for (int i = 0; i < numModules; ++i)
  183. std::cout << " " << modules.getModuleID (i) << std::endl;
  184. }
  185. }
  186. //==============================================================================
  187. static String getModulePackageName (const LibraryModule& module)
  188. {
  189. return module.getID() + ".jucemodule";
  190. }
  191. static void zipModule (const File& targetFolder, const File& moduleFolder)
  192. {
  193. jassert (targetFolder.isDirectory());
  194. auto moduleFolderParent = moduleFolder.getParentDirectory();
  195. LibraryModule module (moduleFolder);
  196. if (! module.isValid())
  197. ConsoleApplication::fail (moduleFolder.getFullPathName() + " is not a valid module folder!");
  198. auto targetFile = targetFolder.getChildFile (getModulePackageName (module));
  199. ZipFile::Builder zip;
  200. {
  201. for (const auto& i : RangedDirectoryIterator (moduleFolder, true, "*", File::findFiles))
  202. if (! i.getFile().isHidden())
  203. zip.addFile (i.getFile(), 9, i.getFile().getRelativePathFrom (moduleFolderParent));
  204. }
  205. std::cout << "Writing: " << targetFile.getFullPathName() << std::endl;
  206. TemporaryFile temp (targetFile);
  207. {
  208. FileOutputStream out (temp.getFile());
  209. if (! (out.openedOk() && zip.writeToStream (out, nullptr)))
  210. ConsoleApplication::fail ("Failed to write to the target file: " + targetFile.getFullPathName());
  211. }
  212. if (! temp.overwriteTargetFileWithTemporary())
  213. ConsoleApplication::fail ("Failed to write to the target file: " + targetFile.getFullPathName());
  214. }
  215. static void buildModules (const ArgumentList& args, const bool buildAllWithIndex)
  216. {
  217. hideDockIcon();
  218. args.checkMinNumArguments (3);
  219. auto targetFolder = args[1].resolveAsFile();
  220. if (! targetFolder.isDirectory())
  221. ConsoleApplication::fail ("The first argument must be the directory to put the result.");
  222. if (buildAllWithIndex)
  223. {
  224. auto folderToSearch = args[2].resolveAsFile();
  225. var infoList;
  226. for (const auto& i : RangedDirectoryIterator (folderToSearch, false, "*", File::findDirectories))
  227. {
  228. LibraryModule module (i.getFile());
  229. if (module.isValid())
  230. {
  231. zipModule (targetFolder, i.getFile());
  232. var moduleInfo (new DynamicObject());
  233. moduleInfo.getDynamicObject()->setProperty ("file", getModulePackageName (module));
  234. moduleInfo.getDynamicObject()->setProperty ("info", module.moduleInfo.getModuleInfo());
  235. infoList.append (moduleInfo);
  236. }
  237. }
  238. auto indexFile = targetFolder.getChildFile ("modulelist");
  239. std::cout << "Writing: " << indexFile.getFullPathName() << std::endl;
  240. indexFile.replaceWithText (JSON::toString (infoList), false, false);
  241. }
  242. else
  243. {
  244. for (int i = 2; i < args.size(); ++i)
  245. zipModule (targetFolder, args[i].resolveAsFile());
  246. }
  247. }
  248. //==============================================================================
  249. struct CleanupOptions
  250. {
  251. bool removeTabs;
  252. bool fixDividerComments;
  253. };
  254. static void cleanWhitespace (const File& file, CleanupOptions options)
  255. {
  256. auto content = file.loadFileAsString();
  257. auto isProjucerTemplateFile = [file, content]
  258. {
  259. return file.getFullPathName().contains ("Templates")
  260. && content.contains ("%""%") && content.contains ("//[");
  261. }();
  262. if (isProjucerTemplateFile)
  263. return;
  264. StringArray lines;
  265. lines.addLines (content);
  266. bool anyTabsRemoved = false;
  267. for (int i = 0; i < lines.size(); ++i)
  268. {
  269. String& line = lines.getReference (i);
  270. if (options.removeTabs && line.containsChar ('\t'))
  271. {
  272. anyTabsRemoved = true;
  273. for (;;)
  274. {
  275. const int tabPos = line.indexOfChar ('\t');
  276. if (tabPos < 0)
  277. break;
  278. const int spacesPerTab = 4;
  279. const int spacesNeeded = spacesPerTab - (tabPos % spacesPerTab);
  280. line = line.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  281. }
  282. }
  283. if (options.fixDividerComments)
  284. {
  285. auto afterIndent = line.trim();
  286. if (afterIndent.startsWith ("//") && afterIndent.length() > 20)
  287. {
  288. afterIndent = afterIndent.substring (2);
  289. if (afterIndent.containsOnly ("=")
  290. || afterIndent.containsOnly ("/")
  291. || afterIndent.containsOnly ("-"))
  292. {
  293. line = line.substring (0, line.indexOfChar ('/'))
  294. + "//" + String::repeatedString ("=", 78);
  295. }
  296. }
  297. }
  298. line = line.trimEnd();
  299. }
  300. if (options.removeTabs && ! anyTabsRemoved)
  301. return;
  302. auto newText = joinLinesIntoSourceFile (lines);
  303. if (newText != content && newText != content + getPreferredLineFeed())
  304. replaceFile (file, newText, options.removeTabs ? "Removing tabs in: "
  305. : "Cleaning file: ");
  306. }
  307. static void scanFilesForCleanup (const ArgumentList& args, CleanupOptions options)
  308. {
  309. args.checkMinNumArguments (2);
  310. for (auto it = args.arguments.begin() + 1; it < args.arguments.end(); ++it)
  311. {
  312. auto target = it->resolveAsFile();
  313. Array<File> files;
  314. if (target.isDirectory())
  315. files = findAllSourceFiles (target);
  316. else
  317. files.add (target);
  318. for (int i = 0; i < files.size(); ++i)
  319. cleanWhitespace (files.getReference (i), options);
  320. }
  321. }
  322. static void cleanWhitespace (const ArgumentList& args, bool replaceTabs)
  323. {
  324. CleanupOptions options = { replaceTabs, false };
  325. scanFilesForCleanup (args, options);
  326. }
  327. static void tidyDividerComments (const ArgumentList& args)
  328. {
  329. CleanupOptions options = { false, true };
  330. scanFilesForCleanup (args, options);
  331. }
  332. //==============================================================================
  333. static File findSimilarlyNamedHeader (const Array<File>& allFiles, const String& name, const File& sourceFile)
  334. {
  335. File result;
  336. for (auto& f : allFiles)
  337. {
  338. if (f.getFileName().equalsIgnoreCase (name) && f != sourceFile)
  339. {
  340. if (result.exists())
  341. return {}; // multiple possible results, so don't change it!
  342. result = f;
  343. }
  344. }
  345. return result;
  346. }
  347. static void fixIncludes (const File& file, const Array<File>& allFiles)
  348. {
  349. const String content (file.loadFileAsString());
  350. StringArray lines;
  351. lines.addLines (content);
  352. bool hasChanged = false;
  353. for (auto& line : lines)
  354. {
  355. if (line.trimStart().startsWith ("#include \""))
  356. {
  357. auto includedFile = line.fromFirstOccurrenceOf ("\"", true, false)
  358. .upToLastOccurrenceOf ("\"", true, false)
  359. .trim()
  360. .unquoted();
  361. auto target = file.getSiblingFile (includedFile);
  362. if (! target.exists())
  363. {
  364. auto header = findSimilarlyNamedHeader (allFiles, target.getFileName(), file);
  365. if (header.exists())
  366. {
  367. line = line.upToFirstOccurrenceOf ("#include \"", true, false)
  368. + header.getRelativePathFrom (file.getParentDirectory())
  369. .replaceCharacter ('\\', '/')
  370. + "\"";
  371. hasChanged = true;
  372. }
  373. }
  374. }
  375. }
  376. if (hasChanged)
  377. {
  378. auto newText = joinLinesIntoSourceFile (lines);
  379. if (newText != content && newText != content + getPreferredLineFeed())
  380. replaceFile (file, newText, "Fixing includes in: ");
  381. }
  382. }
  383. static void fixRelativeIncludePaths (const ArgumentList& args)
  384. {
  385. args.checkMinNumArguments (2);
  386. auto target = args[1].resolveAsExistingFolder();
  387. auto files = findAllSourceFiles (target);
  388. for (int i = 0; i < files.size(); ++i)
  389. fixIncludes (files.getReference(i), files);
  390. }
  391. //==============================================================================
  392. static String getStringConcatenationExpression (Random& rng, int start, int length)
  393. {
  394. jassert (length > 0);
  395. if (length == 1)
  396. return "s" + String (start);
  397. int breakPos = jlimit (1, length - 1, (length / 3) + rng.nextInt (jmax (1, length / 3)));
  398. return "(" + getStringConcatenationExpression (rng, start, breakPos)
  399. + " + " + getStringConcatenationExpression (rng, start + breakPos, length - breakPos) + ")";
  400. }
  401. static void generateObfuscatedStringCode (const ArgumentList& args)
  402. {
  403. args.checkMinNumArguments (2);
  404. auto originalText = args[1].text.unquoted();
  405. struct Section
  406. {
  407. String text;
  408. int position, index;
  409. void writeGenerator (MemoryOutputStream& out) const
  410. {
  411. String name ("s" + String (index));
  412. out << " String " << name << "; " << name;
  413. auto escapeIfSingleQuote = [] (const String& s) -> String
  414. {
  415. if (s == "\'")
  416. return "\\'";
  417. return s;
  418. };
  419. for (int i = 0; i < text.length(); ++i)
  420. out << " << '" << escapeIfSingleQuote (String::charToString (text[i])) << "'";
  421. out << ";" << preferredLineFeed;
  422. }
  423. };
  424. Array<Section> sections;
  425. String text = originalText;
  426. Random rng;
  427. while (text.isNotEmpty())
  428. {
  429. int pos = jmax (0, text.length() - (1 + rng.nextInt (6)));
  430. Section s = { text.substring (pos), pos, 0 };
  431. sections.insert (0, s);
  432. text = text.substring (0, pos);
  433. }
  434. for (int i = 0; i < sections.size(); ++i)
  435. sections.getReference(i).index = i;
  436. for (int i = 0; i < sections.size(); ++i)
  437. sections.swap (i, rng.nextInt (sections.size()));
  438. MemoryOutputStream out;
  439. out << "String createString()" << preferredLineFeed
  440. << "{" << preferredLineFeed;
  441. for (int i = 0; i < sections.size(); ++i)
  442. sections.getReference(i).writeGenerator (out);
  443. out << preferredLineFeed
  444. << " String result = " << getStringConcatenationExpression (rng, 0, sections.size()) << ";" << preferredLineFeed
  445. << preferredLineFeed
  446. << " jassert (result == " << originalText.quoted() << ");" << preferredLineFeed
  447. << " return result;" << preferredLineFeed
  448. << "}" << preferredLineFeed;
  449. std::cout << out.toString() << std::endl;
  450. }
  451. static void scanFoldersForTranslationFiles (const ArgumentList& args)
  452. {
  453. args.checkMinNumArguments (2);
  454. StringArray translations;
  455. for (auto it = args.arguments.begin() + 1; it != args.arguments.end(); ++it)
  456. {
  457. auto directoryToSearch = it->resolveAsExistingFolder();
  458. TranslationHelpers::scanFolderForTranslations (translations, directoryToSearch);
  459. }
  460. std::cout << TranslationHelpers::mungeStrings (translations) << std::endl;
  461. }
  462. static void createFinishedTranslationFile (const ArgumentList& args)
  463. {
  464. args.checkMinNumArguments (3);
  465. auto preTranslated = args[1].resolveAsExistingFile().loadFileAsString();
  466. auto postTranslated = args[2].resolveAsExistingFile().loadFileAsString();
  467. auto localisedContent = (args.size() > 3 ? args[3].resolveAsExistingFile().loadFileAsString() : String());
  468. auto localised = LocalisedStrings (localisedContent, false);
  469. using TH = TranslationHelpers;
  470. std::cout << TH::createFinishedTranslationFile (TH::withTrimmedEnds (TH::breakApart (preTranslated)),
  471. TH::withTrimmedEnds (TH::breakApart (postTranslated)),
  472. localised) << std::endl;
  473. }
  474. //==============================================================================
  475. static void encodeBinary (const ArgumentList& args)
  476. {
  477. args.checkMinNumArguments (3);
  478. auto source = args[1].resolveAsExistingFile();
  479. auto target = args[2].resolveAsExistingFile();
  480. MemoryOutputStream literal;
  481. size_t dataSize = 0;
  482. {
  483. MemoryBlock data;
  484. FileInputStream input (source);
  485. input.readIntoMemoryBlock (data);
  486. build_tools::writeDataAsCppLiteral (data, literal, true, true);
  487. dataSize = data.getSize();
  488. }
  489. auto variableName = build_tools::makeBinaryDataIdentifierName (source);
  490. MemoryOutputStream header, cpp;
  491. header << "// Auto-generated binary data by the Projucer" << preferredLineFeed
  492. << "// Source file: " << source.getRelativePathFrom (target.getParentDirectory()) << preferredLineFeed
  493. << preferredLineFeed;
  494. cpp << header.toString();
  495. if (target.hasFileExtension (headerFileExtensions))
  496. {
  497. header << "static constexpr unsigned char " << variableName << "[] =" << preferredLineFeed
  498. << literal.toString() << preferredLineFeed
  499. << preferredLineFeed;
  500. replaceFile (target, header.toString(), "Writing: ");
  501. }
  502. else if (target.hasFileExtension (cppFileExtensions))
  503. {
  504. header << "extern const char* " << variableName << ";" << preferredLineFeed
  505. << "const unsigned int " << variableName << "Size = " << (int) dataSize << ";" << preferredLineFeed
  506. << preferredLineFeed;
  507. cpp << CodeHelpers::createIncludeStatement (target.withFileExtension (".h").getFileName()) << preferredLineFeed
  508. << preferredLineFeed
  509. << "static constexpr unsigned char " << variableName << "_local[] =" << preferredLineFeed
  510. << literal.toString() << preferredLineFeed
  511. << preferredLineFeed
  512. << "const char* " << variableName << " = (const char*) " << variableName << "_local;" << preferredLineFeed;
  513. replaceFile (target, cpp.toString(), "Writing: ");
  514. replaceFile (target.withFileExtension (".h"), header.toString(), "Writing: ");
  515. }
  516. else
  517. {
  518. ConsoleApplication::fail ("You need to specify a .h or .cpp file as the target");
  519. }
  520. }
  521. //==============================================================================
  522. static bool isThisOS (const String& os)
  523. {
  524. auto targetOS = TargetOS::unknown;
  525. if (os == "osx") targetOS = TargetOS::osx;
  526. else if (os == "windows") targetOS = TargetOS::windows;
  527. else if (os == "linux") targetOS = TargetOS::linux;
  528. if (targetOS == TargetOS::unknown)
  529. ConsoleApplication::fail ("You need to specify a valid OS! Use osx, windows or linux");
  530. return targetOS == TargetOS::getThisOS();
  531. }
  532. static bool isValidPathIdentifier (const String& id, const String& os)
  533. {
  534. return id == "vstLegacyPath" || (id == "aaxPath" && os != "linux") || (id == "rtasPath" && os != "linux")
  535. || id == "androidSDKPath" || id == "androidNDKPath" || id == "defaultJuceModulePath" || id == "defaultUserModulePath";
  536. }
  537. static void setGlobalPath (const ArgumentList& args)
  538. {
  539. args.checkMinNumArguments (3);
  540. if (! isValidPathIdentifier (args[2].text, args[1].text))
  541. ConsoleApplication::fail ("Identifier " + args[2].text + " is not valid for the OS " + args[1].text);
  542. auto userAppData = File::getSpecialLocation (File::userApplicationDataDirectory);
  543. #if JUCE_MAC
  544. userAppData = userAppData.getChildFile ("Application Support");
  545. #endif
  546. auto settingsFile = userAppData.getChildFile ("Projucer").getChildFile ("Projucer.settings");
  547. auto xml = parseXML (settingsFile);
  548. if (xml == nullptr)
  549. ConsoleApplication::fail ("Settings file not valid!");
  550. auto settingsTree = ValueTree::fromXml (*xml);
  551. if (! settingsTree.isValid())
  552. ConsoleApplication::fail ("Settings file not valid!");
  553. ValueTree childToSet;
  554. if (isThisOS (args[1].text))
  555. {
  556. childToSet = settingsTree.getChildWithProperty (Ids::name, "PROJECT_DEFAULT_SETTINGS")
  557. .getOrCreateChildWithName ("PROJECT_DEFAULT_SETTINGS", nullptr);
  558. }
  559. else
  560. {
  561. childToSet = settingsTree.getChildWithProperty (Ids::name, "FALLBACK_PATHS")
  562. .getOrCreateChildWithName ("FALLBACK_PATHS", nullptr)
  563. .getOrCreateChildWithName (args[1].text + "Fallback", nullptr);
  564. }
  565. if (! childToSet.isValid())
  566. ConsoleApplication::fail ("Failed to set the requested setting!");
  567. childToSet.setProperty (args[2].text, args[3].resolveAsFile().getFullPathName(), nullptr);
  568. settingsFile.replaceWithText (settingsTree.toXmlString());
  569. }
  570. static void createProjectFromPIP (const ArgumentList& args)
  571. {
  572. args.checkMinNumArguments (3);
  573. auto pipFile = args[1].resolveAsFile();
  574. if (! pipFile.existsAsFile())
  575. ConsoleApplication::fail ("PIP file doesn't exist.");
  576. auto outputDir = args[2].resolveAsFile();
  577. if (! outputDir.exists())
  578. {
  579. auto res = outputDir.createDirectory();
  580. std::cout << "Creating directory " << outputDir.getFullPathName() << std::endl;
  581. }
  582. File juceModulesPath, userModulesPath;
  583. if (args.size() > 3)
  584. {
  585. juceModulesPath = args[3].resolveAsFile();
  586. if (! juceModulesPath.exists())
  587. ConsoleApplication::fail ("Specified JUCE modules directory doesn't exist.");
  588. if (args.size() == 5)
  589. {
  590. userModulesPath = args[4].resolveAsFile();
  591. if (! userModulesPath.exists())
  592. ConsoleApplication::fail ("Specified JUCE modules directory doesn't exist.");
  593. }
  594. }
  595. PIPGenerator generator (pipFile, outputDir, juceModulesPath, userModulesPath);
  596. auto createJucerFileResult = generator.createJucerFile();
  597. if (! createJucerFileResult)
  598. ConsoleApplication::fail (createJucerFileResult.getErrorMessage());
  599. auto createMainCppResult = generator.createMainCpp();
  600. if (! createMainCppResult)
  601. ConsoleApplication::fail (createMainCppResult.getErrorMessage());
  602. }
  603. //==============================================================================
  604. static void showHelp()
  605. {
  606. hideDockIcon();
  607. auto appName = JUCEApplication::getInstance()->getApplicationName();
  608. std::cout << appName << std::endl
  609. << std::endl
  610. << "Usage: " << std::endl
  611. << std::endl
  612. << " " << appName << " --resave project_file" << std::endl
  613. << " Resaves all files and resources in a project." << std::endl
  614. << std::endl
  615. << " " << appName << " --resave-resources project_file" << std::endl
  616. << " Resaves just the binary resources for a project." << std::endl
  617. << std::endl
  618. << " " << appName << " --get-version project_file" << std::endl
  619. << " Returns the version number of a project." << std::endl
  620. << std::endl
  621. << " " << appName << " --set-version version_number project_file" << std::endl
  622. << " Updates the version number in a project." << std::endl
  623. << std::endl
  624. << " " << appName << " --bump-version project_file" << std::endl
  625. << " Updates the minor version number in a project by 1." << std::endl
  626. << std::endl
  627. << " " << appName << " --git-tag-version project_file" << std::endl
  628. << " Invokes 'git tag' to attach the project's version number to the current git repository." << std::endl
  629. << std::endl
  630. << " " << appName << " --status project_file" << std::endl
  631. << " Displays information about a project." << std::endl
  632. << std::endl
  633. << " " << appName << " --buildmodule target_folder module_folder" << std::endl
  634. << " Zips a module into a downloadable file format." << std::endl
  635. << std::endl
  636. << " " << appName << " --buildallmodules target_folder module_folder" << std::endl
  637. << " Zips all modules in a given folder and creates an index for them." << std::endl
  638. << std::endl
  639. << " " << appName << " --trim-whitespace target_folder" << std::endl
  640. << " Scans the given folder for C/C++ source files (recursively), and trims any trailing whitespace from their lines, as well as normalising their line-endings to CR-LF." << std::endl
  641. << std::endl
  642. << " " << appName << " --remove-tabs target_folder" << std::endl
  643. << " Scans the given folder for C/C++ source files (recursively), and replaces any tab characters with 4 spaces." << std::endl
  644. << std::endl
  645. << " " << appName << " --tidy-divider-comments target_folder" << std::endl
  646. << " Scans the given folder for C/C++ source files (recursively), and normalises any juce-style comment division lines (i.e. any lines that look like //===== or //------- or /////////// will be replaced)." << std::endl
  647. << std::endl
  648. << " " << appName << " --fix-broken-include-paths target_folder" << std::endl
  649. << " Scans the given folder for C/C++ source files (recursively). Where a file contains an #include of one of the other filenames, it changes it to use the optimum relative path. Helpful for auto-fixing includes when re-arranging files and folders in a project." << std::endl
  650. << std::endl
  651. << " " << appName << " --obfuscated-string-code string_to_obfuscate" << std::endl
  652. << " Generates a C++ function which returns the given string, but in an obfuscated way." << std::endl
  653. << std::endl
  654. << " " << appName << " --encode-binary source_binary_file target_cpp_file" << std::endl
  655. << " Converts a binary file to a C++ file containing its contents as a block of data. Provide a .h file as the target if you want a single output file, or a .cpp file if you want a pair of .h/.cpp files." << std::endl
  656. << std::endl
  657. << " " << appName << " --trans target_folders..." << std::endl
  658. << " Scans each of the given folders (recursively) for any NEEDS_TRANS macros, and generates a translation file that can be used with Projucer's translation file builder" << std::endl
  659. << std::endl
  660. << " " << appName << " --trans-finish pre_translated_file post_translated_file optional_existing_translation_file" << std::endl
  661. << " Creates a completed translations mapping file, that can be used to initialise a LocalisedStrings object. This allows you to localise the strings in your project" << std::endl
  662. << std::endl
  663. << " " << appName << " --set-global-search-path os identifier_to_set new_path" << std::endl
  664. << " Sets the global path for a specified os and identifier. The os should be either osx, windows or linux and the identifiers can be any of the following: "
  665. << "defaultJuceModulePath, defaultUserModulePath, vstLegacyPath, aaxPath (not valid on linux), rtasPath (not valid on linux), androidSDKPath or androidNDKPath. " << std::endl
  666. << std::endl
  667. << " " << appName << " --create-project-from-pip path/to/PIP path/to/output path/to/JUCE/modules (optional) path/to/user/modules (optional)" << std::endl
  668. << " Generates a folder containing a JUCE project in the specified output path using the specified PIP file. Use the optional JUCE and user module paths to override "
  669. "the global module paths." << std::endl
  670. << std::endl
  671. << "Note that for any of the file-rewriting commands, add the option \"--lf\" if you want it to use LF linefeeds instead of CRLF" << std::endl
  672. << std::endl;
  673. }
  674. }
  675. //==============================================================================
  676. int performCommandLine (const ArgumentList& args)
  677. {
  678. return ConsoleApplication::invokeCatchingFailures ([&]() -> int
  679. {
  680. if (args.containsOption ("--lf"))
  681. preferredLineFeed = "\n";
  682. auto command = args[0];
  683. auto matchCommand = [&] (StringRef name) -> bool
  684. {
  685. return command == name || command.isLongOption (name);
  686. };
  687. if (matchCommand ("help")) { showHelp(); return 0; }
  688. if (matchCommand ("h")) { showHelp(); return 0; }
  689. if (matchCommand ("resave")) { resaveProject (args, false); return 0; }
  690. if (matchCommand ("resave-resources")) { resaveProject (args, true); return 0; }
  691. if (matchCommand ("get-version")) { getVersion (args); return 0; }
  692. if (matchCommand ("set-version")) { setVersion (args); return 0; }
  693. if (matchCommand ("bump-version")) { bumpVersion (args); return 0; }
  694. if (matchCommand ("git-tag-version")) { gitTag (args); return 0; }
  695. if (matchCommand ("buildmodule")) { buildModules (args, false); return 0; }
  696. if (matchCommand ("buildallmodules")) { buildModules (args, true); return 0; }
  697. if (matchCommand ("status")) { showStatus (args); return 0; }
  698. if (matchCommand ("trim-whitespace")) { cleanWhitespace (args, false); return 0; }
  699. if (matchCommand ("remove-tabs")) { cleanWhitespace (args, true); return 0; }
  700. if (matchCommand ("tidy-divider-comments")) { tidyDividerComments (args); return 0; }
  701. if (matchCommand ("fix-broken-include-paths")) { fixRelativeIncludePaths (args); return 0; }
  702. if (matchCommand ("obfuscated-string-code")) { generateObfuscatedStringCode (args); return 0; }
  703. if (matchCommand ("encode-binary")) { encodeBinary (args); return 0; }
  704. if (matchCommand ("trans")) { scanFoldersForTranslationFiles (args); return 0; }
  705. if (matchCommand ("trans-finish")) { createFinishedTranslationFile (args); return 0; }
  706. if (matchCommand ("set-global-search-path")) { setGlobalPath (args); return 0; }
  707. if (matchCommand ("create-project-from-pip")) { createProjectFromPIP (args); return 0; }
  708. if (command.isLongOption() || command.isShortOption())
  709. ConsoleApplication::fail ("Unrecognised command: " + command.text.quoted());
  710. return commandLineNotPerformed;
  711. });
  712. }