printer.cpp raw

   1  // Copyright (c) The Bitcoin Core developers
   2  // Distributed under the MIT software license, see the accompanying
   3  // file COPYING or http://www.opensource.org/licenses/mit-license.php.
   4  
   5  #include <printer.h>
   6  
   7  #include <init.capnp.h>
   8  #include <init.capnp.proxy.h> // NOLINT(misc-include-cleaner) // IWYU pragma: keep
   9  
  10  #include <charconv>
  11  #include <cstring>
  12  #include <fstream>
  13  #include <iostream>
  14  #include <kj/async.h>
  15  #include <kj/common.h>
  16  #include <kj/memory.h>
  17  #include <memory>
  18  #include <mp/proxy-io.h>
  19  #include <stdexcept>
  20  #include <string>
  21  #include <system_error>
  22  
  23  class PrinterImpl : public Printer
  24  {
  25  public:
  26      void print(const std::string& message) override { std::cout << "mpprinter: " << message << std::endl; }
  27  };
  28  
  29  class InitImpl : public Init
  30  {
  31  public:
  32      std::unique_ptr<Printer> makePrinter() override { return std::make_unique<PrinterImpl>(); }
  33  };
  34  
  35  static void LogPrint(mp::LogMessage log_data)
  36  {
  37      if (log_data.level == mp::Log::Raise) throw std::runtime_error(log_data.message);
  38      std::ofstream("debug.log", std::ios_base::app) << log_data.message << std::endl;
  39  }
  40  
  41  int main(int argc, char** argv)
  42  {
  43      if (argc != 2) {
  44          std::cout << "Usage: mpprinter <fd>\n";
  45          return 1;
  46      }
  47      int fd;
  48      if (std::from_chars(argv[1], argv[1] + strlen(argv[1]), fd).ec != std::errc{}) {
  49          std::cerr << argv[1] << " is not a number or is larger than an int\n";
  50          return 1;
  51      }
  52      mp::EventLoop loop("mpprinter", LogPrint);
  53      std::unique_ptr<Init> init = std::make_unique<InitImpl>();
  54      mp::ServeStream<InitInterface>(loop, fd, *init);
  55      loop.loop();
  56      return 0;
  57  }
  58