util.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // SuperTux - Scripting reference generator
  2. // Copyright (C) 2023 Vankata453
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. #include "util.hpp"
  17. #include <sstream>
  18. #include <fstream>
  19. bool param_matches(int argc, char** argv, int i,
  20. const std::string& rhs1, const std::string& rhs2,
  21. const std::string& rhs3) // Allow for 3 parameter formats
  22. {
  23. const std::string lhs = argv[i];
  24. return i + 1 < argc && (lhs == rhs1 || lhs == rhs2 || lhs == rhs3);
  25. }
  26. bool starts_with(const std::string& str, const std::string& prefix)
  27. {
  28. return str.rfind(prefix, 0) == 0;
  29. }
  30. void replace(std::string& str, const std::string& from,
  31. const std::string to, const std::string to_if_empty)
  32. {
  33. size_t start_pos = str.find(from);
  34. while (start_pos != std::string::npos)
  35. {
  36. str.replace(start_pos, from.length(), to.empty() ? to_if_empty : to);
  37. start_pos = str.find(from);
  38. }
  39. }
  40. void regex_replace(std::string& str, const std::regex from,
  41. const std::string& to)
  42. {
  43. str = std::regex_replace(str, from, to);
  44. }
  45. std::string read_file(const std::string& path)
  46. {
  47. std::ifstream stream(path);
  48. std::stringstream buffer;
  49. buffer << stream.rdbuf();
  50. stream.close();
  51. return buffer.str();
  52. }
  53. void write_file(const std::string& path, const std::string& content)
  54. {
  55. std::ofstream stream(path);
  56. stream << content;
  57. stream.close();
  58. }
  59. bool attr_equal(tinyxml2::XMLElement* el, const char* attr, const std::string& rhs)
  60. {
  61. const char* val = el->FindAttribute(attr)->Value();
  62. return val == NULL ? rhs.empty() : std::string(val) == rhs;
  63. }
  64. bool el_equal(tinyxml2::XMLElement* el, const char* child_el, const std::string& rhs)
  65. {
  66. const char* text = el->FirstChildElement(child_el)->GetText();
  67. return text == NULL ? rhs.empty() : std::string(text) == rhs;
  68. }