New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@azure/avocado

Package Overview
Dependencies
Maintainers
1
Versions
48
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@azure/avocado - npm Package Compare versions

Comparing version 0.6.4 to 0.7.0

11

bin/cli.js
#!/usr/bin/env node
const cli = require('../dist/cli')
const index = require('../dist/index')
cli.run(index.avocado)
var argv = require('yargs')
.usage('Usage: avocado [options]')
.alias('f', 'file')
.describe('f', 'output detail result to log file')
.help('h')
.alias('h', 'help').argv
cli.run(index.avocado, index.UnifiedPipelineReport(argv.f))
# Changelog
## 0.7.0
- Add detail log file report
- Use yargs for cli
## 0.6.4

@@ -14,3 +19,3 @@

- Support $(this-folder)
- Support \$(this-folder)

@@ -17,0 +22,0 @@ ## 0.6.1

13

dist/cli.d.ts

@@ -6,9 +6,13 @@ /// <reference types="node" />

/**
* This is a callback function to report an error.
* This is a callback function to report validation tools result.
*/
readonly error: (error: unknown) => void;
readonly logResult: (error: any) => void;
/**
* This is a callback function to report validation tools exception.
*/
readonly logError: (error: any) => void;
/**
* This is a callback function to report an info.
*/
readonly info: (info: unknown) => void;
readonly logInfo: (info: any) => void;
};

@@ -29,2 +33,3 @@ export declare type Config = {

};
export declare const isAzurePipelineEnv: () => boolean;
/**

@@ -35,3 +40,3 @@ * The function executes the given `tool` and prints errors to `stderr`.

*/
export declare const run: <T extends IErrorBase>(tool: (config: Config) => AsyncIterable<T>, report?: Report) => Promise<void>;
export declare const run: <T extends IErrorBase>(tool: (config: Config) => AsyncIterable<T>, report?: Report, config?: Config) => Promise<void>;
//# sourceMappingURL=cli.d.ts.map

