cmExtraSublimeTextGenerator.cxx 15.9 KB
Newer Older
1 2
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
3
#include "cmExtraSublimeTextGenerator.h"
Brad King's avatar
Brad King committed
4

5
#include <cstring>
6
#include <memory>
7 8 9 10
#include <set>
#include <sstream>
#include <utility>

11 12
#include "cmsys/RegularExpression.hxx"

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 "cmake.h"
25

26 27 28 29 30 31
/*
Sublime Text 2 Generator
Author: Morné Chamberlain
This generator was initially based off of the CodeBlocks generator.

Some useful URLs:
32 33 34 35 36 37 38 39
Homepage:
http://www.sublimetext.com/

File format docs:
http://www.sublimetext.com/docs/2/projects.html
http://sublimetext.info/docs/en/reference/build_systems.html
*/

40 41
cmExternalMakefileProjectGeneratorFactory*
cmExtraSublimeTextGenerator::GetFactory()
42
{
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
  static cmExternalMakefileProjectGeneratorSimpleFactory<
    cmExtraSublimeTextGenerator>
    factory("Sublime Text 2", "Generates Sublime Text 2 project files.");

  if (factory.GetSupportedGlobalGenerators().empty()) {
#if defined(_WIN32)
    factory.AddSupportedGlobalGenerator("MinGW Makefiles");
    factory.AddSupportedGlobalGenerator("NMake Makefiles");
// disable until somebody actually tests it:
// factory.AddSupportedGlobalGenerator("MSYS Makefiles");
#endif
    factory.AddSupportedGlobalGenerator("Ninja");
    factory.AddSupportedGlobalGenerator("Unix Makefiles");
  }

  return &factory;
59 60 61 62
}

cmExtraSublimeTextGenerator::cmExtraSublimeTextGenerator()
{
63
  this->ExcludeBuildFolder = false;
64 65 66 67
}

void cmExtraSublimeTextGenerator::Generate()
{
68 69
  this->ExcludeBuildFolder = this->GlobalGenerator->GlobalSettingIsOn(
    "CMAKE_SUBLIME_TEXT_2_EXCLUDE_BUILD_TREE");
70 71
  this->EnvSettings = this->GlobalGenerator->GetSafeGlobalSetting(
    "CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS");
72

73
  // for each sub project in the project create a sublime text 2 project
74
  for (auto const& it : this->GlobalGenerator->GetProjectMap()) {
75
    // create a project file
76
    this->CreateProjectFile(it.second);
77
  }
78 79 80
}

void cmExtraSublimeTextGenerator::CreateProjectFile(
81
  const std::vector<cmLocalGenerator*>& lgs)
82
{
83 84
  std::string outputDir = lgs[0]->GetCurrentBinaryDirectory();
  std::string projectName = lgs[0]->GetProjectName();
85

86
  const std::string filename =
87
    outputDir + "/" + projectName + ".sublime-project";
88 89 90 91

  this->CreateNewProjectFile(lgs, filename);
}

92 93
void cmExtraSublimeTextGenerator::CreateNewProjectFile(
  const std::vector<cmLocalGenerator*>& lgs, const std::string& filename)
