first commit

This commit is contained in:
2026-01-12 11:28:31 -06:00
commit 66463236cc
6 changed files with 156 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
app
libenv.a
.env

31
Makefile Normal file
View File

@@ -0,0 +1,31 @@
TARGET = app
CXX = g++ -std=c++23 -ggdb -Wall -Wextra -pedantic -O0
INC = -I./include
LIB_PATH =
LIBS =
HEADERS = include/env.hpp
SOURCES = src/env.cpp \
main.cpp
STATIC = libenv.a
all: $(TARGET)
$(TARGET): $(HEADERS) $(SOURCES)
@$(CXX) $(INC) $(LIB_PATH) $(SOURCES) -o $(TARGET) $(LIBS)
$(STATIC): include/env.hpp src/env.cpp
@g++ -std=c++23 -I./include -c src/env.cpp -o env.o
@ar rcs $(STATIC) env.o
.PHONY: clean run
clean:
@rm -rf $(TARGET)
@rm -rf $(STATIC)
run: $(TARGET)
-@./$(TARGET)
@rm -rf $(TARGET)
lib: $(STATIC)
@rm -rf env.o

35
README.md Normal file
View File

@@ -0,0 +1,35 @@
# Env Reader
This is a library to read .env files.
## Usage
- `make lib`
```cpp
#include <expected>
#include <string>
#include <print>
#include "env.hpp"
using std::unexpected;
using std::expected;
using std::println;
using std::string;
int main() {
Env env;
env.loadEnv("");
expected<string, string> result = env.get("FIRST");
if (!result.has_value()) {
println("{}", result.error());
return 1;
}
println("{}", result.value());
return 0;
}
```

15
include/env.hpp Normal file
View File

@@ -0,0 +1,15 @@
#pragma once
#include <expected>
#include <string>
#include <map>
class Env {
public:
Env();
void loadEnv(const std::string& cwd);
std::expected<std::string, std::string> get(const std::string& key);
private:
std::map<std::string, std::string> map_;
};

24
main.cpp Normal file
View File

@@ -0,0 +1,24 @@
#include <expected>
#include <string>
#include <print>
#include "env.hpp"
using std::unexpected;
using std::expected;
using std::println;
using std::string;
int main() {
Env env;
env.loadEnv("");
expected<string, string> result = env.get("FIRST");
if (!result.has_value()) {
println("{}", result.error());
return 1;
}
println("{}", result.value());
return 0;
}

48
src/env.cpp Normal file
View File

@@ -0,0 +1,48 @@
#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");
}