qenv/ts/index.ts

61 lines
2.2 KiB
TypeScript
Raw Normal View History

2016-06-19 18:08:34 +00:00
import * as plugins from "./qenv.plugins";
2016-06-20 08:45:43 +00:00
export class Qenv {
2016-06-20 05:06:15 +00:00
requiredEnvVars:string[];
availableEnvVars:string[];
missingEnvVars:string[];
2016-06-21 14:13:29 +00:00
constructor(basePathArg = process.cwd(),envYmlPathArg,failOnMissing = true){
2016-06-20 05:06:15 +00:00
this.requiredEnvVars = getRequiredEnvVars(basePathArg);
this.availableEnvVars = getAvailableEnvVars(this.requiredEnvVars,envYmlPathArg);
this.missingEnvVars = getMissingEnvVars(this.requiredEnvVars,this.availableEnvVars);
2016-06-21 14:13:29 +00:00
//handle missing variables
if (this.missingEnvVars.length > 0){
2016-06-21 14:25:03 +00:00
plugins.beautylog.info("Required Env Vars are:")
console.log(this.requiredEnvVars);
plugins.beautylog.error("However some Env variables could not be resolved:");
2016-06-21 14:13:29 +00:00
console.log(this.missingEnvVars);
if(failOnMissing){
plugins.beautylog.error("Exiting!")
process.exit(1);
}
2016-06-20 08:45:43 +00:00
}
2016-06-19 18:08:34 +00:00
}
};
2016-06-20 05:06:15 +00:00
let getRequiredEnvVars = (pathArg:string):string[] => {
2016-06-19 18:08:34 +00:00
let result:string[] = [];
let qenvFilePath = plugins.path.join(pathArg,"qenv.yml");
let qenvFile = plugins.smartfile.local.toObjectSync(qenvFilePath);
for(let keyArg in qenvFile.vars){
result.push(qenvFile.vars[keyArg]);
}
return result;
}
2016-06-20 05:06:15 +00:00
let getAvailableEnvVars = (requiredEnvVarsArg:string[],envYmlPathArg:string):string[] => {
2016-06-19 18:08:34 +00:00
let result = [];
2016-06-20 08:45:43 +00:00
envYmlPathArg = plugins.path.join(envYmlPathArg,"env.yml")
2016-06-20 05:06:15 +00:00
let envYml;
try {
envYml = plugins.smartfile.local.toObjectSync(envYmlPathArg);
}
catch(err){
2016-06-21 14:13:29 +00:00
plugins.beautylog.log("env file couldn't be found at " + envYmlPathArg)
2016-06-20 05:06:15 +00:00
envYml = {};
}
2016-06-19 18:49:13 +00:00
for(let keyArg in requiredEnvVarsArg){
2016-06-20 08:45:43 +00:00
let requiredEnvVar:string = requiredEnvVarsArg[keyArg];
if(process.env[requiredEnvVar]){
result.push(requiredEnvVar);
} else if(envYml.hasOwnProperty(requiredEnvVar)){
process.env[requiredEnvVar] = envYml[requiredEnvVar];
result.push(requiredEnvVar);
2016-06-19 18:49:13 +00:00
}
}
2016-06-19 18:08:34 +00:00
return result;
2016-06-20 05:06:15 +00:00
}
let getMissingEnvVars = (requiredEnvVarsArray:string[],availableEnvVarsArray:string[]) => {
return plugins.lodash.difference(requiredEnvVarsArray,availableEnvVarsArray);
2016-06-19 18:08:34 +00:00
}