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

Keep template defined var order #1

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
73 changes: 40 additions & 33 deletions src/get-env-vars.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import mapFileToObject from './map-env-file-to-object';
import mapFileToKeyValueTuple, {
KeyValueTuple,
} from './map-env-file-to-key-value-tuple';

type Provider = (params: any) => Promise<Record<string, string>>;

interface IGetEnvVarsParams {
fileLocation: any;
fileLocation?: string;
config: any;
providers: any;
providers: Provider[];
}

const difference = (a: Array<any>, b: Array<any>) => {
Expand All @@ -14,45 +18,48 @@ const main = async ({
fileLocation,
config,
providers = [],
}: IGetEnvVarsParams) => {
const template =
typeof fileLocation === 'string'
? await mapFileToObject(fileLocation)
: Promise.resolve(fileLocation);
const templateKeys = Object.keys(template);

const data = await Promise.all(
providers.map((provider: any) =>
provider({ keys: templateKeys, options: config })
)
}: IGetEnvVarsParams): Promise<KeyValueTuple[]> => {
const template = fileLocation
? await mapFileToKeyValueTuple(fileLocation)
: undefined;
const filledTemplateEnvs = (template || []).filter(
([, value]) => value !== undefined
);

const providedEnvs = await Promise.all(
providers.map(provider => provider({ keys: templateKeys, options: config }))
);

if (data.find(entry => typeof entry !== 'object')) {
if (providedEnvs.find(env => typeof env !== 'object')) {
throw new Error('providers must return an object');
}

// clean template from undefined values
Object.keys(template).forEach(
key => template[key] === undefined && delete template[key]
);

// create an array of all data, including template values
let parts = [{}].concat(data.reverse()).concat(template);
const mergedProvidedEnvs = Object.assign({}, ...providedEnvs) as Record<
string,
string
>;

// merge values with latter elements taking precedence
const result = Object.assign({}, ...parts);
// merge template tuples with fetched envs but keep the template values when defined
const result = [
...filledTemplateEnvs,
...Object.entries(mergedProvidedEnvs).filter(
([key]) => !filledTemplateEnvs?.find(([_key, value]) => _key === key)
),
];

// get a list of keys that have values
const filledKeys = Object.keys(result as Record<string, any>).filter(
(key: string) => result[key as any] !== undefined
);
const templateKeys = template?.map(([key]) => key);
if (templateKeys) {
const resultKeys = result.map(([key]) => key);

// get a list of keys missing from the results
const missingKeys = difference(templateKeys, filledKeys);
// get a list of keys missing from the results
const missingKeys = difference(templateKeys, resultKeys);

// throw error if not all of the keys have been filled with values
if (missingKeys.length) {
throw new Error(`Result is missing required values: ${missingKeys.join()}`);
// throw error if not all of the keys have been filled with values
if (missingKeys.length) {
throw new Error(
`Result is missing required values: ${missingKeys.join()}`
);
}
}

return result;
Expand Down
24 changes: 24 additions & 0 deletions src/map-env-file-to-key-value-tuple.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { readFile, existsSync } from 'fs';
import { promisify } from 'util';
import { isNotCommentLine, parseLineAsKeyValue } from './utils';

export type KeyValueTuple = [string, string | number];

const readFileAsync = promisify(readFile);

const main = async (fileLocation: any) => {
if (!existsSync(fileLocation)) {
throw new Error(`Source env file not found: ${fileLocation}`);
}

const data = await readFileAsync(fileLocation);

return data
.toString()
.split('\n')
.filter(isNotCommentLine)
.map(line => parseLineAsKeyValue(line))
.filter(([key]) => !!key) as KeyValueTuple[];
};

export default main;
6 changes: 3 additions & 3 deletions src/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ interface IRunnerParams {
params: {
isHeroku?: boolean;
isAws?: boolean;
envVars?: Array<string>;
envVars?: string;
region?: string;
addExport: boolean;
herokuToken?: string;
Expand Down Expand Up @@ -91,8 +91,8 @@ const main = async ({ params, version }: IRunnerParams) => {
fileLocation: envVars,
config: { region, herokuToken, herokuAppName },
providers,
}).then(data => {
Object.entries(data).map(print);
}).then(keyValueTuples => {
keyValueTuples.map(print);

console.log(`# Done! Generated on ${new Date(Date.now())}`);
});
Expand Down