94
{
95
  const cmMakefile* mf = lgs[0]->GetMakefile();
96

97
  cmGeneratedFileStream fout(filename);
98
  if (!fout) {
99
    return;
100
  }
101

102 103
  const std::string& sourceRootRelativeToOutput = cmSystemTools::RelativePath(
    lgs[0]->GetBinaryDirectory(), lgs[0]->GetSourceDirectory());
104
  // Write the folder entries to the project file
105 106
  fout << "{\n";
  fout << "\t\"folders\":\n\t[\n\t";
107 108 109 110 111 112
  if (!sourceRootRelativeToOutput.empty()) {
    fout << "\t{\n\t\t\t\"path\": \"" << sourceRootRelativeToOutput << "\"";
    const std::string& outputRelativeToSourceRoot =
      cmSystemTools::RelativePath(lgs[0]->GetSourceDirectory(),
                                  lgs[0]->GetBinaryDirectory());
    if ((!outputRelativeToSourceRoot.empty()) &&
113
        ((outputRelativeToSourceRoot.length() < 3) ||
114
         (outputRelativeToSourceRoot.substr(0, 3) != "../"))) {
115 116 117 118
      if (this->ExcludeBuildFolder) {
        fout << ",\n\t\t\t\"folder_exclude_patterns\": [\""
             << outputRelativeToSourceRoot << "\"]";
      }
119
    }
120 121 122
  } else {
    fout << "\t{\n\t\t\t\"path\": \"./\"";
  }
123
  fout << "\n\t\t}";
124
  // End of the folders section
125
  fout << "\n\t]";
126 127 128 129 130 131 132

  // Write the beginning of the build systems section to the project file
  fout << ",\n\t\"build_systems\":\n\t[\n\t";

  // Set of include directories over all targets (sublime text/sublimeclang
  // doesn't currently support these settings per build system, only project
  // wide
133 134
  MapSourceFileFlags sourceFileFlags;
  AppendAllTargets(lgs, mf, fout, sourceFileFlags);
135

136 137
  // End of build_systems
  fout << "\n\t]";
138
  std::string systemName = mf->GetSafeDefinition("CMAKE_SYSTEM_NAME");
139
  std::vector<std::string> tokens = cmExpandedList(this->EnvSettings);
140 141 142 143 144 145 146

  if (!this->EnvSettings.empty()) {
    fout << ",";
    fout << "\n\t\"env\":";
    fout << "\n\t{";
    fout << "\n\t\t" << systemName << ":";
    fout << "\n\t\t{";
147 148
    for (std::string const& t : tokens) {
      size_t const pos = t.find_first_of('=');
149 150

      if (pos != std::string::npos) {
151 152
        std::string varName = t.substr(0, pos);
        std::string varValue = t.substr(pos + 1);
153 154 155 156 157 158

        fout << "\n\t\t\t\"" << varName << "\":\"" << varValue << "\"";
      } else {
        std::ostringstream e;
        e << "Could not parse Env Vars specified in "
             "\"CMAKE_SUBLIME_TEXT_2_ENV_SETTINGS\""
159
          << ", corrupted string " << t;
160
        mf->IssueMessage(MessageType::FATAL_ERROR, e.str());
161 162 163 164 165 166
      }
    }
    fout << "\n\t\t}";
    fout << "\n\t}";
  }
  fout << "\n}";
167 168
}

169 170 171
void cmExtraSublimeTextGenerator::AppendAllTargets(
  const std::vector<cmLocalGenerator*>& lgs, const cmMakefile* mf,
  cmGeneratedFileStream& fout, MapSourceFileFlags& sourceFileFlags)
