config.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // config.h
  3. // pokemon-engine
  4. //
  5. // Created by Sam Jaffe on 12/22/18.
  6. // Copyright © 2018 Sam Jaffe. All rights reserved.
  7. //
  8. #pragma once
  9. #include <filesystem>
  10. #include <map>
  11. #include <memory>
  12. #include <string>
  13. #include <json/forwards.h>
  14. namespace engine::env {
  15. class Config {
  16. private:
  17. std::filesystem::path config_path_{""};
  18. std::filesystem::path resource_path_;
  19. std::map<std::string, std::string> properties_;
  20. public:
  21. /**
  22. * @brief Load this configuration from a JSON file on disk.
  23. * @param filepath The absolute path to a JSON config file.
  24. * @throws std::logic_error if any of the following:
  25. * - filepath is empty (i.e. Config cfg = Config("");)
  26. * - filepath is not an absolute UNIX-style path
  27. * - The file is readable and exists.
  28. */
  29. Config(std::filesystem::path const & filepath);
  30. ~Config();
  31. /**
  32. * @brief Obtain the absolute path to a resource, as determined by the
  33. * properties loaded into this object. For example,
  34. * @code std::string image_path = cfg.resource("sprites/nurse_joy.png");
  35. * @param rel_path The relative path to the resource file we are searching
  36. * for.
  37. * @return The absolute path to the file
  38. */
  39. std::filesystem::path resource(std::filesystem::path const & rel_path) const;
  40. /**
  41. * @brief Fetch a singluar property that exists within the object
  42. * @param name The property name being fetched
  43. * @param fallback A fallback value in case that the object is absent
  44. * @return The property being read in
  45. */
  46. std::string const & property(std::string const & name,
  47. std::string const & fallback) const;
  48. protected:
  49. /**
  50. * @brief Construct a config from a raw json blob. Primarily for testing.
  51. * @param json A json object containing certain properties
  52. */
  53. Config(Json::Value const & json,
  54. std::filesystem::path const & config_path = "/");
  55. private:
  56. std::filesystem::path fix(std::filesystem::path input) const;
  57. };
  58. }