From 744b36aefee654530158f06d682e9e330ffc06c9 Mon Sep 17 00:00:00 2001 From: ilotterytea Date: Sun, 21 Apr 2024 02:36:45 +0500 Subject: feat: .env config parser --- src/config.cpp | 45 +++++++++++++++++++++++++++++++++++++++++++++ src/config.hpp | 14 ++++++++++++++ src/main.cpp | 18 +++++++++++++++++- 3 files changed, 76 insertions(+), 1 deletion(-) create mode 100644 src/config.cpp create mode 100644 src/config.hpp (limited to 'src') diff --git a/src/config.cpp b/src/config.cpp new file mode 100644 index 0000000..2d1b876 --- /dev/null +++ b/src/config.cpp @@ -0,0 +1,45 @@ +#include "config.hpp" + +#include +#include +#include +#include +#include +#include + +namespace bot { + std::optional parse_configuration_from_file( + const std::string &file_path) { + std::ifstream ifs(file_path); + + if (!ifs.is_open()) { + std::cerr << "*** Failed to open the configuration file: " << file_path + << "!\n"; + return std::nullopt; + } + + Configuration cfg; + + std::string line; + while (std::getline(ifs, line, '\n')) { + std::istringstream iss(line); + std::string key; + std::string value; + + std::getline(iss, key, '='); + std::getline(iss, value); + + for (char &c : key) { + c = tolower(c); + } + + if (key == "bot_username") { + cfg.bot_username = value; + } else if (key == "bot_password") { + cfg.bot_password = value; + } + } + + return cfg; + } +} diff --git a/src/config.hpp b/src/config.hpp new file mode 100644 index 0000000..3c10d86 --- /dev/null +++ b/src/config.hpp @@ -0,0 +1,14 @@ +#pragma once + +#include +#include + +namespace bot { + struct Configuration { + std::string bot_username; + std::string bot_password; + }; + + std::optional parse_configuration_from_file( + const std::string &file_path); +} diff --git a/src/main.cpp b/src/main.cpp index b940d1d..129b074 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,11 +1,27 @@ #include +#include +#include "config.hpp" #include "irc/client.hpp" int main(int argc, char *argv[]) { std::cout << "hi world\n"; - bot::irc::Client client("", ""); + std::optional o_cfg = + bot::parse_configuration_from_file(".env"); + + if (!o_cfg.has_value()) { + return -1; + } + + bot::Configuration cfg = o_cfg.value(); + + if (cfg.bot_password.empty() || cfg.bot_username.empty()) { + std::cerr << "*** BOT_USERNAME and BOT_PASSWORD must be set!\n"; + return -1; + } + + bot::irc::Client client(cfg.bot_username, cfg.bot_password); client.run(); -- cgit v1.2.3