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.

921 lines
37KB

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