cmExtraSublimeTextGenerator.cxx 16 KB

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