Compare commits

...

38 Commits

Author SHA1 Message Date
adf602ab86 4.0.9 2020-06-08 18:58:56 +00:00
8bc8285430 fix(core): update 2020-06-08 18:58:55 +00:00
63d9434a39 4.0.8 2020-06-08 18:58:44 +00:00
32ddc9cfed fix(core): update 2020-06-08 18:58:43 +00:00
936a719682 4.0.7 2020-06-08 18:57:23 +00:00
56c4b43f3c fix(core): update 2020-06-08 18:57:22 +00:00
5ed11a280f 4.0.6 2019-10-01 12:32:40 +02:00
346809d5be fix(core): update 2019-10-01 12:32:39 +02:00
90add506e3 4.0.5 2019-09-13 11:20:48 +02:00
adea8d1d69 fix(core): update 2019-09-13 11:20:47 +02:00
1b2eb1d763 4.0.4 2019-08-29 14:29:16 +02:00
cbc974b3d1 fix(core): update 2019-08-29 14:29:16 +02:00
76e72e2a28 4.0.3 2019-08-29 14:19:16 +02:00
697eb83390 fix(core): update 2019-08-29 14:19:15 +02:00
00ec15ccf7 4.0.2 2019-08-06 17:41:46 +02:00
b54a5e2fef fix(core): update 2019-08-06 17:41:45 +02:00
a1aa1543a2 4.0.1 2019-08-06 17:37:07 +02:00
0e48cb8f89 fix(core): update 2019-08-06 17:37:07 +02:00
d76d1a263b 4.0.0 2019-01-15 23:54:29 +01:00
5f6f434998 BREAKING CHANGE(process.env): treat environment as immutable 2019-01-15 23:54:29 +01:00
8e7909e367 3.1.1 2019-01-14 22:42:25 +01:00
ff9302f745 fix(core): update 2019-01-14 22:42:24 +01:00
3577fa22e1 3.1.0 2019-01-14 01:54:05 +01:00
f5275adfbd feat(docker secret): docker secret.json can now also be named [anything].secret.json 2019-01-14 01:54:04 +01:00
31bf1b27a4 3.0.7 2019-01-13 22:33:19 +01:00
a77def5844 fix(core): update 2019-01-13 22:33:18 +01:00
2357699f3e 3.0.6 2019-01-13 22:04:20 +01:00
01f5784488 fix(core): update 2019-01-13 22:04:20 +01:00
80f35c39aa 3.0.5 2019-01-13 21:35:57 +01:00
87f55773bd fix(core): update 2019-01-13 21:35:57 +01:00
1a25341232 3.0.4 2019-01-13 18:25:09 +01:00
ccd41d86bf fix(core): update 2019-01-13 18:25:09 +01:00
0a3a7e480e 3.0.3 2019-01-13 00:00:32 +01:00
33a91c6ae7 fix(core): update 2019-01-13 00:00:32 +01:00
0cfbdf2c9e 3.0.2 2019-01-06 03:36:40 +01:00
f7362e5444 fix(core): update 2019-01-06 03:36:40 +01:00
7844fdb954 3.0.1 2019-01-06 03:20:59 +01:00
81d1a4f15e fix(core): update 2019-01-06 03:20:59 +01:00
14 changed files with 4994 additions and 746 deletions

20
.gitignore vendored
View File

@ -1,4 +1,20 @@
node_modules/ .nogit/
# artifacts
coverage/ coverage/
pages/
public/ public/
pages/
# installs
node_modules/
# caches
.yarn/
.cache/
.rpt2_cache
# builds
dist/
dist_*/
# custom

View File

