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