cmProcessTools.cxx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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))) {
  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. : Separator(sep)
  46. , IgnoreCR(ignoreCR)
  47. {
  48. }
  49. void cmProcessTools::LineParser::SetLog(std::ostream* log, const char* prefix)
  50. {
  51. this->Log = log;
  52. this->Prefix = prefix ? prefix : "";
  53. }
  54. bool cmProcessTools::LineParser::ProcessChunk(const char* first, int length)
  55. {
  56. const char* last = first + length;
  57. for (const char* c = first; c != last; ++c) {
  58. if (*c == this->Separator || *c == '\0') {
  59. this->LineEnd = *c;
  60. // Log this line.
  61. if (this->Log && this->Prefix) {
  62. *this->Log << this->Prefix << this->Line << "\n";
  63. }
  64. // Hand this line to the subclass implementation.
  65. if (!this->ProcessLine()) {
  66. this->Line.clear();
  67. return false;
  68. }
  69. this->Line.clear();
  70. } else if (*c != '\r' || !this->IgnoreCR) {
  71. // Append this character to the line under construction.
  72. this->Line.append(1, *c);
  73. }
  74. }
  75. return true;
  76. }