cmProcessTools.h 2.5 KB

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