Files
LumberJack_TUI/env_reader/env.cpp
rapturate 42f50c9e9a 1) First draft of the TUI functionality
2) Added env_reader functions (env.hpp and env.cpp)
3) Program looks for a .env on startup and creates one based on user input if not found.
4) Refactored log_parsing and ip_to_geo to use the global env variables for parsing and ip lookup from the local .mmdb database
5) CMakeLists.txt is now cross platform functional
6) Added various cross platform checks for creating .env variables
2026-06-09 14:29:42 -04:00

84 lines
2.5 KiB
C++

/**
* @file env.cpp
* @author Lewis Price (lewis.e.price@outlook.com)
* @brief Implementation for environment utilities and cross-platform .env loader
* @version 1.0.0
* @date 2026-06-09
*
* @copyright Copyright (c) 2026
*
*/
#include "env.hpp"
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <filesystem>
/**
* @brief Helper utility to set environment variables across operating systems
*/
static int set_env_variable(const std::string& key, const std::string& value) {
#if defined(_WIN32)
return _putenv_s(key.c_str(), value.c_str());
#else
return setenv(key.c_str(), value.c_str(), 1);
#endif
}
bool check_for_env() {
const std::string env_path = ".env";
// Returns true only if .env exists on disk and is a file (not a directory)
return std::filesystem::exists(env_path) && std::filesystem::is_regular_file(env_path);
}
void make_env() {
const std::string env_path = ".env";
if (std::filesystem::exists(env_path)) {
return;
}
std::ofstream file(env_path);
if (!file.is_open()) {
std::cerr << "Error: Could not generate a default " << env_path << " configuration template file." << std::endl;
return;
}
// Write out the clean template configuration block
file << "# ParseLogCLI Global Environment Configuration\n";
file << "# Generated on 2026-06-09\n\n";
file << "# Path to the MaxMind GeoLite2 City Database binary\n";
file << "DB_PATH=data/GeoLite2-City.mmdb\n\n";
file << "# Absolute or relative path to the server access logs target file\n";
file << "LOG_PATH=test_logs/access.log.txt\n";
file.close();
}
void load_env_file(const std::string& env_path) {
std::ifstream file(env_path);
if (!file.is_open()) {
std::cerr << "Warning: Could not open " << env_path << " file." << std::endl;
return;
}
std::string line;
while (std::getline(file, line)) {
// Skip completely empty lines or comment configurations
if (line.empty() || line[0] == '#') continue;
std::size_t delimiter_pos = line.find('=');
if (delimiter_pos != std::string::npos) {
std::string key = line.substr(0, delimiter_pos);
std::string value = line.substr(delimiter_pos + 1);
// Clean up hidden trailing Windows carriage returns (\r) safely
if (!value.empty() && value.back() == '\r') {
value.pop_back();
}
// Expose the key-value pair globally to the active process lifecycle
set_env_variable(key, value);
}
}
}