172
{
173
  const std::string& make = mf->GetRequiredDefinition("CMAKE_MAKE_PROGRAM");
174
  std::string compiler;
175
  if (!lgs.empty()) {
Daniel Pfeifer's avatar
Daniel Pfeifer committed
176
    this->AppendTarget(fout, "all", lgs[0], nullptr, make.c_str(), mf,
177
                       compiler.c_str(), sourceFileFlags, true);
Daniel Pfeifer's avatar
Daniel Pfeifer committed
178
    this->AppendTarget(fout, "clean", lgs[0], nullptr, make.c_str(), mf,
179 180
                       compiler.c_str(), sourceFileFlags, false);
  }
181 182 183

  // add all executable and library targets and some of the GLOBAL
  // and UTILITY targets
184 185
  for (cmLocalGenerator* lg : lgs) {
    cmMakefile* makefile = lg->GetMakefile();
186 187
    const auto& targets = lg->GetGeneratorTargets();
    for (const auto& target : targets) {
188 189
      std::string targetName = target->GetName();
      switch (target->GetType()) {
190
        case cmStateEnums::GLOBAL_TARGET: {
191 192
          // Only add the global targets from CMAKE_BINARY_DIR,
          // not from the subdirs
193
          if (lg->GetCurrentBinaryDirectory() == lg->GetBinaryDirectory()) {
194
            this->AppendTarget(fout, targetName, lg, nullptr, make.c_str(),
195 196
                               makefile, compiler.c_str(), sourceFileFlags,
                               false);
197
          }
198
        } break;
199
        case cmStateEnums::UTILITY:
200 201
          // Add all utility targets, except the Nightly/Continuous/
          // Experimental-"sub"targets as e.g. NightlyStart
202 203 204 205 206 207
          if (((targetName.find("Nightly") == 0) &&
               (targetName != "Nightly")) ||
              ((targetName.find("Continuous") == 0) &&
               (targetName != "Continuous")) ||
              ((targetName.find("Experimental") == 0) &&
               (targetName != "Experimental"))) {
208
            break;
209
          }
210

211
          this->AppendTarget(fout, targetName, lg, nullptr, make.c_str(),
Daniel Pfeifer's avatar
Daniel Pfeifer committed
212 213
                             makefile, compiler.c_str(), sourceFileFlags,
                             false);
214
          break;
215 216 217 218 219
        case cmStateEnums::EXECUTABLE:
        case cmStateEnums::STATIC_LIBRARY:
        case cmStateEnums::SHARED_LIBRARY:
        case cmStateEnums::MODULE_LIBRARY:
        case cmStateEnums::OBJECT_LIBRARY: {
220
          this->AppendTarget(fout, targetName, lg, target.get(), make.c_str(),
221 222
                             makefile, compiler.c_str(), sourceFileFlags,
                             false);
223
          std::string fastTarget = cmStrCat(targetName, "/fast");
224
          this->AppendTarget(fout, fastTarget, lg, target.get(), make.c_str(),
225 226 227
                             makefile, compiler.c_str(), sourceFileFlags,
                             false);
        } break;
228 229 230 231
        default:
          break;
      }
    }
232
  }
233 234
}

235 236 237
void cmExtraSublimeTextGenerator::AppendTarget(
  cmGeneratedFileStream& fout, const std::string& targetName,
  cmLocalGenerator* lg, cmGeneratorTarget* target, const char* make,
238
  const cmMakefile* makefile, const char* /*compiler*/,
239
  MapSourceFileFlags& sourceFileFlags, bool firstTarget)
240
{
241

Daniel Pfeifer's avatar
Daniel Pfeifer committed
242
  if (target != nullptr) {
243 244 245
    std::vector<cmSourceFile*> sourceFiles;
    target->GetSourceFiles(sourceFiles,
                           makefile->GetSafeDefinition("CMAKE_BUILD_TYPE"));
246
    for (cmSourceFile* sourceFile : sourceFiles) {
wahikihiki's avatar
wahikihiki committed
247
      auto sourceFileFlagsIter =
248
        sourceFileFlags.find(sourceFile->ResolveFullPath());
249 250 251
      if (sourceFileFlagsIter == sourceFileFlags.end()) {
        sourceFileFlagsIter =
          sourceFileFlags
252 253
            .insert(MapSourceFileFlags::value_type(
              sourceFile->ResolveFullPath(), std::vector<std::string>()))
254 255 256
            .first;
      }
      std::vector<std::string>& flags = sourceFileFlagsIter->second;
257 258 259
      std::string flagsString =
        this->ComputeFlagsForObject(sourceFile, lg, target);
      std::string definesString = this->ComputeDefines(sourceFile, lg, target);
260 261
      std::string includesString =
        this->ComputeIncludes(sourceFile, lg, target);
262 263 264 265 266
      flags.clear();
      cmsys::RegularExpression flagRegex;
      // Regular expression to extract compiler flags from a string
      // https://gist.github.com/3944250
      const char* regexString =
267
        R"((^|[ ])-[DIOUWfgs][^= ]+(=\"[^"]+\"|=[^"][^ ]+)?)";
268
      flagRegex.compile(regexString);
269
      std::string workString =
270
        cmStrCat(flagsString, " ", definesString, " ", includesString);
