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.

909 lines
37KB

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