@ -1,16 +1,16 @@
# gitzone standard # gitzone ci_default
image: hosttoday/ht-docker-node:npmci image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache: cache:
paths: paths:
- .npmci_cache/ - .npmci_cache/
key: "$CI_BUILD_STAGE" key: '$CI_BUILD_STAGE'
stages: stages:
- security - security
- test - test
- release - release
- metadata - metadata
# ==================== # ====================
# security stage # security stage
@ -20,62 +20,28 @@ mirror:
script: script:
- npmci git mirror - npmci git mirror
tags: tags:
- lossless
- docker - docker
- notpriv - notpriv
snyk: audit:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security stage: security
script: script:
- npmci npm prepare - npmci npm prepare
- npmci command npm install -g snyk
- npmci command npm install --ignore-scripts - npmci command npm install --ignore-scripts
- npmci command snyk test - npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high
tags: tags:
- lossless
- docker - docker
- notpriv - notpriv
sast:
stage: security
image: registry.gitlab.com/hosttoday/ht-docker-dbase:npmci
variables:
DOCKER_DRIVER: overlay2
allow_failure: true
services:
- docker:stable-dind
script:
- npmci npm prepare
- npmci npm install
- npmci command npm run build
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/')
- docker run
--env SAST_CONFIDENCE_LEVEL="${SAST_CONFIDENCE_LEVEL:-3}"
--volume "$PWD:/code"
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/sast:$SP_VERSION" /app/bin/run /code
artifacts:
reports:
sast: gl-sast-report.json
tags:
- docker
- priv
# ==================== # ====================
# test stage # test stage
# ==================== # ====================
testLTS: testStable:
stage: test
script:
- npmci npm prepare
- npmci node install lts
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- docker
- notpriv
testSTABLE:
stage: test stage: test
script: script:
- npmci npm prepare - npmci npm prepare
@ -84,6 +50,20 @@ testSTABLE:
- npmci npm test - npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/ coverage: /\d+.?\d+?\%\s*coverage/
tags: tags:
- lossless
- docker
- priv
testBuild:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci command npm run build
coverage: /\d+.?\d+?\%\s*coverage/
tags:
- lossless
- docker - docker
- notpriv - notpriv
@ -95,6 +75,7 @@ release:
only: only:
- tags - tags
tags: tags:
- lossless
- docker - docker
- notpriv - notpriv
@ -103,20 +84,14 @@ release:
# ==================== # ====================
codequality: codequality:
stage: metadata stage: metadata
image: docker:stable
allow_failure: true allow_failure: true
services:
- docker:stable-dind
script: script:
- export SP_VERSION=$(echo "$CI_SERVER_VERSION" | sed 's/^\([0-9]*\)\.\([0-9]*\).*/\1-\2-stable/') - npmci command npm install -g tslint typescript
- docker run - npmci npm prepare
--env SOURCE_CODE="$PWD" - npmci npm install
--volume "$PWD":/code - npmci command "tslint -c tslint.json ./ts/**/*.ts"
--volume /var/run/docker.sock:/var/run/docker.sock
"registry.gitlab.com/gitlab-org/security-products/codequality:$SP_VERSION" /code
artifacts:
paths: [codeclimate.json]
tags: tags:
- lossless
- docker - docker
- priv - priv
@ -127,18 +102,20 @@ trigger:
only: only:
- tags - tags
tags: tags:
- lossless
- docker - docker
- notpriv - notpriv
pages: pages:
image: hosttoday/ht-docker-node:npmci
stage: metadata stage: metadata
script: script:
- npmci command npm install -g typedoc typescript - npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare - npmci npm prepare
- npmci npm install - npmci npm install
- npmci command typedoc --module "commonjs" --target "ES2016" --out public/ ts/ - npmci command tsdoc
tags: tags:
- lossless
- docker - docker
- notpriv - notpriv
only: only:

29
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,29 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "current file",
"type": "node",
"request": "launch",
"args": [
"${relativeFile}"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
},
{
"name": "test.ts",
"type": "node",
"request": "launch",
"args": [
"test/test.ts"
],
"runtimeArgs": ["-r", "@gitzone/tsrun"],
"cwd": "${workspaceRoot}",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart"
}
]
}

26
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,26 @@
{
"json.schemas": [
{
"fileMatch": ["/npmextra.json"],
"schema": {
"type": "object",
"properties": {
"npmci": {
"type": "object",
"description": "settings for npmci"
},
"gitzone": {
"type": "object",
"description": "settings for gitzone",
"properties": {
"projectType": {
"type": "string",
"enum": ["website", "element", "service", "npm"]
}
}
}
}
}
}
]
}

