Files
env-reader/src/env.cpp
2026-01-12 11:28:31 -06:00

49 lines
1003 B
C++

#include <filesystem>
#include <expected>
#include <fstream>
#include <string>
#include <map>
namespace fs = std::filesystem;
using std::unexpected;
using std::expected;
using std::string;
using std::map;
#include "env.hpp"
Env::Env() {
}
void Env::loadEnv(const string& cwd) {
string filename = ".env";
if (!cwd.empty()) {
filename = (fs::path(cwd) / ".env").string();
}
std::ifstream file(filename);
string line;
string::size_type pos;
while (std::getline(file, line)) {
pos = line.find_first_of("=");
string key = line.substr(0, pos);
string value = line.substr(pos + 1);
if (value.starts_with("'")) {
value = value.substr(1);
}
if (value.ends_with("'")) {
value.pop_back();
}
map_[key] = value;
}
}
expected<string, string> Env::get(const string& key) {
if (map_.contains(key)) {
return map_[key];
}
return unexpected("Key does not exist");
}