271 272 273 274
      while (flagRegex.find(workString)) {
        std::string::size_type start = flagRegex.start();
        if (workString[start] == ' ') {
          start++;
275
        }
276 277 278 279
        flags.push_back(workString.substr(start, flagRegex.end() - start));
        if (flagRegex.end() < workString.size()) {
          workString = workString.substr(flagRegex.end());
        } else {
280
          workString.clear();
281 282
        }
      }
283
    }
284
  }
285

286
  // Ninja uses ninja.build files (look for a way to get the output file name
287 288
  // from cmMakefile or something)
  std::string makefileName;
289 290 291 292 293 294
  if (this->GlobalGenerator->GetName() == "Ninja") {
    makefileName = "build.ninja";
  } else {
    makefileName = "Makefile";
  }
  if (!firstTarget) {
295
    fout << ",\n\t";
296 297 298 299 300 301
  }
  fout << "\t{\n\t\t\t\"name\": \"" << lg->GetProjectName() << " - "
       << targetName << "\",\n";
  fout << "\t\t\t\"cmd\": ["
       << this->BuildMakeCommand(make, makefileName.c_str(), targetName)
       << "],\n";
302
  fout << "\t\t\t\"working_dir\": \"${project_path}\",\n";
303 304 305
  fout << "\t\t\t\"file_regex\": \""
          "^(..[^:]*)(?::|\\\\()([0-9]+)(?::|\\\\))(?:([0-9]+):)?\\\\s*(.*)"
          "\"\n";
306 307 308 309 310 311
  fout << "\t\t}";
}

// Create the command line for building the given target using the selected
// make
std::string cmExtraSublimeTextGenerator::BuildMakeCommand(
312
  const std::string& make, const char* makefile, const std::string& target)
313
{
314
  std::string command = cmStrCat('"', make, '"');
315
  std::string generator = this->GlobalGenerator->GetName();
316
  if (generator == "NMake Makefiles") {
317
    std::string makefileName = cmSystemTools::ConvertToOutputPath(makefile);
318
    command += R"(, "/NOLOGO", "/f", ")";
319
    command += makefileName + "\"";
320
    command += ", \"" + target + "\"";
321
  } else if (generator == "Ninja") {
322
    std::string makefileName = cmSystemTools::ConvertToOutputPath(makefile);
323
    command += R"(, "-f", ")";
324
    command += makefileName + "\"";
325
    command += ", \"" + target + "\"";
326
  } else {
327
    std::string makefileName;
328 329
    if (generator == "MinGW Makefiles") {
      // no escaping of spaces in this case, see
330
      // https://gitlab.kitware.com/cmake/cmake/issues/10014
331 332 333 334
      makefileName = makefile;
    } else {
      makefileName = cmSystemTools::ConvertToOutputPath(makefile);
    }
335
    command += R"(, "-f", ")";
336
    command += makefileName + "\"";
337
    command += ", \"" + target + "\"";
338
  }
339 340
  return command;
}
341 342

// TODO: Most of the code is picked up from the Ninja generator, refactor it.
343 344
std::string cmExtraSublimeTextGenerator::ComputeFlagsForObject(
  cmSourceFile* source, cmLocalGenerator* lg, cmGeneratorTarget* gtgt)
345 346
{
  std::string flags;
347
  std::string language = source->GetOrDetermineLanguage();
348 349 350
  if (language.empty()) {
    language = "C";
  }
351 352
  std::string const& config =
    lg->GetMakefile()->GetSafeDefinition("CMAKE_BUILD_TYPE");
353

354
  lg->GetTargetCompileFlags(gtgt, config, language, flags);
355 356

  // Add source file specific flags.
357 358
  cmGeneratorExpressionInterpreter genexInterpreter(lg, config, gtgt,
                                                    language);
359

360 361 362
  const std::string COMPILE_FLAGS("COMPILE_FLAGS");
  if (const char* cflags = source->GetProperty(COMPILE_FLAGS)) {
    lg->AppendFlags(flags, genexInterpreter.Evaluate(cflags, COMPILE_FLAGS));
363
  }
364

365 366 367 368 369 370
  const std::string COMPILE_OPTIONS("COMPILE_OPTIONS");
  if (const char* coptions = source->GetProperty(COMPILE_OPTIONS)) {
    lg->AppendCompileOptions(
      flags, genexInterpreter.Evaluate(coptions, COMPILE_OPTIONS));
  }

371 372 373 374 375
  return flags;
}