View File

@ -1,46 +0,0 @@
# qenv
easy promised environments
## Availabililty
[![npm](https://pushrocks.gitlab.io/assets/repo-button-npm.svg)](https://www.npmjs.com/package/qenv)
[![git](https://pushrocks.gitlab.io/assets/repo-button-git.svg)](https://GitLab.com/pushrocks/qenv)
[![git](https://pushrocks.gitlab.io/assets/repo-button-mirror.svg)](https://github.com/pushrocks/qenv)
[![docs](https://pushrocks.gitlab.io/assets/repo-button-docs.svg)](https://pushrocks.gitlab.io/qenv/)
## Status for master
[![build status](https://GitLab.com/pushrocks/qenv/badges/master/build.svg)](https://GitLab.com/pushrocks/qenv/commits/master)
[![coverage report](https://GitLab.com/pushrocks/qenv/badges/master/coverage.svg)](https://GitLab.com/pushrocks/qenv/commits/master)
[![npm downloads per month](https://img.shields.io/npm/dm/qenv.svg)](https://www.npmjs.com/package/qenv)
[![Dependency Status](https://david-dm.org/pushrocks/qenv.svg)](https://david-dm.org/pushrocks/qenv)
[![bitHound Dependencies](https://www.bithound.io/github/pushrocks/qenv/badges/dependencies.svg)](https://www.bithound.io/github/pushrocks/qenv/master/dependencies/npm)
[![bitHound Code](https://www.bithound.io/github/pushrocks/qenv/badges/code.svg)](https://www.bithound.io/github/pushrocks/qenv)
[![TypeScript](https://img.shields.io/badge/TypeScript-2.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![node](https://img.shields.io/badge/node->=%206.x.x-blue.svg)](https://nodejs.org/dist/latest-v6.x/docs/api/)
[![JavaScript Style Guide](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)](http://standardjs.com/)
## Usage
Use TypeScript for best in class instellisense.
qenv works with two files:
- **qenv.yml** - specifies which ENV vars are required.
- **env.yml** - specifies all env vars that are not already set in the current environment.
Now obviously you can set build specific env vars in many CI environments.
So there we do not need an **env.yml** since all ENV vars are in place
However when on another machine you can have a env.yml that will be added to the environment by qenv.
```javascript
import { Qenv } from 'qenv';
const myQenv = new Qenv('path/to/dir/where/qenv.yml/is/', 'path/to/dir/where/env.yml/is(');
```
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
> | By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy.html)
[![repo-footer](https://pushrocks.gitlab.io/assets/repo-footer.svg)](https://push.rocks)

View File

@ -2,5 +2,16 @@
"npmci": { "npmci": {
"npmGlobalTools": [], "npmGlobalTools": [],
"npmAccessLevel": "public" "npmAccessLevel": "public"
},
"gitzone": {
"projectType": "npm",
"module": {
"githost": "gitlab.com",
"gitscope": "pushrocks",
"gitrepo": "qenv",
"shortDescription": "easy promised environments",
"npmPackagename": "@pushrocks/qenv",
"license": "MIT"
}
} }
} }

5136
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,10 +1,10 @@
{ {
"name": "@pushrocks/qenv", "name": "@pushrocks/qenv",
"version": "3.0.0", "version": "4.0.9",
"private": false, "private": false,
"description": "easy promised environments", "description": "easy promised environments",
"main": "dist/index.js", "main": "dist_ts/index.js",
"typings": "dist/index.d.ts", "typings": "dist_ts/index.d.ts",
"scripts": { "scripts": {
"test": "(tstest test/)", "test": "(tstest test/)",
"build": "(tsbuild)" "build": "(tsbuild)"
@ -25,16 +25,28 @@
}, },
"homepage": "https://gitlab.com/pushrocks/qenv#README", "homepage": "https://gitlab.com/pushrocks/qenv#README",
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.0.22", "@gitzone/tsbuild": "^2.1.24",
"@gitzone/tsrun": "^1.1.12", "@gitzone/tsrun": "^1.2.12",
"@gitzone/tstest": "^1.0.13", "@gitzone/tstest": "^1.0.33",
"@pushrocks/tapbundle": "^3.0.5", "@pushrocks/tapbundle": "^3.2.1",
"@types/node": "^10.5.8", "@types/node": "^14.0.12",
"tslint": "^5.12.0", "tslint": "^6.1.2",
"tslint-config-prettier": "^1.17.0" "tslint-config-prettier": "^1.18.0"
}, },
"dependencies": { "dependencies": {
"@pushrocks/smartfile": "^6.0.6", "@pushrocks/smartfile": "^7.0.12",
"@pushrocks/smartlog": "^2.0.9" "@pushrocks/smartlog": "^2.0.26"
} },
"files": [
"ts/**/*",
"ts_web/**/*",
"dist/**/*",
"dist_*/**/*",
"dist_ts/**/*",
"dist_ts_web/**/*",
"assets/**/*",
"cli.js",
"npmextra.json",
"readme.md"
]
} }

54
readme.md Normal file
View File

@ -0,0 +1,54 @@
# @pushrocks/qenv
easy promised environments
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@pushrocks/qenv)
* [gitlab.com (source)](https://gitlab.com/pushrocks/qenv)
* [github.com (source mirror)](https://github.com/pushrocks/qenv)
* [docs (typedoc)](https://pushrocks.gitlab.io/qenv/)
## Status for master
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/pushrocks/qenv/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/pushrocks/qenv/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@pushrocks/qenv)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/pushrocks/qenv)](https://lossless.cloud)
TypeScript Support | [![TypeScript](https://badgen.net/badge/TypeScript/>=%203.x/blue?icon=typescript)](https://lossless.cloud)
node Support | [![node](https://img.shields.io/badge/node->=%2010.x.x-blue.svg)](https://nodejs.org/dist/latest-v10.x/docs/api/)
Code Style | [![Code Style](https://badgen.net/badge/style/prettier/purple)](https://lossless.cloud)
PackagePhobia (total standalone install weight) | [![PackagePhobia](https://badgen.net/packagephobia/install/@pushrocks/qenv)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@pushrocks/qenv)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@pushrocks/qenv)](https://lossless.cloud)
Platform support | [![Supports Windows 10](https://badgen.net/badge/supports%20Windows%2010/yes/green?icon=windows)](https://lossless.cloud) [![Supports Mac OS X](https://badgen.net/badge/supports%20Mac%20OS%20X/yes/green?icon=apple)](https://lossless.cloud)
## Usage
Use TypeScript for best in class instellisense.
qenv works with two files:
- **qenv.yml** - specifies which ENV vars are required.
- **env.yml** - specifies all env vars that are not already set in the current environment.
Now obviously you can set build specific env vars in many CI environments.
So there we do not need an **env.yml** since all ENV vars are in place
However when on another machine you can have a env.yml that will be added to the environment by qenv.
```javascript
import { Qenv } from 'qenv';
const myQenv = new Qenv('path/to/dir/where/qenv.yml/is/', 'path/to/dir/where/env.yml/is(');
```
## Contribution
We are always happy for code contributions. If you are not the code contributing type that is ok. Still, maintaining Open Source repositories takes considerable time and thought. If you like the quality of what we do and our modules are useful to you we would appreciate a little monthly contribution: You can [contribute one time](https://lossless.link/contribute-onetime) or [contribute monthly](https://lossless.link/contribute). :)
For further information read the linked docs at the top of this readme.
> MIT licensed | **©** [Lossless GmbH](https://lossless.gmbh)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)
[![repo-footer](https://lossless.gitlab.io/publicrelations/repofooter.svg)](https://maintainedby.lossless.com)

4
test/assets/env.json Normal file
View File

@ -0,0 +1,4 @@
{
"key1": "fromJson",
"key2" :"fromJson"
}

View File

@ -1,2 +0,0 @@
key1: fromYml
key2: fromYml

View File

@ -4,28 +4,26 @@ import * as qenv from '../ts/index';
process.env['key1'] = 'original'; process.env['key1'] = 'original';
let qenvTestObject: qenv.Qenv; let testQenv: qenv.Qenv;
tap.test('should create a new class', async () => { tap.test('should create a new class', async () => {
qenvTestObject = new qenv.Qenv( testQenv = new qenv.Qenv(path.join(__dirname, 'assets'), path.join(__dirname, 'assets'), false);
path.join(__dirname, 'assets'), expect(testQenv).to.be.instanceof(qenv.Qenv);
path.join(__dirname, 'assets'),
false
);
expect(qenvTestObject).to.be.instanceof(qenv.Qenv);
}); });
tap.test('key1 should be not be overwritten since it is already present', async () => { tap.test('key1 should be not be overwritten since it is already present', async () => {
expect(process.env.key1).to.equal('original'); expect(testQenv.getEnvVarRequired('key1')).to.equal('original');
expect(testQenv.getEnvVarOnDemand('key1')).to.equal('original');
}); });
tap.test('key2 should be read from Yml', async () => { tap.test('key2 should be read from Yml', async () => {
expect(process.env.key2).to.equal('fromYml'); expect(testQenv.getEnvVarRequired('key2')).to.equal('fromJson');
expect(testQenv.getEnvVarOnDemand('key2')).to.equal('fromJson');
}); });
tap.test('keyValueObjectArray should hold all retrieved values', async () => { tap.test('keyValueObjectArray should hold all retrieved values', async () => {
expect(qenvTestObject.keyValueObjectArray[0].value).to.equal('original'); expect(testQenv.keyValueObject.key1).to.equal('original');
expect(qenvTestObject.keyValueObjectArray[1].value).to.equal('fromYml'); expect(testQenv.keyValueObject.key2).to.equal('fromJson');
}); });
tap.start(); tap.start();

View File

@ -1,32 +1,30 @@
import * as plugins from './qenv.plugins'; import * as plugins from './qenv.plugins';
export interface IKeyValueObject { /**
key: string; * class Qenv
value: string; * allows to make assertions about the environments while being more flexibel in how to meet them
} */
export class Qenv { export class Qenv {
public requiredEnvVars: string[] = []; public requiredEnvVars: string[] = [];
public availableEnvVars: string[] = []; public availableEnvVars: string[] = [];
public missingEnvVars: string[] = []; public missingEnvVars: string[] = [];
public keyValueObjectArray: IKeyValueObject[] = []; public keyValueObject: { [key: string]: any } = {};
public logger: plugins.smartlog.Smartlog; public logger = new plugins.smartlog.ConsoleLog();
// filePaths // filePaths
public qenvFilePathAbsolute: string; public qenvFilePathAbsolute: string;
public envFilePathAbsolute: string; public envFilePathAbsolute: string;
constructor( constructor(qenvFileBasePathArg = process.cwd(), envFileBasePathArg, failOnMissing = true) {
qenvFileBasePathArg = process.cwd(),
envFileBasePathArg,
failOnMissing = true,
loggerArg: plugins.smartlog.Smartlog = plugins.smartlog.defaultLogger
) {
this.logger = loggerArg;
// lets make sure paths are absolute // lets make sure paths are absolute
this.qenvFilePathAbsolute = plugins.path.join(plugins.path.resolve(qenvFileBasePathArg), 'qenv.yml'); this.qenvFilePathAbsolute = plugins.path.join(
this.envFilePathAbsolute = plugins.path.join(plugins.path.resolve(envFileBasePathArg), 'env.yml'); plugins.path.resolve(qenvFileBasePathArg),
'qenv.yml'
);
this.envFilePathAbsolute = plugins.path.join(
plugins.path.resolve(envFileBasePathArg),
'env.json'
);
this.getRequiredEnvVars(); this.getRequiredEnvVars();
this.getAvailableEnvVars(); this.getAvailableEnvVars();
@ -40,96 +38,147 @@ export class Qenv {
console.error('However some Env variables could not be resolved:'); console.error('However some Env variables could not be resolved:');
console.log(this.missingEnvVars); console.log(this.missingEnvVars);
if (failOnMissing) { if (failOnMissing) {
console.error('Exiting!'); this.logger.log('error', 'Exiting!');
process.exit(1); process.exit(1);
} else {
this.logger.log('warn', 'qenv is not set to fail on missing environment variables');
} }
} }
} }
public getEnvVar(envVarName): string { /**
return process.env[envVarName]; * only gets an environment variable if it is required within a read qenv.yml file
* @param envVarName
*/
public getEnvVarRequired(envVarName): string {
return this.keyValueObject[envVarName];
} }
public getEnvVarOnDemand(requiredEnvVar: string): string { /**
// lets determine the actual env yml * tries to get any env var even if it is not required
let envYml; * @param wantedEnvVar
try { */
envYml = plugins.smartfile.fs.toObjectSync(this.envFilePathAbsolute); public getEnvVarOnDemand(wantedEnvVar: string): string {
} catch (err) { let envVarFromEnvironmentVariable: string;
console.log("env file couldn't be found at " + this.envFilePathAbsolute); let envVarFromEnvJsonFile: string;
envYml = {}; let envVarFromDockerSecret: string;
} let dockerSecretJson: string;
let envVar: string;
let envFileVar: string;
let dockerSecret: string;
// env var check // env var check
if (process.env[requiredEnvVar]) { if (process.env[wantedEnvVar]) {
this.availableEnvVars.push(requiredEnvVar); this.availableEnvVars.push(wantedEnvVar);
envVar = process.env[requiredEnvVar]; envVarFromEnvironmentVariable = process.env[wantedEnvVar];
} }
// env file check // env file check
if (envYml.hasOwnProperty(requiredEnvVar)) { // lets determine the actual env yml
envFileVar = envYml[requiredEnvVar]; let envJsonFileAsObject;
this.availableEnvVars.push(requiredEnvVar); try {
envJsonFileAsObject = plugins.smartfile.fs.toObjectSync(this.envFilePathAbsolute);
} catch (err) {
envJsonFileAsObject = {};
} }
if (envJsonFileAsObject.hasOwnProperty(wantedEnvVar)) {
envVarFromEnvJsonFile = envJsonFileAsObject[wantedEnvVar];
}
// docker secret check
if ( if (
plugins.smartfile.fs.isDirectory('/run') && plugins.smartfile.fs.isDirectory('/run') &&
plugins.smartfile.fs.isDirectory('/run/secrets') && plugins.smartfile.fs.isDirectory('/run/secrets') &&
plugins.smartfile.fs.fileExists(`/run/secrets/${requiredEnvVar}`) plugins.smartfile.fs.fileExistsSync(`/run/secrets/${wantedEnvVar}`)
) { ) {
dockerSecret = plugins.smartfile.fs.toStringSync(`/run/secrets/${requiredEnvVar}`); envVarFromDockerSecret = plugins.smartfile.fs.toStringSync(`/run/secrets/${wantedEnvVar}`);
} }
if ((envVar && envFileVar) || (envVar && dockerSecret) || (envFileVar && dockerSecret)) { // docker secret.json
if (
plugins.smartfile.fs.isDirectory('/run') &&
plugins.smartfile.fs.isDirectory('/run/secrets')
) {
const availableSecrets = plugins.smartfile.fs.listAllItemsSync('/run/secrets');
for (const secret of availableSecrets) {
if (secret.includes('secret.json') && !envVarFromDockerSecret) {
const secretObject = plugins.smartfile.fs.toObjectSync(`/run/secrets/${secret}`);
envVarFromDockerSecret = secretObject[wantedEnvVar];
}
}
}
// warn if there is more than one candidate
const availableCcandidates: any[] = [];
[
envVarFromEnvironmentVariable,
envVarFromEnvJsonFile,
envVarFromDockerSecret,
dockerSecretJson
].forEach(candidate => {
if (candidate) {
availableCcandidates.push(candidate);
}
});
if (availableCcandidates.length > 1) {
this.logger.log( this.logger.log(
'warn', 'warn',
`found multiple candidates for ${requiredEnvVar} Choosing in the order of envVar, envFileVar, dockerSecret` `found multiple candidates for ${wantedEnvVar} Choosing in the order of envVar, envFileVar, dockerSecret, dockerSecretJson`
); );
console.log(availableCcandidates);
} }
let chosenVar: string = null; switch (true) {
if (envVar) { case !!envVarFromEnvironmentVariable:
chosenVar = envVar; this.logger.log('ok', `found ${wantedEnvVar} as environment variable`);
} else if (envFileVar) { return envVarFromEnvironmentVariable;
chosenVar = envFileVar; case !!envVarFromEnvJsonFile:
} else if (dockerSecret) { this.logger.log('ok', `found ${wantedEnvVar} as env.json variable`);
chosenVar = dockerSecret; return envVarFromEnvJsonFile;
case !!envVarFromDockerSecret:
this.logger.log('ok', `found ${wantedEnvVar} as docker secret`);
return envVarFromDockerSecret;
case !!dockerSecretJson:
this.logger.log('ok', `found ${wantedEnvVar} as docker secret.json`);
return dockerSecretJson;
default:
this.logger.log(
'warn',
`could not find the wanted environment variable ${wantedEnvVar} anywhere`
);
return;
} }
return chosenVar;
} }
/** /**
* gets the required env values * gets the required env values
*/ */
private getRequiredEnvVars = () => { private getRequiredEnvVars = () => {
const qenvFile = plugins.smartfile.fs.toObjectSync(this.qenvFilePathAbsolute); let qenvFile: any = {};
if (!qenvFile.required) { if (plugins.smartfile.fs.fileExistsSync(this.qenvFilePathAbsolute)) {
this.logger.log('warn', `env File does not contain a 'required' Array!`); qenvFile = plugins.smartfile.fs.toObjectSync(this.qenvFilePathAbsolute);
} }
for (const keyArg of Reflect.ownKeys(qenvFile.required)) { if (!qenvFile || !qenvFile.required || !Array.isArray(qenvFile.required)) {
this.logger.log(
'warn',
`qenv (promised environment): ./qenv.yml File does not contain a 'required' Array! This might be ok though.`
);
} else {
for (const keyArg of Object.keys(qenvFile.required)) {
this.requiredEnvVars.push(qenvFile.required[keyArg]); this.requiredEnvVars.push(qenvFile.required[keyArg]);
} }
} }
};
/** /**
* gets the available env vars * gets the available env vars
*/ */
private getAvailableEnvVars = () => { private getAvailableEnvVars = () => {
for (const requiredEnvVar of this.requiredEnvVars) { for (const requiredEnvVar of this.requiredEnvVars) {
const chosenVar = this.getEnvVarOnDemand(requiredEnvVar); const chosenVar = this.getEnvVarOnDemand(requiredEnvVar);
if (chosenVar) { if (chosenVar) {
this.availableEnvVars.push(requiredEnvVar); this.availableEnvVars.push(requiredEnvVar);
process.env[requiredEnvVar] = chosenVar; this.keyValueObject[requiredEnvVar] = chosenVar;
this.keyValueObjectArray.push({
key: requiredEnvVar,
value: chosenVar
});
}
} }
} }
};
/** /**
* gets missing env vars * gets missing env vars
@ -142,5 +191,5 @@ export class Qenv {
} }
} }
return missingEnvVars; return missingEnvVars;
} };
} }

View File

@ -1,16 +1,10 @@
// native // native
import * as path from 'path'; import * as path from 'path';
export { export { path };
path
}
// @pushrocks scope // @pushrocks scope
import * as smartfile from '@pushrocks/smartfile'; import * as smartfile from '@pushrocks/smartfile';
import * as smartlog from '@pushrocks/smartlog'; import * as smartlog from '@pushrocks/smartlog';
export { export { smartfile, smartlog };
smartfile,
smartlog
}