Compare commits

...

20 Commits

Author SHA1 Message Date
56ce78f794 5.0.5 2023-08-09 12:49:52 +02:00
9d33054f03 fix(core): update 2023-08-09 12:49:52 +02:00
072ca59ab0 5.0.4 2023-08-08 19:50:45 +02:00
59e3759a3a fix(core): update 2023-08-08 19:50:44 +02:00
bc95ba3f2d 5.0.3 2023-08-08 19:08:25 +02:00
1e6b9779b8 fix(core): update 2023-08-08 19:08:25 +02:00
3988887a37 switch to new org scheme 2023-07-11 00:07:40 +02:00
5a26ba7771 switch to new org scheme 2023-07-10 02:41:52 +02:00
f61c0da30a 5.0.2 2022-08-02 14:50:18 +02:00
3dfb07e875 fix(core): update 2022-08-02 14:50:18 +02:00
fde1e90440 5.0.1 2022-07-28 10:10:40 +02:00
f06c9f186f fix(core): update 2022-07-28 10:10:39 +02:00
e539489901 5.0.0 2022-07-28 10:09:35 +02:00
a1dcfba0a2 BREAKING CHANGE(core): switch to esm 2022-07-28 10:09:34 +02:00
cff79e56c0 4.0.11 2022-07-28 10:09:01 +02:00
44252ab0d3 fix(core): update 2022-07-28 10:09:01 +02:00
d4c3ec6c90 4.0.10 2020-06-08 19:03:18 +00:00
42aa1c2831 fix(core): update 2020-06-08 19:03:17 +00:00
adf602ab86 4.0.9 2020-06-08 18:58:56 +00:00
8bc8285430 fix(core): update 2020-06-08 18:58:55 +00:00
18 changed files with 5188 additions and 5534 deletions

View File

@ -0,0 +1,66 @@
name: Default (not tags)
on:
push:
tags-ignore:
- '**'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Install pnpm and npmci
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
- name: Run npm prepare
run: npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build

View File

@ -0,0 +1,124 @@
name: Default (tags)
on:
push:
tags:
- '*'
env:
IMAGE: registry.gitlab.com/hosttoday/ht-docker-node:npmci
NPMCI_COMPUTED_REPOURL: https://${{gitea.repository_owner}}:${{secrets.GITEA_TOKEN}}@gitea.lossless.digital/${{gitea.repository}}.git
NPMCI_TOKEN_NPM: ${{secrets.NPMCI_TOKEN_NPM}}
NPMCI_TOKEN_NPM2: ${{secrets.NPMCI_TOKEN_NPM2}}
NPMCI_GIT_GITHUBTOKEN: ${{secrets.NPMCI_GIT_GITHUBTOKEN}}
NPMCI_URL_CLOUDLY: ${{secrets.NPMCI_URL_CLOUDLY}}
jobs:
security:
runs-on: ubuntu-latest
continue-on-error: true
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Audit production dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --prod
continue-on-error: true
- name: Audit development dependencies
run: |
npmci command npm config set registry https://registry.npmjs.org
npmci command pnpm audit --audit-level=high --dev
continue-on-error: true
test:
if: ${{ always() }}
needs: security
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Test stable
run: |
npmci node install stable
npmci npm install
npmci npm test
- name: Test build
run: |
npmci node install stable
npmci npm install
npmci npm build
release:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Release
run: |
npmci node install stable
npmci npm publish
metadata:
needs: test
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
container:
image: ${{ env.IMAGE }}
continue-on-error: true
steps:
- uses: actions/checkout@v3
- name: Prepare
run: |
pnpm install -g pnpm
pnpm install -g @shipzone/npmci
npmci npm prepare
- name: Code quality
run: |
npmci command npm install -g typescript
npmci npm install
- name: Trigger
run: npmci trigger
- name: Build docs and upload artifacts
run: |
npmci node install stable
npmci npm install
pnpm install -g @gitzone/tsdoc
npmci command tsdoc
continue-on-error: true

View File

