This commit is contained in:
89
source/src/utils/envmanager.cpp
Normal file
89
source/src/utils/envmanager.cpp
Normal file
@ -0,0 +1,89 @@
|
||||
#include "envmanager.hpp"
|
||||
#include "utils/utils.hpp"
|
||||
#include <fstream>
|
||||
#include <sstream>
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <regex>
|
||||
#include <cstdlib> // For std::getenv
|
||||
|
||||
namespace dropshell {
|
||||
|
||||
envmanager::envmanager(std::string path) : m_path(path) {
|
||||
}
|
||||
|
||||
envmanager::~envmanager() {
|
||||
}
|
||||
|
||||
bool envmanager::load() {
|
||||
std::ifstream file(m_path);
|
||||
if (!file.is_open()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
m_variables.clear();
|
||||
std::string line;
|
||||
while (std::getline(file, line)) {
|
||||
line=trim(line);
|
||||
// Skip empty lines and comments
|
||||
if (line.empty() || line[0] == '#') {
|
||||
continue;
|
||||
}
|
||||
|
||||
size_t pos = line.find('=');
|
||||
if (pos != std::string::npos) {
|
||||
std::string key = line.substr(0, pos);
|
||||
std::string value = line.substr(pos + 1);
|
||||
|
||||
// trim whitespace from the key and value
|
||||
m_variables[dequote(trim(key))] = dequote(trim(value));
|
||||
}
|
||||
}
|
||||
file.close();
|
||||
return true;
|
||||
}
|
||||
|
||||
void envmanager::save() {
|
||||
std::ofstream file(m_path);
|
||||
if (!file.is_open()) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const auto& pair : m_variables) {
|
||||
file << pair.first << "=" << quote(pair.second) << std::endl;
|
||||
}
|
||||
file.close();
|
||||
}
|
||||
|
||||
std::string envmanager::get_variable(std::string key) const {
|
||||
key = dequote(trim(key));
|
||||
|
||||
// Use case-insensitive comparison to find the key
|
||||
for (const auto& pair : m_variables) {
|
||||
if (pair.first == key) {
|
||||
return pair.second;
|
||||
}
|
||||
}
|
||||
|
||||
return "";
|
||||
}
|
||||
|
||||
void envmanager::get_all_variables(std::map<std::string, std::string>& variables) const {
|
||||
variables = m_variables;
|
||||
}
|
||||
|
||||
void envmanager::add_variables(std::map<std::string, std::string> variables) {
|
||||
for (auto& pair : variables) {
|
||||
set_variable(pair.first, pair.second);
|
||||
}
|
||||
}
|
||||
|
||||
void envmanager::set_variable(std::string key, std::string value) {
|
||||
m_variables[dequote(trim(key))] = dequote(trim(value));
|
||||
}
|
||||
|
||||
void envmanager::clear_variables() {
|
||||
m_variables.clear();
|
||||
}
|
||||
|
||||
} // namespace dropshell
|
Reference in New Issue
Block a user