cmProcessTools.cxx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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 "cmProcessTools.h"
  4. #include "cmProcessOutput.h"
  5. #include "cmsys/Process.h"
  6. #include <ostream>
  7. void cmProcessTools::RunProcess(struct cmsysProcess_s* cp, OutputParser* out,
  8. OutputParser* err, Encoding encoding)
  9. {
  10. cmsysProcess_Execute(cp);
  11. char* data = nullptr;
  12. int length = 0;
  13. int p;
  14. cmProcessOutput processOutput(encoding);
  15. std::string strdata;
  16. while ((out || err) &&
  17. (p = cmsysProcess_WaitForData(cp, &data, &length, nullptr), p)) {
  18. if (out && p == cmsysProcess_Pipe_STDOUT) {
  19. processOutput.DecodeText(data, length, strdata, 1);
  20. if (!out->Process(strdata.c_str(), int(strdata.size()))) {
  21. out = nullptr;
  22. }
  23. } else if (err && p == cmsysProcess_Pipe_STDERR) {
  24. processOutput.DecodeText(data, length, strdata, 2);
  25. if (!err->Process(strdata.c_str(), int(strdata.size()))) {
  26. err = nullptr;
  27. }
  28. }
  29. }
  30. if (out) {
  31. processOutput.DecodeText(std::string(), strdata, 1);
  32. if (!strdata.empty()) {
  33. out->Process(strdata.c_str(), int(strdata.size()));
  34. }
  35. }
  36. if (err) {
  37. processOutput.DecodeText(std::string(), strdata, 2);
  38. if (!strdata.empty()) {
  39. err->Process(strdata.c_str(), int(strdata.size()));
  40. }
  41. }
  42. cmsysProcess_WaitForExit(cp, nullptr);
  43. }
  44. cmProcessTools::LineParser::LineParser(char sep, bool ignoreCR)
  45. : Log(nullptr)
  46. , Prefix(nullptr)
  47. , Separator(sep)
  48. , LineEnd('\0')
  49. , IgnoreCR(ignoreCR)
  50. {
  51. }
  52. void cmProcessTools::LineParser::SetLog(std::ostream* log, const char* prefix)
  53. {
  54. this->Log = log;
  55. this->Prefix = prefix ? prefix : "";
  56. }
  57. bool cmProcessTools::LineParser::ProcessChunk(const char* first, int length)
  58. {
  59. const char* last = first + length;
  60. for (const char* c = first; c != last; ++c) {
  61. if (*c == this->Separator || *c == '\0') {
  62. this->LineEnd = *c;
  63. // Log this line.
  64. if (this->Log && this->Prefix) {
  65. *this->Log << this->Prefix << this->Line << "\n";
  66. }
  67. // Hand this line to the subclass implementation.
  68. if (!this->ProcessLine()) {
  69. this->Line.clear();
  70. return false;
  71. }
  72. this->Line.clear();
  73. } else if (*c != '\r' || !this->IgnoreCR) {
  74. // Append this character to the line under construction.
  75. this->Line.append(1, *c);
  76. }
  77. }
  78. return true;
  79. }