ConfigFile.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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/LexicalPath.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibCore/ConfigFile.h>
  11. #include <LibCore/Directory.h>
  12. #include <LibCore/StandardPaths.h>
  13. #include <LibCore/System.h>
  14. #include <pwd.h>
  15. #include <sys/types.h>
  16. namespace Core {
  17. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open_for_lib(String const& lib_name, AllowWriting allow_altering)
  18. {
  19. String directory_name = String::formatted("{}/lib", StandardPaths::config_directory());
  20. auto directory = TRY(Directory::create(directory_name, Directory::CreateDirectories::Yes));
  21. auto path = String::formatted("{}/{}.ini", directory, lib_name);
  22. return ConfigFile::open(path, allow_altering);
  23. }
  24. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open_for_app(String const& app_name, AllowWriting allow_altering)
  25. {
  26. auto directory = TRY(Directory::create(StandardPaths::config_directory(), Directory::CreateDirectories::Yes));
  27. auto path = String::formatted("{}/{}.ini", directory, app_name);
  28. return ConfigFile::open(path, allow_altering);
  29. }
  30. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open_for_system(String const& app_name, AllowWriting allow_altering)
  31. {
  32. auto path = String::formatted("/etc/{}.ini", app_name);
  33. return ConfigFile::open(path, allow_altering);
  34. }
  35. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open(String const& filename, AllowWriting allow_altering)
  36. {
  37. auto maybe_file = Stream::File::open(filename, allow_altering == AllowWriting::Yes ? Stream::OpenMode::ReadWrite : Stream::OpenMode::Read);
  38. OwnPtr<Stream::BufferedFile> buffered_file;
  39. if (maybe_file.is_error()) {
  40. // If we attempted to open a read-only file that does not exist, we ignore the error, making it appear
  41. // the same as if we had opened an empty file. This behavior is a little weird, but is required by
  42. // user code, which does not check the config file exists before opening.
  43. if (!(allow_altering == AllowWriting::No && maybe_file.error().code() == ENOENT))
  44. return maybe_file.error();
  45. } else {
  46. buffered_file = TRY(Stream::BufferedFile::create(maybe_file.release_value()));
  47. }
  48. auto config_file = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) ConfigFile(filename, move(buffered_file))));
  49. TRY(config_file->reparse());
  50. return config_file;
  51. }
  52. ErrorOr<NonnullRefPtr<ConfigFile>> ConfigFile::open(String const& filename, int fd)
  53. {
  54. auto file = TRY(Stream::File::adopt_fd(fd, Stream::OpenMode::ReadWrite));
  55. auto buffered_file = TRY(Stream::BufferedFile::create(move(file)));
  56. auto config_file = TRY(adopt_nonnull_ref_or_enomem(new (nothrow) ConfigFile(filename, move(buffered_file))));
  57. TRY(config_file->reparse());
  58. return config_file;
  59. }
  60. ConfigFile::ConfigFile(String const& filename, OwnPtr<Stream::BufferedFile> open_file)
  61. : m_filename(filename)
  62. , m_file(move(open_file))
  63. {
  64. }
  65. ConfigFile::~ConfigFile()
  66. {
  67. MUST(sync());
  68. }
  69. ErrorOr<void> ConfigFile::reparse()
  70. {
  71. m_groups.clear();
  72. if (!m_file)
  73. return {};
  74. HashMap<String, String>* current_group = nullptr;
  75. auto buffer = TRY(ByteBuffer::create_uninitialized(4096));
  76. while (TRY(m_file->can_read_line())) {
  77. auto line = TRY(m_file->read_line(buffer));
  78. size_t i = 0;
  79. while (i < line.length() && (line[i] == ' ' || line[i] == '\t' || line[i] == '\n'))
  80. ++i;
  81. if (i >= line.length())
  82. continue;
  83. switch (line[i]) {
  84. case '#': // Comment, skip entire line.
  85. case ';': // -||-
  86. continue;
  87. case '[': { // Start of new group.
  88. StringBuilder builder;
  89. ++i; // Skip the '['
  90. while (i < line.length() && (line[i] != ']')) {
  91. builder.append(line[i]);
  92. ++i;
  93. }
  94. current_group = &m_groups.ensure(builder.to_string());
  95. break;
  96. }
  97. default: { // Start of key
  98. StringBuilder key_builder;
  99. StringBuilder value_builder;
  100. while (i < line.length() && (line[i] != '=')) {
  101. key_builder.append(line[i]);
  102. ++i;
  103. }
  104. ++i; // Skip the '='
  105. while (i < line.length() && (line[i] != '\n')) {
  106. value_builder.append(line[i]);
  107. ++i;
  108. }
  109. if (!current_group) {
  110. // We're not in a group yet, create one with the name ""...
  111. current_group = &m_groups.ensure("");
  112. }
  113. auto value_string = value_builder.to_string();
  114. current_group->set(key_builder.to_string(), value_string.trim_whitespace(TrimMode::Right));
  115. }
  116. }
  117. }
  118. return {};
  119. }
  120. String ConfigFile::read_entry(String const& group, String const& key, String const& default_value) const
  121. {
  122. if (!has_key(group, key)) {
  123. return default_value;
  124. }
  125. auto it = m_groups.find(group);
  126. auto jt = it->value.find(key);
  127. return jt->value;
  128. }
  129. int ConfigFile::read_num_entry(String const& group, String const& key, int default_value) const
  130. {
  131. if (!has_key(group, key)) {
  132. return default_value;
  133. }
  134. return read_entry(group, key).to_int().value_or(default_value);
  135. }
  136. bool ConfigFile::read_bool_entry(String const& group, String const& key, bool default_value) const
  137. {
  138. auto value = read_entry(group, key, default_value ? "true" : "false");
  139. return value == "1" || value.equals_ignoring_case("true"sv);
  140. }
  141. void ConfigFile::write_entry(String const& group, String const& key, String const& value)
  142. {
  143. m_groups.ensure(group).ensure(key) = value;
  144. m_dirty = true;
  145. }
  146. void ConfigFile::write_num_entry(String const& group, String const& key, int value)
  147. {
  148. write_entry(group, key, String::number(value));
  149. }
  150. void ConfigFile::write_bool_entry(String const& group, String const& key, bool value)
  151. {
  152. write_entry(group, key, value ? "true" : "false");
  153. }
  154. void ConfigFile::write_color_entry(String const& group, String const& key, Color value)
  155. {
  156. write_entry(group, key, String::formatted("{},{},{},{}", value.red(), value.green(), value.blue(), value.alpha()));
  157. }
  158. ErrorOr<void> ConfigFile::sync()
  159. {
  160. if (!m_dirty)
  161. return {};
  162. if (!m_file)
  163. return Error::from_errno(ENOENT);
  164. TRY(m_file->truncate(0));
  165. TRY(m_file->seek(0, Stream::SeekMode::SetPosition));
  166. for (auto& it : m_groups) {
  167. TRY(m_file->write(String::formatted("[{}]\n", it.key).bytes()));
  168. for (auto& jt : it.value)
  169. TRY(m_file->write(String::formatted("{}={}\n", jt.key, jt.value).bytes()));
  170. TRY(m_file->write("\n"sv.bytes()));
  171. }
  172. m_dirty = false;
  173. return {};
  174. }
  175. void ConfigFile::dump() const
  176. {
  177. for (auto& it : m_groups) {
  178. outln("[{}]", it.key);
  179. for (auto& jt : it.value)
  180. outln("{}={}", jt.key, jt.value);
  181. outln();
  182. }
  183. }
  184. Vector<String> ConfigFile::groups() const
  185. {
  186. return m_groups.keys();
  187. }
  188. Vector<String> ConfigFile::keys(String const& group) const
  189. {
  190. auto it = m_groups.find(group);
  191. if (it == m_groups.end())
  192. return {};
  193. return it->value.keys();
  194. }
  195. bool ConfigFile::has_key(String const& group, String const& key) const
  196. {
  197. auto it = m_groups.find(group);
  198. if (it == m_groups.end())
  199. return {};
  200. return it->value.contains(key);
  201. }
  202. bool ConfigFile::has_group(String const& group) const
  203. {
  204. return m_groups.contains(group);
  205. }
  206. void ConfigFile::remove_group(String const& group)
  207. {
  208. m_groups.remove(group);
  209. m_dirty = true;
  210. }
  211. void ConfigFile::remove_entry(String const& group, String const& key)
  212. {
  213. auto it = m_groups.find(group);
  214. if (it == m_groups.end())
  215. return;
  216. it->value.remove(key);
  217. m_dirty = true;
  218. }
  219. }