// TODO: Refactor with
// void cmMakefileTargetGenerator::WriteTargetLanguageFlags().
376 377
std::string cmExtraSublimeTextGenerator::ComputeDefines(
  cmSourceFile* source, cmLocalGenerator* lg, cmGeneratorTarget* target)
378 379 380

{
  std::set<std::string> defines;
381
  cmMakefile* makefile = lg->GetMakefile();
382
  const std::string& language = source->GetOrDetermineLanguage();
383
  const std::string& config = makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
384 385
  cmGeneratorExpressionInterpreter genexInterpreter(lg, config, target,
                                                    language);
386 387

  // Add preprocessor definitions for this target and configuration.
388
  lg->GetTargetDefines(target, config, language, defines);
389 390 391 392
  const std::string COMPILE_DEFINITIONS("COMPILE_DEFINITIONS");
  if (const char* compile_defs = source->GetProperty(COMPILE_DEFINITIONS)) {
    lg->AppendDefines(
      defines, genexInterpreter.Evaluate(compile_defs, COMPILE_DEFINITIONS));
393 394
  }

395 396
  std::string defPropName =
    cmStrCat("COMPILE_DEFINITIONS_", cmSystemTools::UpperCase(config));
397
  if (const char* config_compile_defs = source->GetProperty(defPropName)) {
398 399 400
    lg->AppendDefines(
      defines,
      genexInterpreter.Evaluate(config_compile_defs, COMPILE_DEFINITIONS));
401 402 403 404 405 406 407
  }

  std::string definesString;
  lg->JoinDefines(defines, definesString, language);

  return definesString;
}
408

409 410 411 412 413 414
std::string cmExtraSublimeTextGenerator::ComputeIncludes(
  cmSourceFile* source, cmLocalGenerator* lg, cmGeneratorTarget* target)

{
  std::vector<std::string> includes;
  cmMakefile* makefile = lg->GetMakefile();
415
  const std::string& language = source->GetOrDetermineLanguage();
416
  const std::string& config = makefile->GetSafeDefinition("CMAKE_BUILD_TYPE");
417 418
  cmGeneratorExpressionInterpreter genexInterpreter(lg, config, target,
                                                    language);
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436

  // Add include directories for this source file
  const std::string INCLUDE_DIRECTORIES("INCLUDE_DIRECTORIES");
  if (const char* cincludes = source->GetProperty(INCLUDE_DIRECTORIES)) {
    lg->AppendIncludeDirectories(
      includes, genexInterpreter.Evaluate(cincludes, INCLUDE_DIRECTORIES),
      *source);
  }

  // Add include directory flags.
  lg->GetIncludeDirectories(includes, target, language, config);

  std::string includesString =
    lg->GetIncludeFlags(includes, target, language, true, false, config);

  return includesString;
}

437 438 439 440 441 442 443 444 445 446
bool cmExtraSublimeTextGenerator::Open(const std::string& bindir,
                                       const std::string& projectName,
                                       bool dryRun)
{
  const char* sublExecutable =
    this->GlobalGenerator->GetCMakeInstance()->GetCacheDefinition(
      "CMAKE_SUBLIMETEXT_EXECUTABLE");
  if (!sublExecutable) {
    return false;
  }
447
  if (cmIsNOTFOUND(sublExecutable)) {
448 449 450 451 452 453 454 455 456 457 458
    return false;
  }

  std::string filename = bindir + "/" + projectName + ".sublime-project";
  if (dryRun) {
    return cmSystemTools::FileExists(filename, true);
  }

  return cmSystemTools::RunSingleCommand(
    { sublExecutable, "--project", filename });
}