cmProcessTools.h 2.5 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. #pragma once
  4. #include "cmConfigure.h" // IWYU pragma: keep
  5. #include <cstring>
  6. #include <iosfwd>
  7. #include <string>
  8. #include "cmProcessOutput.h"
  9. /** \class cmProcessTools
  10. * \brief Helper classes for process output parsing
  11. *
  12. */
  13. class cmProcessTools
  14. {
  15. public:
  16. using Encoding = cmProcessOutput::Encoding;
  17. /** Abstract interface for process output parsers. */
  18. class OutputParser
  19. {
  20. public:
  21. /** Process the given output data from a tool. Processing may be
  22. done incrementally. Returns true if the parser is interested
  23. in any more data and false if it is done. */
  24. bool Process(const char* data, int length)
  25. {
  26. return this->ProcessChunk(data, length);
  27. }
  28. bool Process(const char* data)
  29. {
  30. return this->Process(data, static_cast<int>(strlen(data)));
  31. }
  32. virtual ~OutputParser() = default;
  33. protected:
  34. /** Implement in a subclass to process a chunk of data. It should
  35. return true only if it is interested in more data. */
  36. virtual bool ProcessChunk(const char* data, int length) = 0;
  37. };
  38. /** Process output parser that extracts one line at a time. */
  39. class LineParser : public OutputParser
  40. {
  41. public:
  42. /** Construct with line separation character and choose whether to
  43. ignore carriage returns. */
  44. LineParser(char sep = '\n', bool ignoreCR = true);
  45. /** Configure logging of lines as they are extracted. */
  46. void SetLog(std::ostream* log, const char* prefix);
  47. protected:
  48. std::ostream* Log = nullptr;
  49. const char* Prefix = nullptr;
  50. std::string Line;
  51. char Separator;
  52. char LineEnd = '\0';
  53. bool IgnoreCR;
  54. bool ProcessChunk(const char* data, int length) override;
  55. /** Implement in a subclass to process one line of input. It
  56. should return true only if it is interested in more data. */
  57. virtual bool ProcessLine() = 0;
  58. };
  59. /** Trivial line handler for simple logging. */
  60. class OutputLogger : public LineParser
  61. {
  62. public:
  63. OutputLogger(std::ostream& log, const char* prefix = nullptr)
  64. {
  65. this->SetLog(&log, prefix);
  66. }
  67. private:
  68. bool ProcessLine() override { return true; }
  69. };
  70. /** Run a process and send output to given parsers. */
  71. static void RunProcess(struct cmsysProcess_s* cp, OutputParser* out,
  72. OutputParser* err = nullptr,
  73. Encoding encoding = cmProcessOutput::Auto);
  74. };