constatic
Version:
Constatic is a CLI for creating and managing modern TypeScript projects, providing an organized structure and features that streamline development.
74 lines (72 loc) • 1.8 kB
JavaScript
// src/cli/env.ts
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
class EnvManager {
filepath;
data = {};
get vars() {
return Object.entries(this.data).reduce((obj, [k, v]) => {
if (v !== undefined)
obj[k] = v;
return obj;
}, {});
}
constructor(path) {
this.filepath = path;
}
async load() {
try {
const content = await readFile(this.filepath, "utf-8");
const parsed = EnvManager.parse(content);
this.data = { ...parsed, ...this.data };
} catch {}
}
set(key, value) {
this.data[key] = value ?? "";
}
remove(key) {
delete this.data[key];
}
unset(key) {
if (this.data[key] !== undefined) {
this.data[key] = "";
}
}
update([key, _schema, value]) {
this.set(key, value);
}
async save() {
await mkdir(dirname(this.filepath), { recursive: true });
await this.load();
const content = this.stringify(this.data);
await writeFile(this.filepath, content, "utf-8");
}
async createExample(filePath) {
const exampleData = {};
for (const key of Object.keys(this.data)) {
exampleData[key] = "";
}
const content = this.stringify(exampleData);
await writeFile(filePath, content, "utf-8");
}
static parse(content) {
const lines = content.split(/\r?\n/);
const data = {};
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#"))
continue;
const [key, ...rest] = trimmed.split("=");
const value = rest.join("=");
data[key] = value || data[key];
}
return data;
}
stringify(data) {
return Object.entries(data).map(([key, value]) => `${key}=${value ?? ""}`).join(`
`);
}
}
export {
EnvManager
};