Steve DiBenedetto | c07b3a2 | 2014-03-19 12:32:52 -0600 | [diff] [blame] | 1 | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ |
| 2 | /** |
| 3 | * Copyright (C) 2014 Named Data Networking Project |
| 4 | * See COPYING for copyright and distribution information. |
| 5 | */ |
| 6 | |
| 7 | #ifndef NDN_MANAGEMENT_CONFIG_FILE_HPP |
| 8 | #define NDN_MANAGEMENT_CONFIG_FILE_HPP |
| 9 | |
| 10 | #include "../common.hpp" |
| 11 | |
| 12 | #include <boost/property_tree/ptree.hpp> |
| 13 | #include <boost/filesystem.hpp> |
| 14 | |
| 15 | namespace ndn { |
| 16 | |
| 17 | class ConfigFile : noncopyable |
| 18 | { |
| 19 | public: |
| 20 | |
| 21 | class Error : public std::runtime_error |
| 22 | { |
| 23 | public: |
| 24 | Error(const std::string& what) |
| 25 | : std::runtime_error(what) |
| 26 | { |
| 27 | |
| 28 | } |
| 29 | }; |
| 30 | |
| 31 | typedef boost::property_tree::ptree Parsed; |
| 32 | |
| 33 | /** |
| 34 | * Locate, open, and parse a library configuration file. |
| 35 | * |
| 36 | * @throws ConfigFile::Error on parse error |
| 37 | */ |
| 38 | ConfigFile(); |
| 39 | |
| 40 | ~ConfigFile(); |
| 41 | |
| 42 | const boost::filesystem::path& |
| 43 | getPath() const; |
| 44 | |
| 45 | const Parsed& |
| 46 | getParsedConfiguration() const; |
| 47 | |
| 48 | private: |
| 49 | |
| 50 | bool |
| 51 | open(); |
| 52 | |
| 53 | void |
| 54 | close(); |
| 55 | |
| 56 | /** |
| 57 | * Parse a previously discovered and opened configuration file. |
| 58 | * For convenience this method will attempt to open the file |
| 59 | * if it has previously been located, but open() has not been called. |
| 60 | * |
| 61 | * @throws ConfigFile::Error on parse error |
| 62 | * @throws ConfigFile::Error on failure to open previously un-open configuration file |
| 63 | * @throws ConfigFile::Error if no configuration file was previously located |
| 64 | */ |
| 65 | const Parsed& |
| 66 | parse(); |
| 67 | |
| 68 | /** |
| 69 | * Looking for the configuration file in these well-known locations: |
| 70 | * |
| 71 | * 1. $HOME/.ndn/client.conf |
| 72 | * 2. @SYSCONFDIR@/ndn/client.conf |
| 73 | * 3. /etc/ndn/client.conf |
| 74 | * |
| 75 | * @return path to preferred configuration (according to above order) or empty path on failure |
| 76 | */ |
| 77 | |
| 78 | boost::filesystem::path |
| 79 | findConfigFile(); |
| 80 | |
| 81 | private: |
| 82 | boost::filesystem::path m_path; // absolute path to active configuration file (if any) |
| 83 | std::ifstream m_input; |
| 84 | Parsed m_config; |
| 85 | }; |
| 86 | |
| 87 | inline const boost::filesystem::path& |
| 88 | ConfigFile::getPath() const |
| 89 | { |
| 90 | return m_path; |
| 91 | } |
| 92 | |
| 93 | inline const ConfigFile::Parsed& |
| 94 | ConfigFile::getParsedConfiguration() const |
| 95 | { |
| 96 | return m_config; |
| 97 | } |
| 98 | |
| 99 | } // namespace ndn |
| 100 | |
| 101 | |
| 102 | #endif // NDN_MANAGEMENT_CONFIG_FILE_HPP |
| 103 | |