ConfigFile.cpp 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Jakob-Niklas See <git@nwex.de>
  4. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/StringBuilder.h>
  9. #include <LibCore/ConfigFile.h>
  10. #include <LibCore/File.h>
  11. #include <LibCore/StandardPaths.h>
  12. #include <pwd.h>
  13. namespace Core {
  14. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open_for_lib(String const& lib_name, AllowWriting allow_altering)
  15. {
  16. String directory = StandardPaths::config_directory();
  17. auto path = String::formatted("{}/lib/{}.ini", directory, lib_name);
  18. return ConfigFile::open(path, allow_altering);
  19. }
  20. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open_for_app(String const& app_name, AllowWriting allow_altering)
  21. {
  22. String directory = StandardPaths::config_directory();
  23. auto path = String::formatted("{}/{}.ini", directory, app_name);
  24. return ConfigFile::open(path, allow_altering);
  25. }
  26. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open_for_system(String const& app_name, AllowWriting allow_altering)
  27. {
  28. auto path = String::formatted("/etc/{}.ini", app_name);
  29. return ConfigFile::open(path, allow_altering);
  30. }
  31. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open(String const& filename, AllowWriting allow_altering)
  32. {
  33. auto file = File::construct(filename);
  34. if (!file->open(allow_altering == AllowWriting::Yes ? OpenMode::ReadWrite : OpenMode::ReadOnly)) {
  35. // Failure to open a read-only file is OK, and behaves as if the file was empty.
  36. if (allow_altering == AllowWriting::Yes)
  37. return Error::from_string_literal("Unable to open config file");
  38. }
  39. return adopt_nonnull_ref_or_enomem(new (nothrow) ConfigFile(filename, move(file)));
  40. }
  41. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open(String const& filename, int fd)
  42. {
  43. auto file = File::construct(filename);
  44. if (!file->open(fd, OpenMode::ReadWrite, File::ShouldCloseFileDescriptor::Yes))
  45. return Error::from_string_literal("Unable to open config file");
  46. return adopt_nonnull_ref_or_enomem(new (nothrow) ConfigFile(filename, move(file)));
  47. }
  48. ConfigFile::ConfigFile(String const&, NonnullRefPtr<File> open_file)
  49. : m_file(move(open_file))
  50. {
  51. reparse();
  52. }
  53. ConfigFile::~ConfigFile()
  54. {
  55. MUST(sync());
  56. }
  57. void ConfigFile::reparse()
  58. {
  59. m_groups.clear();
  60. HashMap<String, String>* current_group = nullptr;
  61. while (m_file->can_read_line()) {
  62. auto line = m_file->read_line();
  63. if (line.is_null()) {
  64. m_groups.clear();
  65. return;
  66. }
  67. size_t i = 0;
  68. while (i < line.length() && (line[i] == ' ' || line[i] == '\t' || line[i] == '\n'))
  69. ++i;
  70. // EOL
  71. if (i >= line.length())
  72. continue;
  73. switch (line[i]) {
  74. case '#': // Comment, skip entire line.
  75. case ';': // -||-
  76. continue;
  77. case '[': { // Start of new group.
  78. StringBuilder builder;
  79. ++i; // Skip the '['
  80. while (i < line.length() && (line[i] != ']')) {
  81. builder.append(line[i]);
  82. ++i;
  83. }
  84. current_group = &m_groups.ensure(builder.to_string());
  85. break;
  86. }
  87. default: { // Start of key
  88. StringBuilder key_builder;
  89. StringBuilder value_builder;
  90. while (i < line.length() && (line[i] != '=')) {
  91. key_builder.append(line[i]);
  92. ++i;
  93. }
  94. ++i; // Skip the '='
  95. while (i < line.length() && (line[i] != '\n')) {
  96. value_builder.append(line[i]);
  97. ++i;
  98. }
  99. if (!current_group) {
  100. // We're not in a group yet, create one with the name ""...
  101. current_group = &m_groups.ensure("");
  102. }
  103. auto value_string = value_builder.to_string();
  104. current_group->set(key_builder.to_string(), value_string.trim_whitespace(TrimMode::Right));
  105. }
  106. }
  107. }
  108. }
  109. String ConfigFile::read_entry(String const& group, String const& key, String const& default_value) const
  110. {
  111. if (!has_key(group, key)) {
  112. return default_value;
  113. }
  114. auto it = m_groups.find(group);
  115. auto jt = it->value.find(key);
  116. return jt->value;
  117. }
  118. int ConfigFile::read_num_entry(String const& group, String const& key, int default_value) const
  119. {
  120. if (!has_key(group, key)) {
  121. return default_value;
  122. }
  123. return read_entry(group, key).to_int().value_or(default_value);
  124. }
  125. bool ConfigFile::read_bool_entry(String const& group, String const& key, bool default_value) const
  126. {
  127. auto value = read_entry(group, key, default_value ? "true" : "false");
  128. return value == "1" || value.equals_ignoring_case("true"sv);
  129. }
  130. void ConfigFile::write_entry(String const& group, String const& key, String const& value)
  131. {
  132. m_groups.ensure(group).ensure(key) = value;
  133. m_dirty = true;
  134. }
  135. void ConfigFile::write_num_entry(String const& group, String const& key, int value)
  136. {
  137. write_entry(group, key, String::number(value));
  138. }
  139. void ConfigFile::write_bool_entry(String const& group, String const& key, bool value)
  140. {
  141. write_entry(group, key, value ? "true" : "false");
  142. }
  143. void ConfigFile::write_color_entry(String const& group, String const& key, Color value)
  144. {
  145. write_entry(group, key, String::formatted("{},{},{},{}", value.red(), value.green(), value.blue(), value.alpha()));
  146. }
  147. ErrorOr<void> ConfigFile::sync()
  148. {
  149. if (!m_dirty)
  150. return {};
  151. m_file->truncate(0);
  152. m_file->seek(0);
  153. for (auto& it : m_groups) {
  154. m_file->write(String::formatted("[{}]\n", it.key));
  155. for (auto& jt : it.value)
  156. m_file->write(String::formatted("{}={}\n", jt.key, jt.value));
  157. m_file->write("\n");
  158. }
  159. m_dirty = false;
  160. return {};
  161. }
  162. void ConfigFile::dump() const
  163. {
  164. for (auto& it : m_groups) {
  165. outln("[{}]", it.key);
  166. for (auto& jt : it.value)
  167. outln("{}={}", jt.key, jt.value);
  168. outln();
  169. }
  170. }
  171. Vector<String> ConfigFile::groups() const
  172. {
  173. return m_groups.keys();
  174. }
  175. Vector<String> ConfigFile::keys(String const& group) const
  176. {
  177. auto it = m_groups.find(group);
  178. if (it == m_groups.end())
  179. return {};
  180. return it->value.keys();
  181. }
  182. bool ConfigFile::has_key(String const& group, String const& key) const
  183. {
  184. auto it = m_groups.find(group);
  185. if (it == m_groups.end())
  186. return {};
  187. return it->value.contains(key);
  188. }
  189. bool ConfigFile::has_group(String const& group) const
  190. {
  191. return m_groups.contains(group);
  192. }
  193. void ConfigFile::remove_group(String const& group)
  194. {
  195. m_groups.remove(group);
  196. m_dirty = true;
  197. }
  198. void ConfigFile::remove_entry(String const& group, String const& key)
  199. {
  200. auto it = m_groups.find(group);
  201. if (it == m_groups.end())
  202. return;
  203. it->value.remove(key);
  204. m_dirty = true;
  205. }
  206. }