diff --git a/.gitignore b/.gitignore index 75d0a52fa21e..1f995a5b6470 100644 --- a/.gitignore +++ b/.gitignore @@ -110,3 +110,8 @@ warnings.txt !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json + +*.js +*.d.ts +*.js.map +*.d.ts.map \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index ef3625f33d6b..d5c723118a43 100644 --- a/.travis.yml +++ b/.travis.yml @@ -36,22 +36,26 @@ script: - >- if [[ $MODE == 'semantic' ]]; then npm install + npm run tsc node scripts/semanticValidation.js fi - >- if [[ $MODE == 'model' ]]; then npm install + npm run tsc node scripts/modelValidation.js fi - >- if [[ $MODE == 'BreakingChange' ]]; then scripts/install-dotnet.sh npm install - node -- scripts/breaking-change.js + npm run tsc + node scripts/breaking-change.ts fi - >- if [[ $MODE == 'lintdiff' ]]; then scripts/install-dotnet.sh npm install + npm run tsc node scripts/momentOfTruth.js && node scripts/momentOfTruthPostProcessing.js fi diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 003bf46bbc9e..17c93f53b932 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -41,7 +41,7 @@ jobs: displayName: 'npm install' inputs: verbose: false - - script: 'node scripts/semanticValidation.js' + - script: 'npm run tsc && node scripts/semanticValidation.js' displayName: 'Semantic Validation' - job: "ModelValidation" @@ -52,7 +52,7 @@ jobs: displayName: 'npm install' inputs: verbose: false - - script: 'node scripts/modelValidation.js' + - script: 'npm run tsc && node scripts/modelValidation.js' displayName: 'Model Validation' - job: "Avocado" @@ -78,7 +78,7 @@ jobs: displayName: 'npm install' inputs: verbose: false - - script: 'node scripts/breaking-change.js' + - script: 'npm run tsc && node scripts/breaking-change.js' displayName: 'Breaking Changes' - job: "LintDiff" @@ -94,7 +94,7 @@ jobs: verbose: false - script: 'scripts/install-dotnet.sh' displayName: 'install .Net' - - script: 'node scripts/momentOfTruth.js && node scripts/momentOfTruthPostProcessing.js' + - script: 'npm run tsc && node scripts/momentOfTruth.js && node scripts/momentOfTruthPostProcessing.js' displayName: 'LintDiff' - job: "SDK" diff --git a/package.json b/package.json index 264465a762ea..f76623b5e517 100644 --- a/package.json +++ b/package.json @@ -10,28 +10,28 @@ "description": "Tests for Azure REST API Specifications", "license": "MIT", "devDependencies": { - "@azure/avocado": "^0.3.0", - "@azure/oad": "^0.4.3", - "@microsoft.azure/async-io": "^1.0.21", - "@microsoft.azure/literate": "^1.0.21", - "@microsoft.azure/polyfill": "^1.0.17", - "@ts-common/commonmark-to-markdown": "^1.1.10", - "@ts-common/fs": "0.1.1", - "@types/js-yaml": "^3.12.0", - "fs-extra": "^3.0.1", - "glob": "^5.0.14", - "js-yaml": "^3.13.0", - "json-schema-ref-parser": "^3.1.2", + "@azure/avocado": "^0.3.3", + "@azure/oad": "^0.5.1", + "@microsoft.azure/async-io": "^2.0.21", + "@microsoft.azure/literate": "^1.0.25", + "@microsoft.azure/polyfill": "^1.0.19", + "@octokit/rest": "^16.24.1", + "@ts-common/commonmark-to-markdown": "^1.2.0", + "@ts-common/fs": "0.2.0", + "@types/fs-extra": "^5.0.5", + "@types/js-yaml": "^3.12.1", + "@types/request": "^2.48.1", + "fs-extra": "^7.0.1", + "glob": "^7.1.3", + "js-yaml": "^3.13.1", + "json-schema-ref-parser": "^6.1.0", "mocha": "*", - "oav": "^0.16.1", - "request": "^2.61.0", - "request-promise-native": "^1.0.5", - "ts-node": "^8.0.3", - "typescript": "^3.2.4", - "z-schema": "^3.25.1" - }, - "dependencies": { - "@octokit/rest": "^15.2.6" + "oav": "^0.18.1", + "request": "^2.88.0", + "request-promise-native": "^1.0.7", + "ts-node": "^8.1.0", + "typescript": "^3.4.3", + "z-schema": "^4.0.2" }, "homepage": "https://github.com/azure/azure-rest-api-specs", "repository": { @@ -42,7 +42,7 @@ "url": "http://github.com/azure/azure-rest-api-specs/issues" }, "scripts": { - "test": "mocha -t 500000 --reporter min", + "test": "tsc && mocha -t 500000 --reporter min", "oav": "oav", "tsc": "tsc", "multiapi": "ts-node ./scripts/multiapi.ts" diff --git a/scripts/breaking-change.js b/scripts/breaking-change.ts similarity index 83% rename from scripts/breaking-change.js rename to scripts/breaking-change.ts index 08fea52dfa30..70825c3d42da 100644 --- a/scripts/breaking-change.js +++ b/scripts/breaking-change.ts @@ -1,16 +1,20 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License in the project root for license information. -'use strict'; -const utils = require('../test/util/utils'), - path = require('path'), - fs = require('fs-extra'), - os = require('os'), - exec = require('util').promisify(require('child_process').exec), - oad = require('@azure/oad'); +import * as stringMap from '@ts-common/string-map' +import * as tsUtils from './ts-utils' +import * as utils from '../test/util/utils' +import * as path from 'path' +import * as fs from 'fs-extra' +import * as os from 'os' +import * as childProcess from 'child_process' +import * as oad from '@azure/oad' +import * as util from 'util' + +const exec = util.promisify(childProcess.exec) // This map is used to store the mapping between files resolved and stored location -var resolvedMapForNewSpecs = {}; +var resolvedMapForNewSpecs: stringMap.MutableStringMap = {}; let outputFolder = path.join(os.tmpdir(), "resolved"); // Used to enable running script outside TravisCI for debugging let isRunningInTravisCI = process.env.TRAVIS === 'true'; @@ -20,7 +24,7 @@ const headerText = ` |-|------|----------|---------| `; -function iconFor(type) { +function iconFor(type: unknown) { if (type === 'Error') { return ':x:'; } else if (type === 'Warning') { @@ -32,26 +36,33 @@ function iconFor(type) { } } -function shortName(filePath) { +function shortName(filePath: string) { return `${path.basename(path.dirname(filePath))}/​${path.basename(filePath)}`; } -function tableLine(filePath, diff) { +type Diff = { + readonly type: unknown + readonly id: string + readonly code: unknown + readonly message: unknown +} + +function tableLine(filePath: string, diff: Diff) { return `|${iconFor(diff['type'])}|[${diff['type']} ${diff['id']} - ${diff['code']}](https://github.com/Azure/openapi-diff/blob/master/docs/rules/${diff['id']}.md)|[${shortName(filePath)}](${blobHref(filePath)} "${filePath}")|${diff['message']}|\n`; } -function blobHref(file) { +function blobHref(file: unknown) { return `https://github.com/${process.env.TRAVIS_PULL_REQUEST_SLUG}/blob/${process.env.TRAVIS_PULL_REQUEST_SHA}/${file}`; } /** * Compares old and new specifications for breaking change detection. * - * @param {string} oldSpec Path to the old swagger specification file. + * @param oldSpec Path to the old swagger specification file. * - * @param {string} newSpec Path to the new swagger specification file. + * @param newSpec Path to the new swagger specification file. */ -async function runOad(oldSpec, newSpec) { +async function runOad(oldSpec: string, newSpec: string) { if (oldSpec === null || oldSpec === undefined || typeof oldSpec.valueOf() !== 'string' || !oldSpec.trim().length) { throw new Error('oldSpec is a required parameter of type "string" and it cannot be an empty string.'); } @@ -65,7 +76,7 @@ async function runOad(oldSpec, newSpec) { console.log(`New Spec: "${newSpec}"`); console.log(`>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>`); - let result = await oad.compare(oldSpec, newSpec, { consoleLogLevel: 'warn', json: true }); + let result = await oad.compare(oldSpec, newSpec, { consoleLogLevel: 'warn' }); console.log(result); if (!result) { @@ -81,9 +92,9 @@ async function runOad(oldSpec, newSpec) { /** * Processes the given swagger and stores the resolved swagger on to disk * - * @param {string} swaggerPath Path to the swagger specification file. + * @param swaggerPath Path to the swagger specification file. */ -async function processViaAutoRest(swaggerPath) { +async function processViaAutoRest(swaggerPath: string) { if (swaggerPath === null || swaggerPath === undefined || typeof swaggerPath.valueOf() !== 'string' || !swaggerPath.trim().length) { throw new Error('swaggerPath is a required parameter of type "string" and it cannot be an empty string.'); } @@ -115,10 +126,10 @@ async function runScript() { console.log(swaggersToProcess); console.log('Finding new swaggers...') - let newSwaggers = []; + let newSwaggers: unknown[] = []; if (isRunningInTravisCI && swaggersToProcess.length > 0) { newSwaggers = await utils.doOnBranch(utils.getTargetBranch(), async () => { - return swaggersToProcess.filter(s => !fs.existsSync(s)) + return swaggersToProcess.filter((s: string) => !fs.existsSync(s)) }); } @@ -133,7 +144,7 @@ async function runScript() { console.dir(resolvedMapForNewSpecs); let errors = 0, warnings = 0; - const diffFiles = {}; + const diffFiles: stringMap.MutableStringMap = {}; const newFiles = []; for (const swagger of swaggersToProcess) { @@ -144,8 +155,9 @@ async function runScript() { continue; } - if (resolvedMapForNewSpecs[swagger]) { - const diffs = await runOad(swagger, resolvedMapForNewSpecs[swagger]); + const resolved = resolvedMapForNewSpecs[swagger] + if (resolved) { + const diffs = await runOad(swagger, resolved); if (diffs) { diffFiles[swagger] = diffs; for (const diff of diffs) { @@ -189,7 +201,7 @@ async function runScript() { diffFileNames.sort(); for (const swagger of diffFileNames) { - const diffs = diffFiles[swagger]; + const diffs = tsUtils.asNonUndefined(diffFiles[swagger]); diffs.sort((a, b) => { if (a.type === b.type) { return a.id.localeCompare(b.id); @@ -227,7 +239,7 @@ async function runScript() { } // magic starts here -runScript().then(success => { +runScript().then(() => { console.log(`Thanks for using breaking change tool to review.`); console.log(`If you encounter any issue(s), please open issue(s) at https://github.com/Azure/openapi-diff/issues .`); }).catch(err => { diff --git a/scripts/momentOfTruth.js b/scripts/momentOfTruth.ts similarity index 76% rename from scripts/momentOfTruth.js rename to scripts/momentOfTruth.ts index 754e26a9e38e..70f89f16f2d3 100644 --- a/scripts/momentOfTruth.js +++ b/scripts/momentOfTruth.ts @@ -1,22 +1,30 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. -'use strict'; - -const exec = require('child_process').exec, - path = require('path'), - utils = require('../test/util/utils'), - fs = require('fs'); +import * as stringMap from '@ts-common/string-map' +import * as tsUtils from './ts-utils' +import { exec } from 'child_process' +import * as path from 'path' +import * as utils from '../test/util/utils' +import * as fs from 'fs' let configsToProcess = utils.getConfigFilesChangedInPR(); let pullRequestNumber = utils.getPullRequestNumber(); let linterCmd = `npx autorest --validation --azure-validator --message-format=json `; var filename = `${pullRequestNumber}.json`; var logFilepath = path.join(getLogDir(), filename); -var finalResult = {}; -finalResult["pullRequest"] = pullRequestNumber; -finalResult["repositoryUrl"] = utils.getRepoUrl(); -finalResult["files"] = {}; + +type FinalResult = { + readonly pullRequest: unknown, + readonly repositoryUrl: unknown, + readonly files: stringMap.MutableStringMap> +} + +var finalResult: FinalResult = { + pullRequest: pullRequestNumber, + repositoryUrl: utils.getRepoUrl(), + files: {} +} // Creates and returns path to the logging directory function getLogDir() { @@ -39,12 +47,12 @@ function createLogFile() { } //appends the content to the log file -function writeContent(content) { +function writeContent(content: unknown) { fs.writeFileSync(logFilepath, content); } // Executes linter on given swagger path and returns structured JSON of linter output -async function getLinterResult(swaggerPath) { +async function getLinterResult(swaggerPath: string|null|undefined) { if (swaggerPath === null || swaggerPath === undefined || typeof swaggerPath.valueOf() !== 'string' || !swaggerPath.trim().length) { throw new Error('swaggerPath is a required parameter of type "string" and it cannot be an empty string.'); } @@ -56,7 +64,7 @@ async function getLinterResult(swaggerPath) { let cmd = "npx autorest --reset && " + linterCmd + swaggerPath; console.log(`Executing: ${cmd}`); const { err, stdout, stderr } = await new Promise(res => exec(cmd, { encoding: 'utf8', maxBuffer: 1024 * 1024 * 64 }, - (err, stdout, stderr) => res({ err: err, stdout: stdout, stderr: stderr }))); + (err: unknown, stdout: unknown, stderr: unknown) => res({ err: err, stdout: stdout, stderr: stderr }))); if (err && stderr.indexOf("Process() cancelled due to exception") !== -1) { console.error(`AutoRest exited with code ${err.code}`); @@ -86,7 +94,7 @@ async function getLinterResult(swaggerPath) { }; // Run linter tool -async function runTools(swagger, beforeOrAfter) { +async function runTools(swagger: string, beforeOrAfter: string) { console.log(`Processing "${swagger}":`); const linterErrors = await getLinterResult(swagger); console.log(linterErrors); @@ -94,14 +102,16 @@ async function runTools(swagger, beforeOrAfter) { }; // Updates final result json to be written to the output file -async function updateResult(spec, errors, beforeOrAfter) { - if (!finalResult['files'][spec]) { - finalResult['files'][spec] = {}; +async function updateResult(spec: string, errors: unknown, beforeOrAfter: string) { + const files = finalResult['files'] + if (!files[spec]) { + files[spec] = {}; } - if (!finalResult['files'][spec][beforeOrAfter]) { - finalResult['files'][spec][beforeOrAfter] = {}; + const filesSpec = tsUtils.asNonUndefined(files[spec]) + if (!filesSpec[beforeOrAfter]) { + filesSpec[beforeOrAfter] = {}; } - finalResult['files'][spec][beforeOrAfter] = errors; + filesSpec[beforeOrAfter] = errors; } //main function diff --git a/scripts/ts-utils.ts b/scripts/ts-utils.ts new file mode 100644 index 000000000000..9b9dbb94a898 --- /dev/null +++ b/scripts/ts-utils.ts @@ -0,0 +1,4 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License in the project root for license information. + +export const asNonUndefined = (v: T|undefined) => v as T \ No newline at end of file diff --git a/test/util/utils.js b/test/util/utils.ts similarity index 68% rename from test/util/utils.js rename to test/util/utils.ts index 8b10865e470c..0b854382c084 100644 --- a/test/util/utils.js +++ b/test/util/utils.ts @@ -1,42 +1,43 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License in the project root for license information. -'use strict'; -var assert = require("assert"), - os = require('os'), - fs = require('fs-extra'), - glob = require('glob'), - path = require('path'), - z = require('z-schema'), - YAML = require('js-yaml'), - request = require('request'), - util = require('util'), - execSync = require('child_process').execSync; - -const asyncJsonRequest = url => new Promise((res, rej) => request({ url: url, json: true }, (error, _, body) => error ? rej(error) : res(body))); - -exports = module.exports; - -exports.extensionSwaggerSchemaUrl = "https://raw.githubusercontent.com/Azure/autorest/master/schema/swagger-extensions.json"; -exports.swaggerSchemaUrl = "http://json.schemastore.org/swagger-2.0"; -exports.swaggerSchemaAltUrl = "http://swagger.io/v2/schema.json"; -exports.schemaUrl = "http://json-schema.org/draft-04/schema"; -exports.exampleSchemaUrl = "https://raw.githubusercontent.com/Azure/autorest/master/schema/example-schema.json"; -exports.compositeSchemaUrl = "https://raw.githubusercontent.com/Azure/autorest/master/schema/composite-swagger.json"; - -exports.isWindows = (process.platform.lastIndexOf('win') === 0); -exports.prOnly = undefined !== process.env['PR_ONLY'] ? process.env['PR_ONLY'] : 'false'; - -exports.globPath = path.join(__dirname, '../', '../', '/specification/**/*.json'); -exports.swaggers = glob.sync(exports.globPath, { ignore: ['**/examples/**/*.json', '**/quickstart-templates/*.json', '**/schema/*.json'] }); -exports.exampleGlobPath = path.join(__dirname, '../', '../', '/specification/**/examples/**/*.json'); -exports.examples = glob.sync(exports.exampleGlobPath); -exports.readmes = glob.sync(path.join(__dirname, '../', '../', '/specification/**/readme.md')); +import * as tsUtils from '../../scripts/ts-utils' +import * as stringMap from '@ts-common/string-map' +import * as os from 'os' +import * as fs from 'fs-extra' +import * as glob from 'glob' +import * as path from 'path' +const z = require('z-schema') +import * as YAML from 'js-yaml' +import request = require('request') +import * as util from 'util' +import { execSync } from 'child_process' + +const asyncJsonRequest = (url: string) => new Promise((res, rej) => request( + { url, json: true }, + (error: unknown, _: unknown, body: unknown) => error ? rej(error) : res(body) +)); + +export const extensionSwaggerSchemaUrl = "https://raw.githubusercontent.com/Azure/autorest/master/schema/swagger-extensions.json"; +export const swaggerSchemaUrl = "http://json.schemastore.org/swagger-2.0"; +export const swaggerSchemaAltUrl = "http://swagger.io/v2/schema.json"; +export const schemaUrl = "http://json-schema.org/draft-04/schema"; +export const exampleSchemaUrl = "https://raw.githubusercontent.com/Azure/autorest/master/schema/example-schema.json"; +export const compositeSchemaUrl = "https://raw.githubusercontent.com/Azure/autorest/master/schema/composite-swagger.json"; + +export const isWindows = (process.platform.lastIndexOf('win') === 0); +export const prOnly = undefined !== process.env['PR_ONLY'] ? process.env['PR_ONLY'] : 'false'; + +export const globPath = path.join(__dirname, '../', '../', '/specification/**/*.json'); +export const swaggers = glob.sync(globPath, { ignore: ['**/examples/**/*.json', '**/quickstart-templates/*.json', '**/schema/*.json'] }); +export const exampleGlobPath = path.join(__dirname, '../', '../', '/specification/**/examples/**/*.json'); +export const examples = glob.sync(exampleGlobPath); +export const readmes = glob.sync(path.join(__dirname, '../', '../', '/specification/**/readme.md')); // Remove byte order marker. This catches EF BB BF (the UTF-8 BOM) // because the buffer-to-string conversion in `fs.readFile()` // translates it to FEFF, the UTF-16 BOM. -exports.stripBOM = function stripBOM(content) { +export const stripBOM = function(content: Buffer|string) { if (Buffer.isBuffer(content)) { content = content.toString(); } @@ -50,10 +51,10 @@ exports.stripBOM = function stripBOM(content) { * Parses the json from the given filepath * @returns {string} clr command */ -exports.parseJsonFromFile = async function parseJsonFromFile(filepath) { +export const parseJsonFromFile = async function(filepath: string) { const data = await fs.readFile(filepath, { encoding: 'utf8' }); try { - return YAML.safeLoad(exports.stripBOM(data)); + return YAML.safeLoad(stripBOM(data)); } catch (error) { throw new Error(`swagger "${filepath}" is an invalid JSON.\n${util.inspect(error, { depth: null })}`); } @@ -66,7 +67,7 @@ exports.parseJsonFromFile = async function parseJsonFromFile(filepath) { * If the environment variable is undefined then the method returns 'master' as the default value. * @returns {string} branchName The target branch name. */ -exports.getTargetBranch = function getTargetBranch() { +export const getTargetBranch = function() { console.log(`@@@@@ process.env['TRAVIS_BRANCH'] - ${process.env['TRAVIS_BRANCH']}`); let result = process.env['TRAVIS_BRANCH'] || 'master'; result = result.trim(); @@ -77,13 +78,13 @@ exports.getTargetBranch = function getTargetBranch() { /** * Check out a copy of a branch to a temporary location, execute a function, and then restore the previous state */ -exports.doOnBranch = async function doOnBranch(branch, func) { - exports.fetchBranch(branch); - const branchSha = exports.resolveRef(`origin/${branch}`); +export const doOnBranch = async function(branch: unknown, func: () => Promise) { + fetchBranch(branch); + const branchSha = resolveRef(`origin/${branch}`); const tmpDir = path.join(os.tmpdir(), branchSha); const currentDir = process.cwd(); - exports.checkoutBranch(branch, tmpDir); + checkoutBranch(branch, tmpDir); console.log(`Changing directory and executing the function...`); process.chdir(tmpDir); @@ -99,7 +100,7 @@ exports.doOnBranch = async function doOnBranch(branch, func) { /** * Resolve a ref to its commit hash */ -exports.resolveRef = function resolveRef(ref) { +export const resolveRef = function(ref: unknown) { let cmd = `git rev-parse ${ref}`; console.log(`> ${cmd}`); return execSync(cmd, { encoding: 'utf8' }).trim(); @@ -108,7 +109,7 @@ exports.resolveRef = function resolveRef(ref) { /** * Fetch ref for a branch from the origin */ -exports.fetchBranch = function fetchBranch(branch) { +export const fetchBranch = function(branch: unknown) { let cmds = [ `git remote -vv`, `git branch --all`, @@ -126,7 +127,7 @@ exports.fetchBranch = function fetchBranch(branch) { /** * Checkout a copy of branch to location */ -exports.checkoutBranch = function checkoutBranch(ref, location) { +export const checkoutBranch = function(ref: unknown, location: unknown) { let cmd = `git worktree add -f ${location} origin/${ref}`; console.log(`Checking out a copy of branch ${ref} to ${location}...`); console.log(`> ${cmd}`); @@ -137,7 +138,7 @@ exports.checkoutBranch = function checkoutBranch(ref, location) { * Gets the name of the source branch from which the PR is sent. * @returns {string} branchName The source branch name. */ -exports.getSourceBranch = function getSourceBranch() { +export const getSourceBranch = function() { let cmd = 'git rev-parse --abbrev-ref HEAD'; let result = process.env['TRAVIS_PULL_REQUEST_BRANCH']; console.log(`@@@@@ process.env['TRAVIS_PULL_REQUEST_BRANCH'] - ${process.env['TRAVIS_PULL_REQUEST_BRANCH']}`); @@ -148,7 +149,7 @@ exports.getSourceBranch = function getSourceBranch() { console.log(`An error occurred while getting the current branch ${util.inspect(err, { depth: null })}.`); } } - result = result.trim(); + result = tsUtils.asNonUndefined(result).trim(); console.log(`>>>>> The source branch is: "${result}".`); return result; }; @@ -159,7 +160,7 @@ exports.getSourceBranch = function getSourceBranch() { * https://docs.travis-ci.com/user/environment-variables/#Convenience-Variables * @returns {string} PR number or 'undefined'. */ -exports.getPullRequestNumber = function getPullRequestNumber() { +export const getPullRequestNumber = function() { let result = process.env['TRAVIS_PULL_REQUEST']; console.log(`@@@@@ process.env['TRAVIS_PULL_REQUEST'] - ${process.env['TRAVIS_PULL_REQUEST']}`); @@ -176,7 +177,7 @@ exports.getPullRequestNumber = function getPullRequestNumber() { * https://docs.travis-ci.com/user/environment-variables/#Convenience-Variables * @returns {string} repo name or 'undefined'. */ -exports.getRepoName = function getRepoName() { +export const getRepoName = function() { let result = process.env['TRAVIS_REPO_SLUG']; console.log(`@@@@@ process.env['TRAVIS_REPO_SLUG'] - ${result}`); @@ -189,7 +190,7 @@ exports.getRepoName = function getRepoName() { * https://docs.travis-ci.com/user/environment-variables/#Convenience-Variables * @returns {string} repo name or 'undefined'. */ -exports.getSourceRepoName = function getSourceRepoName() { +export const getSourceRepoName = function() { let result = process.env['TRAVIS_PULL_REQUEST_SLUG']; console.log(`@@@@@ process.env['TRAVIS_PULL_REQUEST_SLUG'] - ${result}`); @@ -201,8 +202,8 @@ exports.getSourceRepoName = function getSourceRepoName() { * Gets the repo URL * @returns {string} repo URL or 'undefined' */ -exports.getRepoUrl = function getRepoUrl() { - let repoName = exports.getRepoName(); +export const getRepoUrl = function() { + let repoName = getRepoName(); return `https://github.com/${repoName}`; }; @@ -211,14 +212,14 @@ exports.getRepoUrl = function getRepoUrl() { * Gets the repo URL from where the PR originated * @returns {string} repo URL or 'undefined' */ -exports.getSourceRepoUrl = function getSourceRepoUrl() { - let repoName = exports.getSourceRepoName(); +export const getSourceRepoUrl = function() { + let repoName = getSourceRepoName(); return `https://github.com/${repoName}`; }; -exports.getTimeStamp = function getTimeStamp() { +export const getTimeStamp = function() { // We pad each value so that sorted directory listings show the files in chronological order - function pad(number) { + function pad(number: any): any { if (number < 10) { return '0' + number; } @@ -240,11 +241,11 @@ exports.getTimeStamp = function getTimeStamp() { * Retrieves list of swagger files to be processed for linting * @returns {Array} list of files to be processed for linting */ -exports.getConfigFilesChangedInPR = function getConfigFilesChangedInPR() { - if (exports.prOnly === 'true') { - let targetBranch, cmd, filesChanged, swaggerFilesInPR; +export const getConfigFilesChangedInPR = function() { + if (prOnly === 'true') { + let targetBranch, cmd, filesChanged; try { - targetBranch = exports.getTargetBranch(); + targetBranch = getTargetBranch(); execSync(`git fetch origin ${targetBranch}`); cmd = `git diff --name-only HEAD $(git merge-base HEAD FETCH_HEAD)`; filesChanged = execSync(cmd, { encoding: 'utf8' }).split('\n'); @@ -277,7 +278,7 @@ exports.getConfigFilesChangedInPR = function getConfigFilesChangedInPR() { throw err; } } else { - return exports.swaggers; + return swaggers; } }; @@ -285,18 +286,18 @@ exports.getConfigFilesChangedInPR = function getConfigFilesChangedInPR() { * Retrieves list of swagger files to be processed for linting * @returns {Array} list of files to be processed for linting */ -exports.getFilesChangedInPR = function getFilesChangedInPR() { - let result = exports.swaggers; - if (exports.prOnly === 'true') { +export const getFilesChangedInPR = function() { + let result = swaggers; + if (prOnly === 'true') { let targetBranch, cmd, filesChanged, swaggerFilesInPR; try { - targetBranch = exports.getTargetBranch(); + targetBranch = getTargetBranch(); execSync(`git fetch origin ${targetBranch}`); cmd = `git diff --name-only HEAD $(git merge-base HEAD FETCH_HEAD)`; filesChanged = execSync(cmd, { encoding: 'utf8' }); console.log('>>>>> Files changed in this PR are as follows:') console.log(filesChanged); - swaggerFilesInPR = filesChanged.split('\n').filter(function (item) { + swaggerFilesInPR = filesChanged.split('\n').filter(function (item: string) { if (item.match(/.*(json|yaml)$/ig) == null || item.match(/.*specification.*/ig) == null) { return false; } @@ -310,13 +311,13 @@ exports.getFilesChangedInPR = function getFilesChangedInPR() { }); console.log(`>>>> Number of swaggers found in this PR: ${swaggerFilesInPR.length}`); - var deletedFiles = swaggerFilesInPR.filter(function (swaggerFile) { + var deletedFiles = swaggerFilesInPR.filter(function (swaggerFile: string) { return !fs.existsSync(swaggerFile); }); console.log('>>>>> Files deleted in this PR are as follows:') console.log(deletedFiles); // Remove files that have been deleted in the PR - swaggerFilesInPR = swaggerFilesInPR.filter(function (x) { return deletedFiles.indexOf(x) < 0 }); + swaggerFilesInPR = swaggerFilesInPR.filter(function (x: string) { return deletedFiles.indexOf(x) < 0 }); result = swaggerFilesInPR; } catch (err) { @@ -330,17 +331,17 @@ exports.getFilesChangedInPR = function getFilesChangedInPR() { * Downloads the remote schemas and initializes the validator with remote references. * @returns {Object} context Provides the schemas in json format and the validator. */ -exports.initializeValidator = async function initializeValidator() { - const context = { - extensionSwaggerSchema: await asyncJsonRequest(exports.extensionSwaggerSchemaUrl), - swaggerSchema: await asyncJsonRequest(exports.swaggerSchemaAltUrl), - exampleSchema: await asyncJsonRequest(exports.exampleSchemaUrl), - compositeSchema: await asyncJsonRequest(exports.compositeSchemaUrl) +export const initializeValidator = async function() { + const context: stringMap.MutableStringMap = { + extensionSwaggerSchema: await asyncJsonRequest(extensionSwaggerSchemaUrl), + swaggerSchema: await asyncJsonRequest(swaggerSchemaAltUrl), + exampleSchema: await asyncJsonRequest(exampleSchemaUrl), + compositeSchema: await asyncJsonRequest(compositeSchemaUrl) }; let validator = new z({ breakOnFirstError: false }); - validator.setRemoteReference(exports.swaggerSchemaUrl, context.swaggerSchema); - validator.setRemoteReference(exports.exampleSchemaUrl, context.exampleSchema); - validator.setRemoteReference(exports.compositeSchemaUrl, context.compositeSchema); + validator.setRemoteReference(swaggerSchemaUrl, context.swaggerSchema); + validator.setRemoteReference(exampleSchemaUrl, context.exampleSchema); + validator.setRemoteReference(compositeSchemaUrl, context.compositeSchema); context.validator = validator; return context; }; diff --git a/tsconfig.json b/tsconfig.json index dbfdac46ba4a..e05dca6c434d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -11,7 +11,7 @@ "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ "sourceMap": true, /* Generates corresponding '.map' file. */ // "outFile": "./", /* Concatenate and emit output to single file. */ - "outDir": "./dist", /* Redirect output structure to the directory. */ + // "outDir": "./dist", /* Redirect output structure to the directory. */ // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ // "composite": true, /* Enable project compilation */ // "removeComments": true, /* Do not emit comments to output. */