Add support for config file.

This commit is contained in:
tastytea 2021-05-20 09:05:39 +02:00
parent e5a36c010b
commit f95389d76c
Signed by: tastytea
GPG Key ID: CFC39497F1B26E07
2 changed files with 49 additions and 0 deletions

View File

@ -23,7 +23,10 @@
#include <boost/program_options/parsers.hpp>
#include <boost/program_options/variables_map.hpp>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
namespace epubgrep
{
@ -53,6 +56,11 @@ po::variables_map parse_options(int argc, char *argv[])
// clang-format on
po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
std::ifstream configfile(get_config_path());
po::store(po::parse_config_file(configfile, desc, true), vm);
configfile.close();
po::notify(vm);
if (vm.count("help") != 0)
@ -75,4 +83,34 @@ po::variables_map parse_options(int argc, char *argv[])
return vm;
}
std::string get_config_path()
{
auto get_env = [](std::string const &name)
{
const char *env = std::getenv(name.c_str());
if (env != nullptr)
{
return env;
}
return "";
};
std::string path{get_env("XDG_CONFIG_HOME")};
if (path.empty())
{
path = get_env("HOME");
if (!path.empty())
{
path += "/.config";
}
}
if (!path.empty())
{
path += "/";
}
return path += "epubgrep.conf";
}
} // namespace epubgrep

View File

@ -19,6 +19,8 @@
#include <boost/program_options/variables_map.hpp>
#include <string>
namespace epubgrep
{
@ -27,6 +29,15 @@ namespace po = boost::program_options;
//! Parse options and return them.
po::variables_map parse_options(int argc, char *argv[]);
/*!
* @brief Returns the path of the config file.
*
* Tries these paths: ${XDG_CONFIG_HOME}/epubgrep.conf
* ${HOME}/.config/epubgrep.conf
* epubgrep.conf
*/
std::string get_config_path();
} // namespace epubgrep
#endif // EPUBGREP_OPTIONS_HPP