1
1

params.cpp 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #include <fstream>
  2. #include <iostream>
  3. #include <sstream>
  4. #include <curses.h>
  5. #include <unistd.h>
  6. #include "params.hh"
  7. Params::Params(int ac, char **av) :progName(*av), params(std::list<std::string>(ac -1))
  8. {
  9. bool written = false;
  10. std::stringstream *input = nullptr;
  11. ignoreUnicode = false;
  12. colorMode = isatty(1);
  13. while (*(++av))
  14. {
  15. std::string tmp(*av);
  16. if (!input)
  17. {
  18. if (tmp == "-f")
  19. {
  20. tmp = *(++av);
  21. if (!*av)
  22. throw std::runtime_error("Invalid use of -f without argument");
  23. std::ifstream *in = new std::ifstream(tmp);
  24. if (!in->is_open())
  25. {
  26. delete in;
  27. throw std::runtime_error("Cannot open " +tmp +" for reading");
  28. }
  29. this->input = in;
  30. }
  31. else if (tmp == "--")
  32. {
  33. input = new std::stringstream();
  34. }
  35. else if (tmp == "--ascii")
  36. ignoreUnicode = true;
  37. else if (tmp == "--color")
  38. colorMode = true;
  39. else if (tmp.find("--color=") == 0)
  40. {
  41. std::string mode = (*av) + 8;
  42. if (mode == "always")
  43. colorMode = true;
  44. else if (mode == "never")
  45. colorMode = false;
  46. else if (mode == "auto")
  47. colorMode = isatty(1);
  48. else
  49. throw std::runtime_error("Invalid option for --color: " +mode);
  50. }
  51. else
  52. throw std::runtime_error("Invalid argument: " +tmp);
  53. }
  54. else
  55. {
  56. if (written)
  57. input->write(" ", sizeof(char));
  58. else
  59. written = true;
  60. input->write(tmp.c_str(), sizeof(char) * tmp.size());
  61. }
  62. }
  63. if (!this->input)
  64. this->input = input;
  65. }
  66. Params::~Params()
  67. {
  68. if (input)
  69. delete input;
  70. }
  71. std::basic_istream<char> &Params::getInput() const
  72. {
  73. if (input != nullptr)
  74. return *input;
  75. return std::cin;
  76. }
  77. void Params::usage(const std::string &progName) noexcept
  78. {
  79. std::cout << "Usage: " << progName << " [OPTIONS] [--] INPUT" << std::endl;
  80. std::cout << "\t\t-f filename\tread input from (filename) instead of stdin" << std::endl;
  81. std::cout << "\t\t--ascii\tignore unicode values" << std::endl;
  82. std::cout << "\t\t--color[=MODE]\tColorize output, MODE can be always (default when ommited), never or auto (default if --color is ommited)" << std::endl;
  83. }
  84. bool Params::isValid() const
  85. { return true; }
  86. bool Params::colorEnabled() const
  87. { return colorMode; }
  88. bool Params::isIgnoringUnicode() const
  89. { return ignoreUnicode; }
  90. const std::string &Params::getProgName() const
  91. { return progName; }