@ -1,127 +0,0 @@
# gitzone ci_default
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
cache:
paths:
- .npmci_cache/
key: '$CI_BUILD_STAGE'
stages:
- security
- test
- release
- metadata
# ====================
# security stage
# ====================
mirror:
stage: security
script:
- npmci git mirror
tags:
- lossless
- docker
- notpriv
audit:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security
script:
- npmci npm prepare
- npmci command npm install --ignore-scripts
- npmci command npm config set registry https://registry.npmjs.org
- npmci command npm audit --audit-level=high
tags:
- lossless
- docker
- notpriv
# ====================
# test stage
# ====================
testStable:
stage: test
script:
- npmci npm prepare
- npmci node install stable
- npmci npm install
- npmci npm test
coverage: /\d+.?\d+?\%\s*coverage/
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
- notpriv
release:
stage: release
script:
- npmci node install stable
- npmci npm publish
only:
- tags
tags:
- lossless
- docker
- notpriv
# ====================
# metadata stage
# ====================
codequality:
stage: metadata
allow_failure: true
script:
- npmci command npm install -g tslint typescript
- npmci npm prepare
- npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags:
- lossless
- docker
- priv
trigger:
stage: metadata
script:
- npmci trigger
only:
- tags
tags:
- lossless
- docker
- notpriv
pages:
stage: metadata
script:
- npmci node install lts
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare
- npmci npm install
- npmci command tsdoc
tags:
- lossless
- docker
- notpriv
only:
- tags
artifacts:
expire_in: 1 week
paths:
- public
allow_failure: true

View File

@ -1,4 +0,0 @@
node_modules/
coverage/
docs/

24
.vscode/launch.json vendored
View File

@ -2,28 +2,10 @@
"version": "0.2.0", "version": "0.2.0",
"configurations": [ "configurations": [
{ {
"name": "current file", "command": "npm test",
"type": "node", "name": "Run npm test",
"request": "launch", "request": "launch",
"args": [ "type": "node-terminal"
"${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"
} }
] ]
} }

View File

@ -15,7 +15,7 @@
"properties": { "properties": {
"projectType": { "projectType": {
"type": "string", "type": "string",
"enum": ["website", "element", "service", "npm"] "enum": ["website", "element", "service", "npm", "wcc"]
} }
} }
} }

View File

@ -7,10 +7,10 @@
"projectType": "npm", "projectType": "npm",
"module": { "module": {
"githost": "gitlab.com", "githost": "gitlab.com",
"gitscope": "pushrocks", "gitscope": "push.rocks",
"gitrepo": "qenv", "gitrepo": "qenv",
"shortDescription": "easy promised environments", "description": "easy promised environments",
"npmPackagename": "@pushrocks/qenv", "npmPackagename": "@push.rocks/qenv",
"license": "MIT" "license": "MIT"
} }
} }

5183
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,13 +1,15 @@
{ {
"name": "@pushrocks/qenv", "name": "@push.rocks/qenv",
"version": "4.0.8", "version": "5.0.5",
"private": false, "private": false,
"description": "easy promised environments", "description": "easy promised environments",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts", "typings": "dist_ts/index.d.ts",
"type": "module",
"scripts": { "scripts": {
"test": "(tstest test/)", "test": "(tstest test/)",
"build": "(tsbuild)" "build": "(tsbuild --web --allowimplicitany)",
"buildDocs": "tsdoc"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@ -25,17 +27,17 @@
}, },
"homepage": "https://gitlab.com/pushrocks/qenv#README", "homepage": "https://gitlab.com/pushrocks/qenv#README",
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.24", "@gitzone/tsbuild": "^2.1.66",
"@gitzone/tsrun": "^1.2.12", "@gitzone/tsrun": "^1.2.44",
"@gitzone/tstest": "^1.0.33", "@gitzone/tstest": "^1.0.77",
"@pushrocks/tapbundle": "^3.2.1", "@push.rocks/tapbundle": "^5.0.12",
"@types/node": "^14.0.12", "@types/node": "^20.4.6"
"tslint": "^6.1.2",
"tslint-config-prettier": "^1.18.0"
}, },
"dependencies": { "dependencies": {
"@pushrocks/smartfile": "^7.0.12", "@configvault.io/interfaces": "^1.0.2",
"@pushrocks/smartlog": "^2.0.26" "@push.rocks/smartfile": "^10.0.28",
"@push.rocks/smartlog": "^3.0.3",
"@push.rocks/smartpath": "^5.0.11"
}, },
"files": [ "files": [
"ts/**/*", "ts/**/*",
@ -48,5 +50,8 @@
"cli.js", "cli.js",
"npmextra.json", "npmextra.json",
"readme.md" "readme.md"
],
"browserslist": [
"last 1 chrome versions"
] ]
} }

