split-file.cpp 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. //===- split-file.cpp - Input splitting utility ---------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Split input into multipe parts separated by regex '^(.|//)--- ' and extract
  10. // the specified part.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "llvm/ADT/StringExtras.h"
  15. #include "llvm/ADT/StringRef.h"
  16. #include "llvm/Support/CommandLine.h"
  17. #include "llvm/Support/FileOutputBuffer.h"
  18. #include "llvm/Support/LineIterator.h"
  19. #include "llvm/Support/MemoryBuffer.h"
  20. #include "llvm/Support/Path.h"
  21. #include "llvm/Support/ToolOutputFile.h"
  22. #include "llvm/Support/WithColor.h"
  23. #include <string>
  24. #include <system_error>
  25. using namespace llvm;
  26. static cl::OptionCategory cat("split-file Options");
  27. static cl::opt<std::string> input(cl::Positional, cl::desc("filename"),
  28. cl::cat(cat));
  29. static cl::opt<std::string> output(cl::Positional, cl::desc("directory"),
  30. cl::value_desc("directory"), cl::cat(cat));
  31. static cl::opt<bool> noLeadingLines("no-leading-lines",
  32. cl::desc("Don't preserve line numbers"),
  33. cl::cat(cat));
  34. static StringRef toolName;
  35. static int errorCount;
  36. LLVM_ATTRIBUTE_NORETURN static void fatal(StringRef filename,
  37. const Twine &message) {
  38. if (filename.empty())
  39. WithColor::error(errs(), toolName) << message << '\n';
  40. else
  41. WithColor::error(errs(), toolName) << filename << ": " << message << '\n';
  42. exit(1);
  43. }
  44. static void error(StringRef filename, int64_t line, const Twine &message) {
  45. ++errorCount;
  46. errs() << filename << ':' << line << ": ";
  47. WithColor::error(errs()) << message << '\n';
  48. }
  49. namespace {
  50. struct Part {
  51. const char *begin = nullptr;
  52. const char *end = nullptr;
  53. int64_t leadingLines = 0;
  54. };
  55. } // namespace
  56. static int handle(MemoryBuffer &inputBuf, StringRef input) {
  57. DenseMap<StringRef, Part> partToBegin;
  58. StringRef lastPart, separator;
  59. for (line_iterator i(inputBuf, /*SkipBlanks=*/false, '\0'); !i.is_at_eof();) {
  60. const int64_t lineNo = i.line_number();
  61. const StringRef line = *i++;
  62. const size_t markerLen = line.startswith("//") ? 6 : 5;
  63. if (!(line.size() >= markerLen &&
  64. line.substr(markerLen - 4).startswith("--- ")))
  65. continue;
  66. separator = line.substr(0, markerLen);
  67. const StringRef partName = line.substr(markerLen);
  68. if (partName.empty()) {
  69. error(input, lineNo, "empty part name");
  70. continue;
  71. }
  72. if (isSpace(partName.front()) || isSpace(partName.back())) {
  73. error(input, lineNo, "part name cannot have leading or trailing space");
  74. continue;
  75. }
  76. auto res = partToBegin.try_emplace(partName);
  77. if (!res.second) {
  78. error(input, lineNo,
  79. "'" + separator + partName + "' occurs more than once");
  80. continue;
  81. }
  82. if (!lastPart.empty())
  83. partToBegin[lastPart].end = line.data();
  84. Part &cur = res.first->second;
  85. if (!i.is_at_eof())
  86. cur.begin = i->data();
  87. // If --no-leading-lines is not specified, numEmptyLines is 0. Append
  88. // newlines so that the extracted part preserves line numbers.
  89. cur.leadingLines = noLeadingLines ? 0 : i.line_number() - 1;
  90. lastPart = partName;
  91. }
  92. if (lastPart.empty())
  93. fatal(input, "no part separator was found");
  94. if (errorCount)
  95. return 1;
  96. partToBegin[lastPart].end = inputBuf.getBufferEnd();
  97. std::vector<std::unique_ptr<ToolOutputFile>> outputFiles;
  98. SmallString<256> partPath;
  99. for (auto &keyValue : partToBegin) {
  100. partPath.clear();
  101. sys::path::append(partPath, output, keyValue.first);
  102. std::error_code ec =
  103. sys::fs::create_directories(sys::path::parent_path(partPath));
  104. if (ec)
  105. fatal(input, ec.message());
  106. auto f = std::make_unique<ToolOutputFile>(partPath.str(), ec,
  107. llvm::sys::fs::OF_None);
  108. if (!f)
  109. fatal(input, ec.message());
  110. Part &part = keyValue.second;
  111. for (int64_t i = 0; i != part.leadingLines; ++i)
  112. (*f).os().write('\n');
  113. if (part.begin)
  114. (*f).os().write(part.begin, part.end - part.begin);
  115. outputFiles.push_back(std::move(f));
  116. }
  117. for (std::unique_ptr<ToolOutputFile> &outputFile : outputFiles)
  118. outputFile->keep();
  119. return 0;
  120. }
  121. int main(int argc, const char **argv) {
  122. toolName = sys::path::stem(argv[0]);
  123. cl::HideUnrelatedOptions({&cat});
  124. cl::ParseCommandLineOptions(
  125. argc, argv,
  126. "Split input into multiple parts separated by regex '^(.|//)--- ' and "
  127. "extract the part specified by '^(.|//)--- <part>'\n",
  128. nullptr,
  129. /*EnvVar=*/nullptr,
  130. /*LongOptionsUseDoubleDash=*/true);
  131. if (input.empty())
  132. fatal("", "input filename is not specified");
  133. if (output.empty())
  134. fatal("", "output directory is not specified");
  135. ErrorOr<std::unique_ptr<MemoryBuffer>> bufferOrErr =
  136. MemoryBuffer::getFileOrSTDIN(input);
  137. if (std::error_code ec = bufferOrErr.getError())
  138. fatal(input, ec.message());
  139. // Delete output if it is a file or an empty directory, so that we can create
  140. // a directory.
  141. sys::fs::file_status status;
  142. if (std::error_code ec = sys::fs::status(output, status))
  143. if (ec.value() != static_cast<int>(std::errc::no_such_file_or_directory))
  144. fatal(output, ec.message());
  145. if (status.type() != sys::fs::file_type::file_not_found &&
  146. status.type() != sys::fs::file_type::directory_file &&
  147. status.type() != sys::fs::file_type::regular_file)
  148. fatal(output, "output cannot be a special file");
  149. if (std::error_code ec = sys::fs::remove(output, /*IgnoreNonExisting=*/true))
  150. if (ec.value() != static_cast<int>(std::errc::directory_not_empty) &&
  151. ec.value() != static_cast<int>(std::errc::file_exists))
  152. fatal(output, ec.message());
  153. return handle(**bufferOrErr, input);
  154. }