-
Notifications
You must be signed in to change notification settings - Fork 4
/
mod.ts
49 lines (38 loc) · 1.12 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/* base code from https://github.com/rubiin/deno-env */
import { join } from "./imports/path.ts";
export interface Config {
path?: string;
encoding?: string;
}
type objectGen = {
[name: string]: string;
};
const defaultPath = join(Deno.cwd(), ".env");
const LINE_BREAK = /\r\n|\n|\r/;
const DECLARATION = /^\s*(\w+)\s*\=\s*(.*)?\s*$/;
function parse(source: string) {
const lines = source.split(LINE_BREAK);
return lines.reduce((vars: objectGen, line: string) => {
if (!DECLARATION.test(line)) return vars;
const [, name, value] = DECLARATION.exec(line)!;
if (!value) vars[name] = "";
else if (/^".*"$/.test(value))
vars[name] = value.replace(/^\"(.*)\"$/, "$1").replace(/\\n/g, "\n");
else vars[name] = value;
return vars;
}, {} as objectGen);
}
/**
* load .env file
*/
export function config({
path = defaultPath,
encoding = "utf-8",
}: Config = {}) {
const encoder = new TextDecoder(encoding);
const env = Deno.readFileSync(join(Deno.cwd(), path));
const entrie = encoder.decode(env);
for (const [key, value] of Object.entries(parse(entrie))) {
Deno.env.set(key, value);
}
}