Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for loading env values #23

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.unittest
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
TEST=test
19 changes: 19 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
"homepage": "https://github.com/AmericanAirlines/simple-env#readme",
"dependencies": {},
"devDependencies": {
"@types/dotenv-flow": "^3.1.0",
"@typescript-eslint/eslint-plugin": "^4.8.1",
"@typescript-eslint/parser": "^4.8.1",
"eslint": "^7.13.0",
Expand Down
56 changes: 55 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import { readFileSync, existsSync } from 'fs';
import { EOL } from 'os';
import { join } from 'path';
import { EnvVarSymbols, UndefinedEnvVars } from './types/EnvVars';
import { SymbolWithDescription } from './types/helpers';
import { InternalOptions, Options } from './types/Options';
import { EnvOptions, InternalOptions, Options } from './types/Options';

let _requiredEnvVars: SymbolWithDescription[] = [];
let _symbolizedEnvVars: Record<string, SymbolWithDescription>;
let _options: InternalOptions = {
required: {},
optional: {},
dotEnvOptions: {},
};

const createSymbol = (description: string): SymbolWithDescription => Symbol(description) as SymbolWithDescription;
Expand All @@ -33,6 +37,54 @@ function symbolizeVars<T>(input: Record<string, string>) {
);
}

function parseLine(line: string): Record<string, string> {
const delimiter = '=';
const lineRegex = /^\s*[a-zA-Z_][a-zA-Z0-9_]*\s*="?'?.*'?"?$/g;
let [key, val] = line.split(delimiter);

// Ignore comments, or lines which don't conform to acceptable patterns
if (key.startsWith('#') || key.startsWith('//') || !lineRegex.test(line)) {
return {};
}

key = key.trim();
val = val.trim();
// Get rid of wrapping double or single quotes
if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) {
val = val.substr(1, val.length - 2);
}

return { [key]: val };
}

function parseEnvFile(dotEnvOptions: EnvOptions = {}): Record<string, string> {
const envPath = dotEnvOptions.pathToEnv || process.cwd();
const envFilename = dotEnvOptions.envFileName || '.env';
const fullPath = join(envPath, envFilename);

if (!existsSync(fullPath)) {
return {};
}

const envFileContents = readFileSync(fullPath).toString();
let envVarPairs: Record<string, string> = {};

const lines = envFileContents.split(EOL);
lines.forEach((line: string) => {
envVarPairs = { ...envVarPairs, ...parseLine(line) };
});

// Toss everything into the environment
Object.entries(envVarPairs).forEach(([key, val]) => {
// Prefer env vars that have been set by the OS
if (!process.env[key]) {
process.env[key] = val;
}
});

return envVarPairs;
}

export default function setEnv<T extends UndefinedEnvVars, V extends UndefinedEnvVars>(
options: Options<T, V>,
): {
Expand All @@ -43,6 +95,8 @@ export default function setEnv<T extends UndefinedEnvVars, V extends UndefinedEn
...options,
};

parseEnvFile(_options.dotEnvOptions);

const symbolizedRequiredEnvVars = symbolizeVars<EnvVarSymbols<T>>(_options.required);
_requiredEnvVars = Object.values(symbolizedRequiredEnvVars);

Expand Down
6 changes: 6 additions & 0 deletions src/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,5 +99,11 @@ describe('simple-env', () => {
expect(Object.getOwnPropertyDescriptors(env)).not.toHaveProperty('something');
expect(Object.getOwnPropertyDescriptors(env)).toHaveProperty('somethingElse');
});

it('will read an env variable from a .env file into process.env', () => {
const env = setEnv({ required: { test: 'TEST' }, dotEnvOptions: { envFileName: '.env.unittest' } });

expect(process.env.TEST).toEqual(env.test);
});
});
});
6 changes: 6 additions & 0 deletions src/types/Options.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { DefaultEnvVars, UndefinedEnvVars } from './EnvVars';
import { RemoveKeys } from './helpers';

export interface EnvOptions {
pathToEnv?: string;
envFileName?: string;
}

export interface Options<Required extends UndefinedEnvVars = DefaultEnvVars, Optional extends UndefinedEnvVars = DefaultEnvVars> {
required?: Required;
optional?: RemoveKeys<Optional, keyof Required>;
dotEnvOptions?: EnvOptions;
}

export interface InternalOptions extends Required<Options> {
Expand Down