ConfigFile.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, networkException <networkexception@serenityos.org>
  4. * Copyright (c) 2022, Sam Atkins <atkinssj@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #pragma once
  9. #include <AK/Forward.h>
  10. #include <AK/HashMap.h>
  11. #include <AK/RefCounted.h>
  12. #include <AK/RefPtr.h>
  13. #include <AK/String.h>
  14. #include <AK/Vector.h>
  15. #include <LibCore/Stream.h>
  16. namespace Core {
  17. class ConfigFile : public RefCounted<ConfigFile> {
  18. public:
  19. enum class AllowWriting {
  20. Yes,
  21. No,
  22. };
  23. static ErrorOr<NonnullRefPtr<ConfigFile>> open_for_lib(String const& lib_name, AllowWriting = AllowWriting::No);
  24. static ErrorOr<NonnullRefPtr<ConfigFile>> open_for_app(String const& app_name, AllowWriting = AllowWriting::No);
  25. static ErrorOr<NonnullRefPtr<ConfigFile>> open_for_system(String const& app_name, AllowWriting = AllowWriting::No);
  26. static ErrorOr<NonnullRefPtr<ConfigFile>> open(String const& filename, AllowWriting = AllowWriting::No);
  27. static ErrorOr<NonnullRefPtr<ConfigFile>> open(String const& filename, int fd);
  28. ~ConfigFile();
  29. bool has_group(String const&) const;
  30. bool has_key(String const& group, String const& key) const;
  31. Vector<String> groups() const;
  32. Vector<String> keys(String const& group) const;
  33. size_t num_groups() const { return m_groups.size(); }
  34. String read_entry(String const& group, String const& key, String const& default_value = String()) const;
  35. int read_num_entry(String const& group, String const& key, int default_value = 0) const;
  36. bool read_bool_entry(String const& group, String const& key, bool default_value = false) const;
  37. void write_entry(String const& group, String const& key, String const& value);
  38. void write_num_entry(String const& group, String const& key, int value);
  39. void write_bool_entry(String const& group, String const& key, bool value);
  40. void dump() const;
  41. bool is_dirty() const { return m_dirty; }
  42. ErrorOr<void> sync();
  43. void add_group(String const& group);
  44. void remove_group(String const& group);
  45. void remove_entry(String const& group, String const& key);
  46. String const& filename() const { return m_filename; }
  47. private:
  48. ConfigFile(String const& filename, OwnPtr<Stream::BufferedFile> open_file);
  49. ErrorOr<void> reparse();
  50. String m_filename;
  51. OwnPtr<Stream::BufferedFile> m_file;
  52. HashMap<String, HashMap<String, String>> m_groups;
  53. bool m_dirty { false };
  54. };
  55. }