cmExtraSublimeTextGenerator.cxx 16 KB

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