4792
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

52
readme.md Normal file
View File

@ -0,0 +1,52 @@
# @push.rocks/qenv
easy promised environments
## Availabililty and Links
* [npmjs.org (npm package)](https://www.npmjs.com/package/@push.rocks/qenv)
* [gitlab.com (source)](https://gitlab.com/push.rocks/qenv)
* [github.com (source mirror)](https://github.com/push.rocks/qenv)
* [docs (typedoc)](https://push.rocks.gitlab.io/qenv/)
## Status for master
Status Category | Status Badge
-- | --
GitLab Pipelines | [![pipeline status](https://gitlab.com/push.rocks/qenv/badges/master/pipeline.svg)](https://lossless.cloud)
GitLab Pipline Test Coverage | [![coverage report](https://gitlab.com/push.rocks/qenv/badges/master/coverage.svg)](https://lossless.cloud)
npm | [![npm downloads per month](https://badgen.net/npm/dy/@push.rocks/qenv)](https://lossless.cloud)
Snyk | [![Known Vulnerabilities](https://badgen.net/snyk/push.rocks/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/@push.rocks/qenv)](https://lossless.cloud)
PackagePhobia (package size on registry) | [![PackagePhobia](https://badgen.net/packagephobia/publish/@push.rocks/qenv)](https://lossless.cloud)
BundlePhobia (total size when bundled) | [![BundlePhobia](https://badgen.net/bundlephobia/minzip/@push.rocks/qenv)](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.
## Legal
> MIT licensed | **©** [Task Venture Capital GmbH](https://task.vc)
| By using this npm module you agree to our [privacy policy](https://lossless.gmbH/privacy)

View File

@ -1,29 +1,35 @@
import * as path from 'path'; import * as path from 'path';
import { tap, expect } from '@pushrocks/tapbundle'; import { tap, expect } from '@push.rocks/tapbundle';
import * as qenv from '../ts/index'; import * as qenv from '../ts/index.js';
import * as smartpath from '@push.rocks/smartpath';
export { smartpath };
const testDir = smartpath.get.dirnameFromImportMetaUrl(import.meta.url);
process.env['key1'] = 'original'; process.env['key1'] = 'original';
let testQenv: qenv.Qenv; let testQenv: qenv.Qenv;
tap.test('should create a new class', async () => { tap.test('should create a new class', async () => {
testQenv = new qenv.Qenv(path.join(__dirname, 'assets'), path.join(__dirname, 'assets'), false); testQenv = new qenv.Qenv(path.join(testDir, 'assets'), path.join(testDir, 'assets'), false);
expect(testQenv).to.be.instanceof(qenv.Qenv); expect(testQenv).toBeInstanceOf(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(testQenv.getEnvVarRequired('key1')).to.equal('original'); expect(testQenv.getEnvVarOnDemand('key1')).toEqual('original');
expect(testQenv.getEnvVarOnDemand('key1')).to.equal('original'); expect(testQenv.getEnvVarOnDemand('key1')).toEqual('original');
}); });
tap.test('key2 should be read from Yml', async () => { tap.test('key2 should be read from Yml', async () => {
expect(testQenv.getEnvVarRequired('key2')).to.equal('fromJson'); expect(testQenv.getEnvVarOnDemand('key2')).toEqual('fromJson');
expect(testQenv.getEnvVarOnDemand('key2')).to.equal('fromJson'); expect(testQenv.getEnvVarOnDemand('key2')).toEqual('fromJson');
}); });
tap.test('keyValueObjectArray should hold all retrieved values', async () => { tap.test('keyValueObjectArray should hold all retrieved values', async () => {
expect(testQenv.keyValueObject.key1).to.equal('original'); expect(testQenv.keyValueObject.key1).toEqual('original');
expect(testQenv.keyValueObject.key2).to.equal('fromJson'); expect(testQenv.keyValueObject.key2).toEqual('fromJson');
}); });
tap.start(); tap.start();

8
ts/00_commitinfo_data.ts Normal file
View File

@ -0,0 +1,8 @@
/**
* autocreated commitinfo by @pushrocks/commitinfo
*/
export const commitinfo = {
name: '@push.rocks/qenv',
version: '5.0.5',
description: 'easy promised environments'
}

View File

@ -1 +1 @@
export * from './qenv.classes.qenv'; export * from './qenv.classes.qenv.js';

View File

@ -1,9 +1,5 @@
import * as plugins from './qenv.plugins'; import * as plugins from './qenv.plugins.js';
/**
* class Qenv
* 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[] = [];
@ -11,34 +7,54 @@ export class Qenv {
public keyValueObject: { [key: string]: any } = {}; public keyValueObject: { [key: string]: any } = {};
public logger = new plugins.smartlog.ConsoleLog(); public logger = new plugins.smartlog.ConsoleLog();
// filePaths
public qenvFilePathAbsolute: string; public qenvFilePathAbsolute: string;
public envFilePathAbsolute: string; public envFilePathAbsolute: string;
constructor(qenvFileBasePathArg = process.cwd(), envFileBasePathArg, failOnMissing = true) { constructor(
// lets make sure paths are absolute qenvFileBasePathArg: string = process.cwd(),
this.qenvFilePathAbsolute = plugins.path.join( envFileBasePathArg: string,
plugins.path.resolve(qenvFileBasePathArg), failOnMissing: boolean = true
'qenv.yml' ) {
); this.initializeFilePaths(qenvFileBasePathArg, envFileBasePathArg);
this.envFilePathAbsolute = plugins.path.join( this.loadRequiredEnvVars();
plugins.path.resolve(envFileBasePathArg), this.loadAvailableEnvVars();
'env.json' this.checkForMissingEnvVars(failOnMissing);
); }
this.getRequiredEnvVars(); private initializeFilePaths(qenvFileBasePathArg: string, envFileBasePathArg: string) {
this.getAvailableEnvVars(); this.qenvFilePathAbsolute = plugins.path.join(plugins.path.resolve(qenvFileBasePathArg), 'qenv.yml');
this.envFilePathAbsolute = plugins.path.join(plugins.path.resolve(envFileBasePathArg), 'env.json');
}
this.missingEnvVars = this.getMissingEnvVars(); private loadRequiredEnvVars() {
if (plugins.smartfile.fs.fileExistsSync(this.qenvFilePathAbsolute)) {
const qenvFile = plugins.smartfile.fs.toObjectSync(this.qenvFilePathAbsolute);
if (qenvFile?.required && Array.isArray(qenvFile.required)) {
this.requiredEnvVars.push(...qenvFile.required);
} else {
this.logger.log('warn', 'qenv.yml does not contain a "required" Array!');
}
}
}
private loadAvailableEnvVars() {
for (const envVar of this.requiredEnvVars) {
const value = this.getEnvVarOnDemand(envVar);
if (value) {
this.availableEnvVars.push(envVar);
this.keyValueObject[envVar] = value;
}
}
}
private checkForMissingEnvVars(failOnMissing: boolean) {
this.missingEnvVars = this.requiredEnvVars.filter((envVar) => !this.availableEnvVars.includes(envVar));
// handle missing variables
if (this.missingEnvVars.length > 0) { if (this.missingEnvVars.length > 0) {
console.info('Required Env Vars are:'); console.info('Required Env Vars are:', this.requiredEnvVars);
console.log(this.requiredEnvVars); console.error('Missing Env Vars:', this.missingEnvVars);
console.error('However some Env variables could not be resolved:');
console.log(this.missingEnvVars);
if (failOnMissing) { if (failOnMissing) {
this.logger.log('error', 'Exiting!'); this.logger.log('error', 'Exiting due to missing env vars!');
process.exit(1); process.exit(1);
} else { } else {
this.logger.log('warn', 'qenv is not set to fail on missing environment variables'); this.logger.log('warn', 'qenv is not set to fail on missing environment variables');
@ -46,150 +62,73 @@ export class Qenv {
} }
} }
/** public getEnvVarOnDemand(envVarName: string): string | undefined {
* only gets an environment variable if it is required within a read qenv.yml file return (
* @param envVarName this.getFromEnvironmentVariable(envVarName) ||
*/ this.getFromEnvJsonFile(envVarName) ||
public getEnvVarRequired(envVarName): string { this.getFromDockerSecret(envVarName) ||
return this.keyValueObject[envVarName]; this.getFromDockerSecretJson(envVarName)
);
} }
/** public getEnvVarOnDemandAsObject(envVarName: string): any {
* tries to get any env var even if it is not required const rawValue = this.getEnvVarOnDemand(envVarName);
* @param wantedEnvVar if (rawValue && rawValue.startsWith('base64Object:')) {
*/ const base64Part = rawValue.split('base64Object:')[1];
public getEnvVarOnDemand(wantedEnvVar: string): string { return this.decodeBase64(base64Part);
let envVarFromEnvironmentVariable: string; }
let envVarFromEnvJsonFile: string; return rawValue;
let envVarFromDockerSecret: string;
let dockerSecretJson: string;
// env var check
if (process.env[wantedEnvVar]) {
this.availableEnvVars.push(wantedEnvVar);
envVarFromEnvironmentVariable = process.env[wantedEnvVar];
} }
// env file check private getFromEnvironmentVariable(envVarName: string): string | undefined {
// lets determine the actual env yml return process.env[envVarName];
let envJsonFileAsObject; }
private getFromEnvJsonFile(envVarName: string): string | undefined {
try { try {
envJsonFileAsObject = plugins.smartfile.fs.toObjectSync(this.envFilePathAbsolute); const envJson = plugins.smartfile.fs.toObjectSync(this.envFilePathAbsolute);
} catch (err) { const value = envJson[envVarName];
envJsonFileAsObject = {}; if (typeof value === 'object') {
return 'base64Object:' + this.encodeBase64(value);
}
return value;
} catch (error) {
return undefined;
} }
if (envJsonFileAsObject.hasOwnProperty(wantedEnvVar)) {
envVarFromEnvJsonFile = envJsonFileAsObject[wantedEnvVar];
} }
// docker secret check private getFromDockerSecret(envVarName: string): string | undefined {
if ( const secretPath = `/run/secrets/${envVarName}`;
plugins.smartfile.fs.isDirectory('/run') && if (plugins.smartfile.fs.fileExistsSync(secretPath)) {
plugins.smartfile.fs.isDirectory('/run/secrets') && return plugins.smartfile.fs.toStringSync(secretPath);
plugins.smartfile.fs.fileExistsSync(`/run/secrets/${wantedEnvVar}`) }
) { return undefined;
envVarFromDockerSecret = plugins.smartfile.fs.toStringSync(`/run/secrets/${wantedEnvVar}`);
} }
// docker secret.json private getFromDockerSecretJson(envVarName: string): string | undefined {
if ( if (plugins.smartfile.fs.isDirectory('/run/secrets')) {
plugins.smartfile.fs.isDirectory('/run') &&
plugins.smartfile.fs.isDirectory('/run/secrets')
) {
const availableSecrets = plugins.smartfile.fs.listAllItemsSync('/run/secrets'); const availableSecrets = plugins.smartfile.fs.listAllItemsSync('/run/secrets');
for (const secret of availableSecrets) { for (const secret of availableSecrets) {
if (secret.includes('secret.json') && !envVarFromDockerSecret) { if (secret.includes('secret.json')) {
const secretObject = plugins.smartfile.fs.toObjectSync(`/run/secrets/${secret}`); const secretObject = plugins.smartfile.fs.toObjectSync(`/run/secrets/${secret}`);
envVarFromDockerSecret = secretObject[wantedEnvVar]; const value = secretObject[envVarName];
if (typeof value === 'object') {
return 'base64Object:' + this.encodeBase64(value);
}
return value;
} }
} }
} }
return undefined;
}
// warn if there is more than one candidate private encodeBase64(data: any): string {
const availableCcandidates: any[] = []; const jsonString = JSON.stringify(data);
[ return Buffer.from(jsonString).toString('base64');
envVarFromEnvironmentVariable,
envVarFromEnvJsonFile,
envVarFromDockerSecret,
dockerSecretJson
].forEach(candidate => {
if (candidate) {
availableCcandidates.push(candidate);
}
});
if (availableCcandidates.length > 1) {
this.logger.log(
'warn',
`found multiple candidates for ${wantedEnvVar} Choosing in the order of envVar, envFileVar, dockerSecret, dockerSecretJson`
);
console.log(availableCcandidates);
} }
switch (true) { private decodeBase64(encodedString: string): any {
case !!envVarFromEnvironmentVariable: const decodedString = Buffer.from(encodedString, 'base64').toString('utf-8');
this.logger.log('ok', `found ${wantedEnvVar} as environment variable`); return JSON.parse(decodedString);
return envVarFromEnvironmentVariable;
case !!envVarFromEnvJsonFile:
this.logger.log('ok', `found ${wantedEnvVar} as env.json variable`);
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;
} }
} }
/**
* gets the required env values
*/
private getRequiredEnvVars = () => {
let qenvFile: any = {};
if (plugins.smartfile.fs.fileExistsSync(this.qenvFilePathAbsolute)) {
qenvFile = plugins.smartfile.fs.toObjectSync(this.qenvFilePathAbsolute);
}
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]);
}
}
};
/**
* gets the available env vars
*/
private getAvailableEnvVars = () => {
for (const requiredEnvVar of this.requiredEnvVars) {
const chosenVar = this.getEnvVarOnDemand(requiredEnvVar);
if (chosenVar) {
this.availableEnvVars.push(requiredEnvVar);
this.keyValueObject[requiredEnvVar] = chosenVar;
}
}
};
/**
* gets missing env vars
*/
private getMissingEnvVars = (): string[] => {
const missingEnvVars: string[] = [];
for (const envVar of this.requiredEnvVars) {
if (!this.availableEnvVars.includes(envVar)) {
missingEnvVars.push(envVar);
}
}
return missingEnvVars;
};
}

View File

@ -4,7 +4,7 @@ import * as path from 'path';
export { path }; export { path };
// @pushrocks scope // @pushrocks scope
import * as smartfile from '@pushrocks/smartfile'; import * as smartfile from '@push.rocks/smartfile';
import * as smartlog from '@pushrocks/smartlog'; import * as smartlog from '@push.rocks/smartlog';
export { smartfile, smartlog }; export { smartfile, smartlog };

11
tsconfig.json Normal file
View File

@ -0,0 +1,11 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false,
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "nodenext",
"esModuleInterop": true,
"verbatimModuleSyntax": true,
}
}

View File

@ -1,17 +0,0 @@
{
"extends": ["tslint:latest", "tslint-config-prettier"],
"rules": {
"semicolon": [true, "always"],
"no-console": false,
"ordered-imports": false,
"object-literal-sort-keys": false,
"member-ordering": {
"options":{
"order": [
"static-method"
]
}
}
},
"defaultSeverity": "warning"
}