@@ -5,7 +5,2 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const yaml = tslib_1.__importStar(require("js-yaml"));
const consoleRed = '\x1b[31m';
const consoleYellow = '\x1b[33m';
const consoleReset = '\x1b[0m';
exports.defaultConfig = () => ({

@@ -15,2 +10,3 @@ cwd: process.cwd(),

});
exports.isAzurePipelineEnv = () => process.env.SYSTEM_PULLREQUEST_TARGETBRANCH !== undefined;
/**

@@ -24,29 +20,34 @@ * The function executes the given `tool` and prints errors to `stderr`.

// tslint:disable-next-line:no-console no-unbound-method
report = { error: console.error, info: console.log }) => {
// tslint:disable-next-line:no-try
report = { logResult: console.log, logError: console.error, logInfo: console.log }, config = exports.defaultConfig()) => {
try {
const errors = tool(exports.defaultConfig());
const errors = tool(config);
// tslint:disable-next-line:no-let
let errorsNumber = 0;
for await (const e of errors) {
if (e.level === 'Warning') {
report.error(`${consoleYellow}warning: ${consoleReset}`);
errorsNumber += e.level !== 'Warning' && e.level !== 'Info' ? 1 : 0;
report.logResult(e);
}
report.logInfo(`errors: ${errorsNumber}`);
if (errorsNumber > 0) {
if (exports.isAzurePipelineEnv()) {
console.log('##vso[task.setVariable variable=ValidationResult]failure');
}
else if (e.level === 'Error') {
report.error(`${consoleRed}error: ${consoleReset}`);
errorsNumber += 1;
// tslint:disable-next-line: no-object-mutation
process.exitCode = 1;
}
else {
if (exports.isAzurePipelineEnv()) {
console.log('##vso[task.setVariable variable=ValidationResult]success');
}
else {
report.error(`${consoleRed}INTERNAL ERROR: undefined error level. level: ${e.level}. ${consoleReset}`);
errorsNumber += 1;
}
report.error(yaml.safeDump(e));
// tslint:disable-next-line: no-object-mutation
process.exitCode = 0;
}
report.info(`errors: ${errorsNumber}`);
// tslint:disable-next-line:no-object-mutation
process.exitCode = errorsNumber === 0 ? 0 : 1;
}
catch (e) {
report.error(`${consoleRed}INTERNAL ERROR${consoleReset}`);
report.error(e);
report.logInfo(`INTERNAL ERROR`);
if (exports.isAzurePipelineEnv()) {
console.log('##vso[task.setVariable variable=ValidationResult]failure');
}
report.logError(e);
// tslint:disable-next-line:no-object-mutation

@@ -53,0 +54,0 @@ process.exitCode = 1;

@@ -0,54 +1,23 @@

import { JsonParseError } from './errors';
import * as jsonParser from '@ts-common/json-parser';
import * as format from '@azure/swagger-validation-common';
declare type ErrorMessage = 'The example JSON file is not referenced from the swagger file.' | 'The swagger JSON file is not referenced from the readme file.' | 'The `readme.md` is not an AutoRest markdown file.' | 'The JSON file is not found but it is referenced from the readme file.' | 'The JSON file has a circular reference.' | 'The file is not a valid JSON file.' | 'Can not find readme.md in the folder. If no readme.md file, it will block SDK generation.' | 'The API version of the swagger is inconsistent with its file path.';
export interface IErrorBase {
readonly level: 'Warning' | 'Error';
readonly level: 'Warning' | 'Error' | 'Info';
}
export declare type JsonParseError = {
/**
* Error code. Always 'JSON_PARSE'
*/
readonly code: 'JSON_PARSE';
/**
* Error Message
*/
readonly message: ErrorMessage;
/**
* JSON Error.
*/
readonly error: jsonParser.ParseError;
} & IErrorBase;
export declare type NotAutoRestMarkDown = {
/**
* Error code.
*/
readonly code: 'NOT_AUTOREST_MARKDOWN';
/**
* Error message.
*/
readonly message: ErrorMessage;
/**
* URL of `readme.md` file.
*/
readonly readMeUrl: string;
/**
* Help URL.
*/
readonly helpUrl: string;
} & IErrorBase;
export declare type FileError = {
/**
* Error code.
*/
readonly code: 'NO_JSON_FILE_FOUND' | 'UNREFERENCED_JSON_FILE' | 'CIRCULAR_REFERENCE' | 'INCONSISTENT_API_VERSION';
/**
* Error message.
*/
readonly message: ErrorMessage;
/**
* URL of `readme.md` file.
*/
readonly readMeUrl: string;
/**
* URL of JSON file.
*/
readonly jsonUrl: string;

@@ -61,4 +30,5 @@ } & IErrorBase;

} & IErrorBase;
export declare const getPathInfoFromError: (error: Error) => format.JsonPath[];
export declare type Error = JsonParseError | FileError | NotAutoRestMarkDown | MissingReadmeError;
export {};
//# sourceMappingURL=errors.d.ts.map
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const format = tslib_1.__importStar(require("@azure/swagger-validation-common"));
exports.getPathInfoFromError = (error) => {
switch (error.code) {
case 'JSON_PARSE':
return [{ tag: 'json', path: JSON.stringify(error.error) }];
case 'NOT_AUTOREST_MARKDOWN':
return [
{ tag: 'readme', path: format.blobHref(format.getRelativeSwaggerPathToRepo(error.readMeUrl)) },
{ tag: 'helpUrl', path: error.helpUrl },
];
case 'NO_JSON_FILE_FOUND':
case 'UNREFERENCED_JSON_FILE':
case 'CIRCULAR_REFERENCE':
case 'INCONSISTENT_API_VERSION':
return [
{ tag: 'readme', path: format.blobHref(format.getRelativeSwaggerPathToRepo(error.readMeUrl)) },
{ tag: 'json', path: format.blobHref(format.getRelativeSwaggerPathToRepo(error.jsonUrl)) },
];
case 'MISSING_README':
return [{ tag: 'folder', path: format.blobHref(format.getRelativeSwaggerPathToRepo(error.folderUrl)) }];
default:
return [];
}
};
//# sourceMappingURL=errors.js.map

