cmExtraSublimeTextGenerator.cxx 16 KB

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