Skip to content

Commit

Permalink
feat: export verify, preview function from cli (#33)
Browse files Browse the repository at this point in the history
* feat: export verify, preview function from cli

Signed-off-by: zxypro1 <[email protected]>

* publish: [email protected]

Signed-off-by: zxypro1 <[email protected]>

* publish: [email protected]

Signed-off-by: zxypro1 <[email protected]>

* feat: add flag on header for mock env

Signed-off-by: zxypro1 <[email protected]>

---------

Signed-off-by: zxypro1 <[email protected]>
  • Loading branch information
zxypro1 authored Feb 21, 2024
1 parent 99bd02c commit 20706b9
Show file tree
Hide file tree
Showing 6 changed files with 111 additions and 5 deletions.
3 changes: 2 additions & 1 deletion packages/engine/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@serverless-devs/engine",
"version": "0.0.27",
"version": "0.1.0-beta.2",
"description": "a engine lib for serverless-devs",
"main": "lib/index.js",
"scripts": {
Expand All @@ -27,6 +27,7 @@
"@serverless-devs/logger": "workspace:^",
"@serverless-devs/parse-spec": "workspace:^",
"@serverless-devs/utils": "workspace:^",
"ajv": "^8.12.0",
"chalk": "4.x",
"flatted": "^3.2.7",
"fs-extra": "^11.1.0",
Expand Down
1 change: 1 addition & 0 deletions packages/engine/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { DevsError, ETrackerType, emoji, getAbsolutePath, getRootHome, getUserAg
import { EXIT_CODE } from './constants';
import assert from 'assert';
export * from './types';
export { verify, preview } from './utils';

const debug = require('@serverless-cd/debug')('serverless-devs:engine');

Expand Down
102 changes: 100 additions & 2 deletions packages/engine/src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import Credential from '@serverless-devs/credential';
import { ILoggerInstance } from '@serverless-devs/logger';
import { IAllowFailure } from '@serverless-devs/parse-spec';
import ParseSpec, { IAllowFailure, ISpec } from '@serverless-devs/parse-spec';
import flatted from 'flatted';
import { get, omit, set, map, includes } from 'lodash';
import { get, omit, set, map, includes, isEmpty } from 'lodash';
import fs from 'fs-extra';
import Ajv from 'ajv';
import loadComponent from '@serverless-devs/load-component';

export function getLogPath(filePath: string) {
return `step_${filePath}.log`;
Expand Down Expand Up @@ -61,3 +64,98 @@ export const getAllowFailure = (allowFailure: boolean | IAllowFailure | undefine
}
return false;
};

/**
* Preview command function.
* Notice: only support json output.
* Example:
* ```javascript
* await preview('s.yaml', 's.output', ['-a', 'default', '--debug']);
* ```
* @param {string} filePath template file path
* @param {string} outputFile output file path
* @param {string[]} argv all argv
* @returns {string} preview result
*/
export async function preview(
filePath: string,
outputFile: string,
argv?: string[],
): Promise<string> {
const spec = await new ParseSpec(filePath, { argv }).start();
if (get(spec, 'yaml.use3x')) {
const content = get(spec, 'yaml.content');
const data = omit(content, ['extend']);
if (outputFile) writeOutput(outputFile, data);
return JSON.stringify(data);
}
return `Not support template: ${get(spec, 'yaml.path')}, you can update template to 3.x version`;
};

/**
* Verify command function.
* Notice: only support json output.
* Example:
* ```javascript
* await verify('s.yaml', 's.output', ['-a', 'default', '--debug']);
* ```
* @param {string} filePath template file path
* @param {string} outputFile output file path
* @param {string[]} argv all argv
* @returns {string[]|string} verify result
*/
export async function verify(
filePath: string,
outputFile: string,
argv?: string[],
): Promise<string[]|string> {
const ajv = new Ajv({ allErrors: true });
const logger = console;
const spec = await new ParseSpec(filePath, { argv }).start();
if (get(spec, 'yaml.use3x')) {
const errorsList = await getErrorList(spec, ajv, logger);
let data;
if (!isEmpty(errorsList)) {
data = errorsList;
} else {
data = [`Format verification for [${get(spec, 'yaml.path', '').split('/').pop()}] passed.`];
}
if (outputFile) writeOutput(outputFile, data);
return data;
}

return (`Not support template: ${get(spec, 'yaml.path')}, you can update template to 3.x version`);
}

const writeOutput = (outputFile: string, data: Record<string, any> | string[]) => {
fs.writeFileSync(outputFile, JSON.stringify(data, null, 2), 'utf-8');
fs.appendFileSync(outputFile, '\n');
};

const getErrorList = async (spec: ISpec, ajv: Ajv, logger: any) => {
let errorsList: any[] = [];
for (const i of spec.steps) {
const schema = await getSchema(i.component, logger);
if (isEmpty(schema)) continue;
const validate = ajv.compile(JSON.parse(schema));
if (!validate(i.props)) {
const errors = validate.errors;
if (!errors) continue;
for (const j of errors) {
j.instancePath = i.projectName + '/props' + j.instancePath;
if (j.keyword === 'enum') {
j.message = j.message + ': ' + j.params.allowedValues.join(', ');
}
}
errorsList = errorsList.concat(errors);
}
}
return errorsList;
};

const getSchema = async (componentName: string, logger: any) => {
// const componentLogger = logger.loggerInstance.__generate(componentName);
const instance = await loadComponent(componentName, { logger });
if (!instance || !instance.getSchema) return null;
return instance.getSchema();
};
2 changes: 1 addition & 1 deletion packages/load-application/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@serverless-devs/load-application",
"version": "0.0.11",
"version": "0.0.12-beta.1",
"description": "load application for serverless-devs",
"main": "lib/index.js",
"scripts": {
Expand Down
5 changes: 4 additions & 1 deletion packages/load-application/src/v3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,7 +376,10 @@ class LoadApplication {
dest: this.tempPath,
logger,
extract: true,
headers: registry.getSignHeaders(),
headers: {
...registry.getSignHeaders(),
devs_mock_env: process.env.DEVS_MOCK_ENV || 'false',
},
filename: this.name,
});
}
Expand Down
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

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

0 comments on commit 20706b9

Please sign in to comment.