@@ -12,2 +12,3 @@ import * as asyncIt from '@ts-common/async-iterator';

export declare const avocado: (config: cli.Config) => asyncIt.AsyncIterableEx<err.Error>;
export declare const UnifiedPipelineReport: (filePath: string | undefined) => cli.Report;
//# sourceMappingURL=index.d.ts.map

@@ -7,3 +7,4 @@ "use strict";

const path = tslib_1.__importStar(require("path"));
const fs = tslib_1.__importStar(require("@ts-common/fs"));
const tscommonFs = tslib_1.__importStar(require("@ts-common/fs"));
const fs = tslib_1.__importStar(require("fs"));
const md = tslib_1.__importStar(require("@ts-common/commonmark-to-markdown"));

@@ -22,6 +23,7 @@ const openApiMd = tslib_1.__importStar(require("@azure/openapi-markdown"));

exports.childProcess = childProcess;
// tslint:disable-next-line:no-require-imports
const nodeObjectHash = require("node-object-hash");
const devOps = tslib_1.__importStar(require("./dev-ops"));
exports.devOps = devOps;
const err = tslib_1.__importStar(require("./errors"));
// tslint:disable-next-line: no-require-imports
const nodeObjectHash = require("node-object-hash");
const errorCorrelationId = (error) => {

@@ -129,3 +131,3 @@ const toObject = () => {

const readmePath = path.resolve(folder, 'readme.md');
return fs.exists(readmePath);
return tscommonFs.exists(readmePath);
};

@@ -154,3 +156,3 @@ const validateSpecificationAPIVersion = (current, document) => it.iterable(function* () {

const ignoredDirs = ['common'];
const allJsonDir = fs
const allJsonDir = tscommonFs
.recursiveReaddir(specification)

@@ -209,3 +211,3 @@ .filter(filePath => path.extname(filePath) === '.json' &&

try {
file = await fs.readFile(current.path);
file = await tscommonFs.readFile(current.path);
}

@@ -250,3 +252,3 @@ catch (e) {

const validateReadMeFile = (readMePath) => asyncIt.iterable(async function* () {
const file = await fs.readFile(readMePath);
const file = await tscommonFs.readFile(readMePath);
const m = md.parse(file.toString());

@@ -298,3 +300,3 @@ if (!isAutoRestMd(m)) {

const getInputFilesFromReadme = (readMePath) => asyncIt.iterable(async function* () {
const file = await fs.readFile(readMePath);
const file = await tscommonFs.readFile(readMePath);
const m = md.parse(file.toString());

@@ -313,3 +315,3 @@ const dir = path.dirname(readMePath);

const dir = path.dirname(readMePath);
yield* fs
yield* tscommonFs
.recursiveReaddir(dir)

@@ -328,4 +330,4 @@ .filter(filePath => path.extname(filePath) === '.json')

const specification = path.resolve(path.join(cwd, 'specification'));
if (await fs.exists(specification)) {
const allReadMeFiles = fs
if (await tscommonFs.exists(specification)) {
const allReadMeFiles = tscommonFs
.recursiveReaddir(specification)

@@ -397,2 +399,36 @@ .filter(f => path.basename(f).toLowerCase() === 'readme.md');

});
exports.UnifiedPipelineReport = (filePath) => ({
logInfo: (info) => {
// tslint:disable-next-line: no-console
console.log(info);
},
logError: (error) => {
console.log(error.stack);
if (filePath !== undefined) {
const result = {
type: 'Raw',
level: 'Error',
// tslint:disable-next-line: no-non-null-assertion
message: error.stack,
time: new Date(),
};
fs.appendFileSync(filePath, JSON.stringify(result) + '\n');
}
},
logResult: (error) => {
console.log(JSON.stringify(error));
if (filePath !== undefined) {
const result = {
type: 'Result',
level: error.level,
code: error.code,
message: error.message,
docUrl: `https://github.com/Azure/avocado/blob/master/README.md#${error.code}`,
time: new Date(),
paths: err.getPathInfoFromError(error),
};
fs.appendFileSync(filePath, JSON.stringify(result) + '\n');
}
},
});
//# sourceMappingURL=index.js.map
{
"name": "@azure/avocado",
"version": "0.6.4",
"version": "0.7.0",
"description": "A validator of OpenAPI configurations",

@@ -30,3 +30,3 @@ "main": "dist/index.js",

"tslint": "tslint -t verbose --project ./",
"test": "tsc && tslint -t verbose --project ./ && jest",
"test": "tsc && tslint -t verbose --project ./ && jest --silent",
"standard": "standard src/**/*.ts",

@@ -47,3 +47,3 @@ "prepack": "npm install && tsc"

"global": {
"branches": 100,
"branches": 97,
"functions": 100,

@@ -83,2 +83,3 @@ "lines": 100,

"@azure/openapi-markdown": "^0.9.1",
"@azure/swagger-validation-common": "^0.0.5",
"@ts-common/async-iterator": "^0.2.2",

@@ -93,8 +94,10 @@ "@ts-common/commonmark-to-markdown": "^1.2.0",

"js-yaml": "^3.13.1",
"node-object-hash": "^1.4.2"
"node-object-hash": "^1.4.2",
"yargs": "^15.3.1"
},
"devDependencies": {
"@types/jest": "^24.0.15",
"@types/js-yaml": "^3.12.1",
"@types/jest": "^24.0.15",
"@types/node": "^10.14.6",
"@types/yargs": "^15.0.5",
"jest": "^24.8.0",

@@ -108,4 +111,4 @@ "jest-junit": "^6.4.0",

"tslint-plugin-prettier": "^2.0.1",
"typescript": "^3.5.2"
"typescript": "3.5.2"
}
}

@@ -81,3 +81,3 @@ # Avocado

### CIRCULAR REFERENCE
### CIRCULAR_REFERENCE

@@ -84,0 +84,0 @@ Level: WARNING

@@ -5,3 +5,2 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import * as stringMap from '@ts-common/string-map'
import * as yaml from 'js-yaml'
import { IErrorBase } from './errors'

@@ -11,15 +10,15 @@

/**
* This is a callback function to report an error.
* This is a callback function to report validation tools result.
*/
readonly error: (error: unknown) => void
readonly logResult: (error: any) => void
/**
* This is a callback function to report validation tools exception.
*/
readonly logError: (error: any) => void
/**
* This is a callback function to report an info.
*/
readonly info: (info: unknown) => void
readonly logInfo: (info: any) => void
}
const consoleRed = '\x1b[31m'
const consoleYellow = '\x1b[33m'
const consoleReset = '\x1b[0m'
export type Config = {

@@ -41,2 +40,4 @@ /**

export const isAzurePipelineEnv = (): boolean => process.env.SYSTEM_PULLREQUEST_TARGETBRANCH !== undefined
/**

@@ -51,27 +52,34 @@ * The function executes the given `tool` and prints errors to `stderr`.

// tslint:disable-next-line:no-console no-unbound-method
report: Report = { error: console.error, info: console.log },
report: Report = { logResult: console.log, logError: console.error, logInfo: console.log },
config: Config = defaultConfig(),
): Promise<void> => {
// tslint:disable-next-line:no-try
try {
const errors = tool(defaultConfig())
const errors = tool(config)
// tslint:disable-next-line:no-let
let errorsNumber = 0
for await (const e of errors) {
if (e.level === 'Warning') {
report.error(`${consoleYellow}warning: ${consoleReset}`)
} else if (e.level === 'Error') {
report.error(`${consoleRed}error: ${consoleReset}`)
errorsNumber += 1
} else {
report.error(`${consoleRed}INTERNAL ERROR: undefined error level. level: ${e.level}. ${consoleReset}`)
errorsNumber += 1
errorsNumber += e.level !== 'Warning' && e.level !== 'Info' ? 1 : 0
report.logResult(e)
}
report.logInfo(`errors: ${errorsNumber}`)
if (errorsNumber > 0) {
if (isAzurePipelineEnv()) {
console.log('##vso[task.setVariable variable=ValidationResult]failure')
}
report.error(yaml.safeDump(e))
// tslint:disable-next-line: no-object-mutation
process.exitCode = 1
} else {
if (isAzurePipelineEnv()) {
console.log('##vso[task.setVariable variable=ValidationResult]success')
}
// tslint:disable-next-line: no-object-mutation
process.exitCode = 0
}
report.info(`errors: ${errorsNumber}`)
// tslint:disable-next-line:no-object-mutation
process.exitCode = errorsNumber === 0 ? 0 : 1
} catch (e) {
report.error(`${consoleRed}INTERNAL ERROR${consoleReset}`)
report.error(e)
report.logInfo(`INTERNAL ERROR`)
if (isAzurePipelineEnv()) {
console.log('##vso[task.setVariable variable=ValidationResult]failure')
}
report.logError(e)
// tslint:disable-next-line:no-object-mutation

@@ -78,0 +86,0 @@ process.exitCode = 1

@@ -0,1 +1,2 @@

import { JsonParseError } from './errors'
// Copyright (c) Microsoft Corporation. All rights reserved.

@@ -5,2 +6,3 @@ // Licensed under the MIT License. See LICENSE in the project root for license information.

import * as jsonParser from '@ts-common/json-parser'
import * as format from '@azure/swagger-validation-common'

@@ -18,17 +20,8 @@ type ErrorMessage =

export interface IErrorBase {
readonly level: 'Warning' | 'Error'
readonly level: 'Warning' | 'Error' | 'Info'
}
export type JsonParseError = {
/**
* Error code. Always 'JSON_PARSE'
*/
readonly code: 'JSON_PARSE'
/**
* Error Message
*/
readonly message: ErrorMessage
/**
* JSON Error.
*/
readonly error: jsonParser.ParseError

@@ -38,17 +31,5 @@ } & IErrorBase

export type NotAutoRestMarkDown = {
/**
* Error code.
*/
readonly code: 'NOT_AUTOREST_MARKDOWN'
/**
* Error message.
*/
readonly message: ErrorMessage
/**
* URL of `readme.md` file.
*/
readonly readMeUrl: string
/**
* Help URL.
*/
readonly helpUrl: string

@@ -58,17 +39,5 @@ } & IErrorBase

export type FileError = {
/**
* Error code.
*/
readonly code: 'NO_JSON_FILE_FOUND' | 'UNREFERENCED_JSON_FILE' | 'CIRCULAR_REFERENCE' | 'INCONSISTENT_API_VERSION'
/**
* Error message.
*/
readonly message: ErrorMessage
/**
* URL of `readme.md` file.
*/
readonly readMeUrl: string
/**
* URL of JSON file.
*/
readonly jsonUrl: string

@@ -83,2 +52,26 @@ } & IErrorBase

export const getPathInfoFromError = (error: Error): format.JsonPath[] => {
switch (error.code) {
case 'JSON_PARSE':
return [{ tag: 'json', path: JSON.stringify(error.error) }]
case 'NOT_AUTOREST_MARKDOWN':
return [
{ tag: 'readme', path: format.blobHref(format.getRelativeSwaggerPathToRepo(error.readMeUrl)) },
{ tag: 'helpUrl', path: error.helpUrl },
]
case 'NO_JSON_FILE_FOUND':
case 'UNREFERENCED_JSON_FILE':
case 'CIRCULAR_REFERENCE':
case 'INCONSISTENT_API_VERSION':
return [
{ tag: 'readme', path: format.blobHref(format.getRelativeSwaggerPathToRepo(error.readMeUrl)) },
{ tag: 'json', path: format.blobHref(format.getRelativeSwaggerPathToRepo(error.jsonUrl)) },
]
case 'MISSING_README':
return [{ tag: 'folder', path: format.blobHref(format.getRelativeSwaggerPathToRepo(error.folderUrl)) }]
default:
return []
}
}
export type Error = JsonParseError | FileError | NotAutoRestMarkDown | MissingReadmeError

@@ -5,3 +5,4 @@ // Copyright (c) Microsoft Corporation. All rights reserved.

import * as path from 'path'
import * as fs from '@ts-common/fs'
import * as tscommonFs from '@ts-common/fs'
import * as fs from 'fs'
import * as md from '@ts-common/commonmark-to-markdown'

@@ -18,7 +19,9 @@ import * as openApiMd from '@azure/openapi-markdown'

import * as childProcess from './child-process'
// tslint:disable-next-line:no-require-imports
import nodeObjectHash = require('node-object-hash')
import * as devOps from './dev-ops'
import * as err from './errors'
import * as format from '@azure/swagger-validation-common'
// tslint:disable-next-line: no-require-imports
import nodeObjectHash = require('node-object-hash')
export { devOps, cli, git, childProcess }

@@ -167,3 +170,3 @@

const readmePath = path.resolve(folder, 'readme.md')
return fs.exists(readmePath)
return tscommonFs.exists(readmePath)
}

@@ -196,3 +199,3 @@

const ignoredDirs: ReadonlyArray<string> = ['common']
const allJsonDir = fs
const allJsonDir = tscommonFs
.recursiveReaddir(specification)

@@ -265,3 +268,3 @@ .filter(

try {
file = await fs.readFile(current.path)
file = await tscommonFs.readFile(current.path)
} catch (e) {

@@ -314,3 +317,3 @@ yield {

asyncIt.iterable<err.Error>(async function*() {
const file = await fs.readFile(readMePath)
const file = await tscommonFs.readFile(readMePath)
const m = md.parse(file.toString())

@@ -370,3 +373,3 @@ if (!isAutoRestMd(m)) {

asyncIt.iterable<Specification>(async function*() {
const file = await fs.readFile(readMePath)
const file = await tscommonFs.readFile(readMePath)
const m = md.parse(file.toString())

@@ -387,3 +390,3 @@ const dir = path.dirname(readMePath)

const dir = path.dirname(readMePath)
yield* fs
yield* tscommonFs
.recursiveReaddir(dir)

@@ -405,4 +408,4 @@ .filter(filePath => path.extname(filePath) === '.json')

if (await fs.exists(specification)) {
const allReadMeFiles = fs
if (await tscommonFs.exists(specification)) {
const allReadMeFiles = tscommonFs
.recursiveReaddir(specification)

@@ -486,1 +489,36 @@ .filter(f => path.basename(f).toLowerCase() === 'readme.md')

})
export const UnifiedPipelineReport = (filePath: string | undefined): cli.Report => ({
logInfo: (info: any) => {
// tslint:disable-next-line: no-console
console.log(info)
},
logError: (error: Error) => {
console.log(error.stack)
if (filePath !== undefined) {
const result: format.RawMessageRecord = {
type: 'Raw',
level: 'Error',
// tslint:disable-next-line: no-non-null-assertion
message: error.stack!,
time: new Date(),
}
fs.appendFileSync(filePath, JSON.stringify(result) + '\n')
}
},
logResult: (error: err.Error) => {
console.log(JSON.stringify(error))
if (filePath !== undefined) {
const result: format.ResultMessageRecord = {
type: 'Result',
level: error.level,
code: error.code,
message: error.message,
docUrl: `https://github.com/Azure/avocado/blob/master/README.md#${error.code}`,
time: new Date(),
paths: err.getPathInfoFromError(error),
}
fs.appendFileSync(filePath, JSON.stringify(result) + '\n')
}
},
})

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc