cmExtraSublimeTextGenerator.cxx 16 KB

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