| 70 | } // namespace |
| 71 | |
| 72 | bool ReadSettings(const fs::path& path, std::map<std::string, SettingsValue>& values, std::vector<std::string>& errors) |
| 73 | { |
| 74 | values.clear(); |
| 75 | errors.clear(); |
| 76 | |
| 77 | // Ok for file to not exist |
| 78 | if (!fs::exists(path)) return true; |
| 79 | |
| 80 | std::ifstream file; |
| 81 | file.open(path.std_path()); |
| 82 | if (!file.is_open()) { |
| 83 | errors.emplace_back(strprintf("%s. Please check permissions.", fs::PathToString(path))); |
| 84 | return false; |
| 85 | } |
| 86 | |
| 87 | SettingsValue in; |
| 88 | if (!in.read(std::string{std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>()})) { |
| 89 | errors.emplace_back(strprintf("Settings file %s does not contain valid JSON. This may be caused by a crash, power loss, full disk, or storage error, " |
| 90 | "and can be fixed by removing the file, which will reset settings to default values.", |
| 91 | fs::PathToString(path))); |
| 92 | return false; |
| 93 | } |
| 94 | |
| 95 | if (file.fail()) { |
| 96 | errors.emplace_back(strprintf("Failed reading settings file %s", fs::PathToString(path))); |
| 97 | return false; |
| 98 | } |
| 99 | file.close(); // Done with file descriptor. Release while copying data. |
| 100 | |
| 101 | if (!in.isObject()) { |
| 102 | errors.emplace_back(strprintf("Found non-object value %s in settings file %s", in.write(), fs::PathToString(path))); |
| 103 | return false; |
| 104 | } |
| 105 | |
| 106 | const std::vector<std::string>& in_keys = in.getKeys(); |
| 107 | const std::vector<SettingsValue>& in_values = in.getValues(); |
| 108 | for (size_t i = 0; i < in_keys.size(); ++i) { |
| 109 | auto inserted = values.emplace(in_keys[i], in_values[i]); |
| 110 | if (!inserted.second) { |
| 111 | errors.emplace_back(strprintf("Found duplicate key %s in settings file %s", in_keys[i], fs::PathToString(path))); |
| 112 | values.clear(); |
| 113 | break; |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | // Remove auto-generated warning comment from the accessible settings. |
| 118 | values.erase(SETTINGS_WARN_MSG_KEY); |
| 119 | |
| 120 | return errors.empty(); |
| 121 | } |
| 122 | |
| 123 | bool WriteSettings(const fs::path& path, |
| 124 | const std::map<std::string, SettingsValue>& values, |