cmExtraSublimeTextGenerator.cxx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmExtraSublimeTextGenerator.h"
  4. #include "cmsys/RegularExpression.hxx"
  5. #include <set>
  6. #include <sstream>
  7. #include <string.h>
  8. #include <utility>
  9. #include "cmGeneratedFileStream.h"
  10. #include "cmGeneratorExpression.h"
  11. #include "cmGeneratorTarget.h"
  12. #include "cmGlobalGenerator.h"
  13. #include "cmLocalGenerator.h"
  14. #include "cmMakefile.h"
  15. #include "cmSourceFile.h"
  16. #include "cmStateTypes.h"
  17. #include "cmSystemTools.h"
  18. #include "cmake.h"
  19. /*
  20. Sublime Text 2 Generator
  21. Author: Morné Chamberlain
  22. This generator was initially based off of the CodeBlocks generator.
  23. Some useful URLs:
  24. Homepage:
  25. http://www.sublimetext.com/
  26. File format docs:
  27. http://www.sublimetext.com/docs/2/projects.html
  28. http://sublimetext.info/docs/en/reference/build_systems.html
  29. */
  30. cmExternalMakefileProjectGeneratorFactory*
  31. cmExtraSublimeTextGenerator::GetFactory()
  32. {
  33. static cmExternalMakefileProjectGeneratorSimpleFactory<
  34. cmExtraSublimeTextGenerator>
  35. factory("Sublime Text 2", "Generates Sublime Text 2 project files.");
  36. if (factory.GetSupportedGlobalGenerators().empty()) {
  37. #if defined(_WIN32)
  38. factory.AddSupportedGlobalGenerator("MinGW Makefiles");
  39. factory.AddSupportedGlobalGenerator("NMake Makefiles");
  40. // disable until somebody actually tests it:
  41. // factory.AddSupportedGlobalGenerator("MSYS Makefiles");
  42. #endif
  43. factory.AddSupportedGlobalGenerator("Ninja");
  44. factory.AddSupportedGlobalGenerator("Unix Makefiles");
  45. }
  46. return &factory;
  47. }
  48. cmExtraSublimeTextGenerator::cmExtraSublimeTextGenerator()
  49. : cmExternalMakefileProjectGenerator()
  50. {
  51. this->ExcludeBuildFolder = false;
  52. }
  53. void cmExtraSublimeTextGenerator::Generate()
  54. {
  55. this->ExcludeBuildFolder = this->GlobalGenerator->GlobalSettingIsOn(
  56. "CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE");
  57. this->EnvSettings = this->GlobalGenerator->GetSafeGlobalSetting(
  58. "CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS");
  59. // for each sub project in the project create a sublime text 2 project
  60. for (auto const& it : this->GlobalGenerator->GetProjectMap()) {
  61. // create a project file
  62. this->CreateProjectFile(it.second);
  63. }
  64. }
  65. void cmExtraSublimeTextGenerator::CreateProjectFile(
  66. const std::vector<cmLocalGenerator*>& lgs)
  67. {
  68. std::string outputDir = lgs[0]->GetCurrentBinaryDirectory();
  69. std::string projectName = lgs[0]->GetProjectName();
  70. const std::string filename =
  71. outputDir + "/" + projectName + ".sublime-project";
  72. this->CreateNewProjectFile(lgs, filename);
  73. }
  74. void cmExtraSublimeTextGenerator::CreateNewProjectFile(
  75. const std::vector<cmLocalGenerator*>& lgs, const std::string& filename)
  76. {
  77. const cmMakefile* mf = lgs[0]->GetMakefile();
  78. cmGeneratedFileStream fout(filename.c_str());
  79. if (!fout) {
  80. return;
  81. }
  82. const std::string& sourceRootRelativeToOutput = cmSystemTools::RelativePath(
  83. lgs[0]->GetBinaryDirectory(), lgs[0]->GetSourceDirectory());
  84. // Write the folder entries to the project file
  85. fout << "{\n";
  86. fout << "\t\"folders\":\n\t[\n\t";
  87. if (!sourceRootRelativeToOutput.empty()) {
  88. fout << "\t{\n\t\t\t\"path\": \"" << sourceRootRelativeToOutput << "\"";
  89. const std::string& outputRelativeToSourceRoot =
  90. cmSystemTools::RelativePath(lgs[0]->GetSourceDirectory(),
  91. lgs[0]->GetBinaryDirectory());
  92. if ((!outputRelativeToSourceRoot.empty()) &&
  93. ((outputRelativeToSourceRoot.length() < 3) ||
  94. (outputRelativeToSourceRoot.substr(0, 3) != "../"))) {
  95. if (this->ExcludeBuildFolder) {
  96. fout << ",\n\t\t\t\"folder_exclude_patterns\": [\""
  97. << outputRelativeToSourceRoot << "\"]";
  98. }
  99. }
  100. } else {
  101. fout << "\t{\n\t\t\t\"path\": \"./\"";
  102. }
  103. fout << "\n\t\t}";
  104. // End of the folders section
  105. fout << "\n\t]";
  106. // Write the beginning of the build systems section to the project file
  107. fout << ",\n\t\"build_systems\":\n\t[\n\t";
  108. // Set of include directories over all targets (sublime text/sublimeclang
  109. // doesn't currently support these settings per build system, only project
  110. // wide
  111. MapSourceFileFlags sourceFileFlags;
  112. AppendAllTargets(lgs, mf, fout, sourceFileFlags);
  113. // End of build_systems
  114. fout << "\n\t]";
  115. std::string systemName = mf->GetSafeDefinition("CMAKE_SYSTEM_NAME");
  116. std::vector<std::string> tokens;
  117. cmSystemTools::ExpandListArgument(this->EnvSettings, tokens);
  118. if (!this->EnvSettings.empty()) {
  119. fout << ",";
  120. fout << "\n\t\"env\":";
  121. fout << "\n\t{";
  122. fout << "\n\t\t" << systemName << ":";
  123. fout << "\n\t\t{";
  124. for (std::string const& t : tokens) {
  125. size_t const pos = t.find_first_of('=');
  126. if (pos != std::string::npos) {
  127. std::string varName = t.substr(0, pos);
  128. std::string varValue = t.substr(pos + 1);
  129. fout << "\n\t\t\t\"" << varName << "\":\"" << varValue << "\"";
  130. } else {
  131. std::ostringstream e;
  132. e << "Could not parse Env Vars specified in "
  133. "\"CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS\""
  134. << ", corrupted string " << t;
  135. mf->IssueMessage(cmake::FATAL_ERROR, e.str());
  136. }
  137. }
  138. fout << "\n\t\t}";
  139. fout << "\n\t}";
  140. }
  141. fout << "\n}";
  142. }
  143. void cmExtraSublimeTextGenerator::AppendAllTargets(
  144. const std::vector<cmLocalGenerator*>& lgs, const cmMakefile* mf,
  145. cmGeneratedFileStream& fout, MapSourceFileFlags& sourceFileFlags)
  146. {
  147. std::string make = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
  148. std::string compiler;
  149. if (!lgs.empty()) {
  150. this->AppendTarget(fout, "all", lgs[0], nullptr, make.c_str(), mf,
  151. compiler.c_str(), sourceFileFlags, true);
  152. this->AppendTarget(fout, "clean", lgs[0], nullptr, make.c_str(), mf,
  153. compiler.c_str(), sourceFileFlags, false);
  154. }
  155. // add all executable and library targets and some of the GLOBAL
  156. // and UTILITY targets
  157. for (cmLocalGenerator* lg : lgs) {
  158. cmMakefile* makefile = lg->GetMakefile();
  159. const std::vector<cmGeneratorTarget*>& targets = lg->GetGeneratorTargets();
  160. for (cmGeneratorTarget* target : targets) {
  161. std::string targetName = target->GetName();
  162. switch (target->GetType()) {
  163. case cmStateEnums::GLOBAL_TARGET: {
  164. // Only add the global targets from CMAKE_BINARY_DIR,
  165. // not from the subdirs
  166. if (strcmp(lg->GetCurrentBinaryDirectory(),
  167. lg->GetBinaryDirectory()) == 0) {
  168. this->AppendTarget(fout, targetName, lg, nullptr, make.c_str(),
  169. makefile, compiler.c_str(), sourceFileFlags,
  170. false);
  171. }
  172. } break;
  173. case cmStateEnums::UTILITY:
  174. // Add all utility targets, except the Nightly/Continuous/
  175. // Experimental-"sub"targets as e.g. NightlyStart
  176. if (((targetName.find("Nightly") == 0) &&
  177. (targetName != "Nightly")) ||
  178. ((targetName.find("Continuous") == 0) &&
  179. (targetName != "Continuous")) ||
  180. ((targetName.find("Experimental") == 0) &&
  181. (targetName != "Experimental"))) {
  182. break;
  183. }
  184. this->AppendTarget(fout, targetName, lg, nullptr, make.c_str(),
  185. makefile, compiler.c_str(), sourceFileFlags,
  186. false);
  187. break;
  188. case cmStateEnums::EXECUTABLE:
  189. case cmStateEnums::STATIC_LIBRARY:
  190. case cmStateEnums::SHARED_LIBRARY:
  191. case cmStateEnums::MODULE_LIBRARY:
  192. case cmStateEnums::OBJECT_LIBRARY: {
  193. this->AppendTarget(fout, targetName, lg, target, make.c_str(),
  194. makefile, compiler.c_str(), sourceFileFlags,
  195. false);
  196. std::string fastTarget = targetName;
  197. fastTarget += "/fast";
  198. this->AppendTarget(fout, fastTarget, lg, target, make.c_str(),
  199. makefile, compiler.c_str(), sourceFileFlags,
  200. false);
  201. } break;
  202. default:
  203. break;
  204. }
  205. }
  206. }
  207. }
  208. void cmExtraSublimeTextGenerator::AppendTarget(
  209. cmGeneratedFileStream& fout, const std::string& targetName,
  210. cmLocalGenerator* lg, cmGeneratorTarget* target, const char* make,
  211. const cmMakefile* makefile, const char* /*compiler*/,
  212. MapSourceFileFlags& sourceFileFlags, bool firstTarget)
  213. {
  214. if (target != nullptr) {
  215. std::vector<cmSourceFile*> sourceFiles;
  216. target->GetSourceFiles(sourceFiles,
  217. makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
  218. for (cmSourceFile* sourceFile : sourceFiles) {
  219. MapSourceFileFlags::iterator sourceFileFlagsIter =
  220. sourceFileFlags.find(sourceFile->GetFullPath());
  221. if (sourceFileFlagsIter == sourceFileFlags.end()) {
  222. sourceFileFlagsIter =
  223. sourceFileFlags
  224. .insert(MapSourceFileFlags::value_type(sourceFile->GetFullPath(),
  225. std::vector<std::string>()))
  226. .first;
  227. }
  228. std::vector<std::string>& flags = sourceFileFlagsIter->second;
  229. std::string flagsString =
  230. this->ComputeFlagsForObject(sourceFile, lg, target);
  231. std::string definesString = this->ComputeDefines(sourceFile, lg, target);
  232. std::string includesString =
  233. this->ComputeIncludes(sourceFile, lg, target);
  234. flags.clear();
  235. cmsys::RegularExpression flagRegex;
  236. // Regular expression to extract compiler flags from a string
  237. // https://gist.github.com/3944250
  238. const char* regexString =
  239. "(^|[ ])-[DIOUWfgs][^= ]+(=\\\"[^\"]+\\\"|=[^\"][^ ]+)?";
  240. flagRegex.compile(regexString);
  241. std::string workString =
  242. flagsString + " " + definesString + " " + includesString;
  243. while (flagRegex.find(workString)) {
  244. std::string::size_type start = flagRegex.start();
  245. if (workString[start] == ' ') {
  246. start++;
  247. }
  248. flags.push_back(workString.substr(start, flagRegex.end() - start));
  249. if (flagRegex.end() < workString.size()) {
  250. workString = workString.substr(flagRegex.end());
  251. } else {
  252. workString.clear();
  253. }
  254. }
  255. }
  256. }
  257. // Ninja uses ninja.build files (look for a way to get the output file name
  258. // from cmMakefile or something)
  259. std::string makefileName;
  260. if (this->GlobalGenerator->GetName() == "Ninja") {
  261. makefileName = "build.ninja";
  262. } else {
  263. makefileName = "Makefile";
  264. }
  265. if (!firstTarget) {
  266. fout << ",\n\t";
  267. }
  268. fout << "\t{\n\t\t\t\"name\": \"" << lg->GetProjectName() << " - "
  269. << targetName << "\",\n";
  270. fout << "\t\t\t\"cmd\": ["
  271. << this->BuildMakeCommand(make, makefileName.c_str(), targetName)
  272. << "],\n";
  273. fout << "\t\t\t\"working_dir\": \"${project_path}\",\n";
  274. fout << "\t\t\t\"file_regex\": \""
  275. "^(..[^:]*)(?::|\\\\()([0-9]+)(?::|\\\\))(?:([0-9]+):)?\\\\s*(.*)"
  276. "\"\n";
  277. fout << "\t\t}";
  278. }
  279. // Create the command line for building the given target using the selected
  280. // make
  281. std::string cmExtraSublimeTextGenerator::BuildMakeCommand(
  282. const std::string& make, const char* makefile, const std::string& target)
  283. {
  284. std::string command = "\"";
  285. command += make + "\"";
  286. std::string generator = this->GlobalGenerator->GetName();
  287. if (generator == "NMake Makefiles") {
  288. std::string makefileName = cmSystemTools::ConvertToOutputPath(makefile);
  289. command += ", \"/NOLOGO\", \"/f\", \"";
  290. command += makefileName + "\"";
  291. command += ", \"" + target + "\"";
  292. } else if (generator == "Ninja") {
  293. std::string makefileName = cmSystemTools::ConvertToOutputPath(makefile);
  294. command += ", \"-f\", \"";
  295. command += makefileName + "\"";
  296. command += ", \"" + target + "\"";
  297. } else {
  298. std::string makefileName;
  299. if (generator == "MinGW Makefiles") {
  300. // no escaping of spaces in this case, see
  301. // https://gitlab.kitware.com/cmake/cmake/issues/10014
  302. makefileName = makefile;
  303. } else {
  304. makefileName = cmSystemTools::ConvertToOutputPath(makefile);
  305. }
  306. command += ", \"-f\", \"";
  307. command += makefileName + "\"";
  308. command += ", \"" + target + "\"";
  309. }
  310. return command;
  311. }
  312. // TODO: Most of the code is picked up from the Ninja generator, refactor it.
  313. std::string cmExtraSublimeTextGenerator::ComputeFlagsForObject(
  314. cmSourceFile* source, cmLocalGenerator* lg, cmGeneratorTarget* gtgt)
  315. {
  316. std::string flags;
  317. std::string language = source->GetLanguage();
  318. if (language.empty()) {
  319. language = "C";
  320. }
  321. std::string const& config =
  322. lg->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE");
  323. lg->GetTargetCompileFlags(gtgt, config, language, flags);
  324. // Add source file specific flags.
  325. cmGeneratorExpressionInterpreter genexInterpreter(lg, gtgt, config,
  326. gtgt->GetName(), language);
  327. const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  328. if (const char* cflags = source->GetProperty(COMPILE_FLAGS)) {
  329. lg->AppendFlags(flags, genexInterpreter.Evaluate(cflags, COMPILE_FLAGS));
  330. }
  331. const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  332. if (const char* coptions = source->GetProperty(COMPILE_OPTIONS)) {
  333. lg->AppendCompileOptions(
  334. flags, genexInterpreter.Evaluate(coptions, COMPILE_OPTIONS));
  335. }
  336. return flags;
  337. }
  338. // TODO: Refactor with
  339. // void cmMakefileTargetGenerator::WriteTargetLanguageFlags().
  340. std::string cmExtraSublimeTextGenerator::ComputeDefines(
  341. cmSourceFile* source, cmLocalGenerator* lg, cmGeneratorTarget* target)
  342. {
  343. std::set<std::string> defines;
  344. cmMakefile* makefile = lg->GetMakefile();
  345. const std::string& language = source->GetLanguage();
  346. const std::string& config = makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  347. cmGeneratorExpressionInterpreter genexInterpreter(
  348. lg, target, config, target->GetName(), language);
  349. // Add the export symbol definition for shared library objects.
  350. if (const char* exportMacro = target->GetExportMacro()) {
  351. lg->AppendDefines(defines, exportMacro);
  352. }
  353. // Add preprocessor definitions for this target and configuration.
  354. lg->AddCompileDefinitions(defines, target, config, language);
  355. const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  356. if (const char* compile_defs = source->GetProperty(COMPILE_DEFINITIONS)) {
  357. lg->AppendDefines(
  358. defines, genexInterpreter.Evaluate(compile_defs, COMPILE_DEFINITIONS));
  359. }
  360. std::string defPropName = "COMPILE_DEFINITIONS_";
  361. defPropName += cmSystemTools::UpperCase(config);
  362. if (const char* config_compile_defs = source->GetProperty(defPropName)) {
  363. lg->AppendDefines(defines, genexInterpreter.Evaluate(config_compile_defs,
  364. COMPILE_DEFINITIONS));
  365. }
  366. std::string definesString;
  367. lg->JoinDefines(defines, definesString, language);
  368. return definesString;
  369. }
  370. std::string cmExtraSublimeTextGenerator::ComputeIncludes(
  371. cmSourceFile* source, cmLocalGenerator* lg, cmGeneratorTarget* target)
  372. {
  373. std::vector<std::string> includes;
  374. cmMakefile* makefile = lg->GetMakefile();
  375. const std::string& language = source->GetLanguage();
  376. const std::string& config = makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
  377. cmGeneratorExpressionInterpreter genexInterpreter(
  378. lg, target, config, target->GetName(), language);
  379. // Add include directories for this source file
  380. const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  381. if (const char* cincludes = source->GetProperty(INCLUDE_DIRECTORIES)) {
  382. lg->AppendIncludeDirectories(
  383. includes, genexInterpreter.Evaluate(cincludes, INCLUDE_DIRECTORIES),
  384. *source);
  385. }
  386. // Add include directory flags.
  387. lg->GetIncludeDirectories(includes, target, language, config);
  388. std::string includesString =
  389. lg->GetIncludeFlags(includes, target, language, true, false, config);
  390. return includesString;
  391. }
  392. bool cmExtraSublimeTextGenerator::Open(const std::string& bindir,
  393. const std::string& projectName,
  394. bool dryRun)
  395. {
  396. const char* sublExecutable =
  397. this->GlobalGenerator->GetCMakeInstance()->GetCacheDefinition(
  398. "CMAKE_SUBLIMETEXT_EXECUTABLE");
  399. if (!sublExecutable) {
  400. return false;
  401. }
  402. if (cmSystemTools::IsNOTFOUND(sublExecutable)) {
  403. return false;
  404. }
  405. std::string filename = bindir + "/" + projectName + ".sublime-project";
  406. if (dryRun) {
  407. return cmSystemTools::FileExists(filename, true);
  408. }
  409. return cmSystemTools::RunSingleCommand(
  410. { sublExecutable, "--project", filename });
  411. }