mconfig-gen.cc 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <string>
  4. // This program generates an mconfig.h file. It is used in the build process.
  5. // Map of variable name to value. Variables are passed via command line and stored
  6. // in this map.
  7. std::unordered_map<std::string, std::string> vars;
  8. char to_hex_digit(int i)
  9. {
  10. if (i < 10) return i + '0';
  11. return i - 10 + 'A';
  12. }
  13. // turn a string into a C++-source string, eg:
  14. // he said "hello"
  15. // becomes
  16. // "he said \"hello\""
  17. static std::string stringify(std::string a)
  18. {
  19. std::string out = "\"";
  20. for (std::string::size_type i = 0; i < a.length(); i++) {
  21. char c = a[i];
  22. if (c == '\n') out += "\\n";
  23. else if (c == '\t') out += "\\t";
  24. else if (c == '\"') out += "\\\"";
  25. else if (c < 0x20) {
  26. out += "\\x" ;
  27. out += to_hex_digit((c & 0xF0) >> 4);
  28. out += to_hex_digit((c & 0x0F));
  29. }
  30. else out += c;
  31. }
  32. out += "\"";
  33. return out;
  34. }
  35. // parse a NAME=VALUE argument and store in the variable map
  36. void parse_arg(std::string arg)
  37. {
  38. auto idx = arg.find("=", 0, 1);
  39. if (idx == std::string::npos) {
  40. throw std::string("Couldn't parse argument: ") + arg;
  41. }
  42. auto name = arg.substr(0, idx);
  43. auto value = arg.substr(idx + 1);
  44. vars.emplace(std::move(name), std::move(value));
  45. }
  46. int main(int argc, char **argv)
  47. {
  48. for (int i = 1; i < argc; i++) {
  49. parse_arg(argv[i]);
  50. }
  51. using namespace std;
  52. cout << "// This file is auto-generated by mconfig-gen.cc." << endl;
  53. cout << "\n// Defines\n";
  54. if (vars.find("USE_UTMPX") != vars.end()) {
  55. cout << "#define USE_UTMPX " << vars["USE_UTMPX"] << "\n";
  56. }
  57. cout << "\n// Constants\n";
  58. cout << "constexpr static char SYSCONTROLSOCKET[] = " << stringify(vars["SYSCONTROLSOCKET"]) << ";\n";
  59. cout << "constexpr static char SBINDIR[] = " << stringify(vars["SBINDIR"]) << ";\n";
  60. return 0;
  61. }