Skip to content

Base version of the nodeJs cli #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 21, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ install:
sudo apt-get update
sudo apt-get install dotnet-dev-1.0.0-rc4-004769 -y
script:
- npm install
- dotnet clean openapi-diff/OpenApiDiff.sln
- dotnet restore openapi-diff/OpenApiDiff.sln
- dotnet build -c debug openapi-diff/OpenApiDiff.sln /nologo /clp:NoSummary
Expand Down
37 changes: 37 additions & 0 deletions cli.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#!/usr/bin/env node

// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

'use strict';

var yargs = require('yargs'),
os = require('os'),
log = require('./lib/util/logging');

var defaultLogDir = log.directory;
var logFilepath = log.filepath;
var packageVersion = require('./package.json').version;

yargs
.version(packageVersion)
.commandDir('lib/commands')
.option('h', { alias: 'help' })
.option('l', {
alias: 'logLevel',
describe: 'Set the logging level for console.',
choices: ['off', 'json', 'error', 'warn', 'info', 'verbose', 'debug', 'silly'],
default: 'warn'
})
.option('f', {
alias: 'logFilepath',
describe: `Set the log file path. It must be an absolute filepath. ` +
`By default the logs will stored in a timestamp based log file at "${defaultLogDir}".`
})
.global(['h', 'l', 'f'])
.help()
.argv;

if (yargs.argv._.length === 0 && yargs.argv.h === false) {
yargs.coerce('help', function (arg) { return true; }).argv;
}
17 changes: 17 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

'use strict';

var validate = require('./lib/validate');
var utils = require('./lib/util/utils');

// Easy to use methods from validate.js
exports.log = require('./lib/util/logging');
exports.detectChnages = validate.detectChnages;

// Classes
exports.OpenApiDiff = require('./lib/validators/OpenApiDiff');

// Constants
exports.Constants = require('./lib/util/constants');
23 changes: 23 additions & 0 deletions lib/commands/oad.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// 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 log = require('../util/logging'),
validate = require('../validate');

exports.command = 'oad <old-spec> <new-spec>';

exports.describe = 'Detects breaking changes between old and new open api specification.';

exports.handler = function (argv) {
log.debug(argv);
let oldSpec = argv.oldSpec;
let newSpec = argv.newSpec;
let vOptions = {};
vOptions.consoleLogLevel = argv.logLevel;
vOptions.logFilepath = argv.f;

return validate.detectChanges(oldSpec, newSpec, vOptions);
}

exports = module.exports;
35 changes: 35 additions & 0 deletions lib/scripts/postInstall.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// 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 execSync = require('child_process').execSync;

/**
* @class
* Open API Diff class.
*/
class PostInstall {

constructor() {
}

installAutoRest() {
try {
// let cmd = `npm install -g autorest`;
// let result = execSync(cmd, { encoding: 'utf8' });
let cmd = `autorest --version=latest`;
let result = execSync(cmd, { encoding: 'utf8' });
console.log(result);
result = execSync(`which autorest`, { encoding: 'utf8' });
console.log(result);
} catch (err) {
throw new Error(`An error occurred while installing AutoRest: ${util.inspect(err, { depth: null })}.`);
}
}
}

let postInstall = new PostInstall();
postInstall.installAutoRest();

module.exports = PostInstall;
60 changes: 60 additions & 0 deletions lib/util/constants.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

'use strict';

var Constants = {
constraints: ['minLength', 'maxLength', 'minimum', 'maximum', 'enum', 'maxItems', 'minItems', 'uniqueItems', 'multipleOf', 'pattern'],
xmsExamples: 'x-ms-examples',
exampleInSpec: 'example-in-spec',
BodyParameterValid: 'BODY_PARAMETER_VALID',
xmsSkipUrlEncoding: 'x-ms-skip-url-encoding',
Errors: 'Errors',
Warnings: 'Warnings',
ErrorCodes: {
InternalError: 'INTERNAL_ERROR',
InitializationError: 'INITIALIZATION_ERROR',
ResolveSpecError: 'RESOLVE_SPEC_ERROR',
RefNotFoundError: 'REF_NOTFOUND_ERROR',
JsonParsingError: 'JSON_PARSING_ERROR',
RequiredParameterExampleNotFound: 'REQUIRED_PARAMETER_EXAMPLE_NOT_FOUND',
ErrorInPreparingRequest: 'ERROR_IN_PREPARING_REQUEST',
XmsExampleNotFoundError: 'X-MS-EXAMPLE_NOTFOUND_ERROR',
ResponseValidationError: 'RESPONSE_VALIDATION_ERROR',
RequestValidationError: 'REQUEST_VALIDATION_ERROR',
ResponseBodyValidationError: 'RESPONSE_BODY_VALIDATION_ERROR',
ResponseStatusCodeNotInExample: 'RESPONSE_STATUS_CODE_NOT_IN_EXAMPLE',
ResponseStatusCodeNotInSpec: 'RESPONSE_STATUS_CODE_NOT_IN_SPEC',
ResponseSchemaNotInSpec: 'RESPONSE_SCHEMA_NOT_IN_SPEC',
RequiredParameterNotInExampleError: 'REQUIRED_PARAMETER_NOT_IN_EXAMPLE_ERROR',
BodyParameterValidationError: 'BODY_PARAMETER_VALIDATION_ERROR',
TypeValidationError: 'TYPE_VALIDATION_ERROR',
ConstraintValidationError: 'CONSTRAINT_VALIDATION_ERROR',
StatuscodeNotInExampleError: 'STATUS_CODE_NOT_IN_EXAMPLE_ERROR',
SemanticValidationError: 'SEMANTIC_VALIDATION_ERROR',
MultipleOperationsFound: 'MULTIPLE_OPERATIONS_FOUND',
NoOperationFound: 'NO_OPERATION_FOUND',
IncorrectInput: 'INCORRECT_INPUT',
PotentialOperationSearchError: 'POTENTIAL_OPERATION_SEARCH_ERROR',
PathNotFoundInRequestUrl: "PATH_NOT_FOUND_IN_REQUEST_URL",
OperationNotFoundInCache: "OPERATION_NOT_FOUND_IN_CACHE",
OperationNotFoundInCacheWithVerb: "OPERATION_NOT_FOUND_IN_CACHE_WITH_VERB", // Implies we found correct api-version + provider in cache
OperationNotFoundInCacheWithApi: "OPERATION_NOT_FOUND_IN_CACHE_WITH_API", // Implies we found correct provider in cache
OperationNotFoundInCacheWithProvider: "OPERATION_NOT_FOUND_IN_CACHE_WITH_PROVIDER" // Implies we never found correct provider in cache
},
EnvironmentVariables: {
ClientId: 'CLIENT_ID',
Domain: 'DOMAIN',
ApplicationSecret: 'APPLICATION_SECRET',
AzureSubscriptionId: 'AZURE_SUBSCRIPTION_ID',
AzureLocation: 'AZURE_LOCATION',
AzureResourcegroup: 'AZURE_RESOURCE_GROUP'
},
unknownResourceProvider: 'microsoft.unknown',
unknownApiVersion: 'unknown-api-version',
knownTitleToResourceProviders: {
'ResourceManagementClient': 'Microsoft.Resources'
}
};

exports = module.exports = Constants;
124 changes: 124 additions & 0 deletions lib/util/logging.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

'use strict';

var winston = require('winston'),
path = require('path'),
fs = require('fs'),
os = require('os'),
logDir = path.resolve(os.homedir(), 'oad_output');

var currentLogFile;

/*
* Provides current time in custom format that will be used in naming log files. Example:'20140820_151113'
* @return {string} Current time in a custom string format
*/
function getTimeStamp() {
// We pad each value so that sorted directory listings show the files in chronological order
function pad(number) {
if (number < 10) {
return '0' + number;
}

return number;
}

var now = new Date();
return pad(now.getFullYear())
+ pad(now.getMonth() + 1)
+ pad(now.getDate())
+ "_"
+ pad(now.getHours())
+ pad(now.getMinutes())
+ pad(now.getSeconds());
}
var customLogLevels = {
off: 0,
json: 1,
error: 2,
warn: 3,
info: 4,
verbose: 5,
debug: 6,
silly: 7
};

var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)({
level: 'warn',
colorize: true,
prettyPrint: true,
humanReadableUnhandledException: true
})
],
levels: customLogLevels
});

Object.defineProperties(logger, {
'consoleLogLevel': {
enumerable: true,
get: function () { return this.transports.console.level; },
set: function (level) {
if (!level) {
level = 'warn';
}
let validLevels = Object.keys(customLogLevels);
if (!validLevels.some(function (item) { return item === level; })) {
throw new Error(`The logging level provided is "${level}". Valid values are: "${validLevels}".`);
}
this.transports.console.level = level;
return;
}
},
'directory': {
enumerable: true,
get: function () {
return logDir;
},
set: function (logDirectory) {
if (!logDirectory || logDirectory && typeof logDirectory.valueOf() !== 'string') {
throw new Error('logDirectory cannot be null or undefined and must be of type "string".');
}

if (!fs.existsSync(logDirectory)) {
fs.mkdirSync(logDirectory);
}
logDir = logDirectory;
return;
}
},
'filepath': {
enumerable: true,
get: function () {
if (!currentLogFile) {
let filename = `validate_log_${getTimeStamp()}.log`;
currentLogFile = path.join(this.directory, filename);
}

return currentLogFile;
},
set: function (logFilePath) {
if (!logFilePath || logFilePath && typeof logFilePath.valueOf() !== 'string') {
throw new Error('filepath cannot be null or undefined and must be of type string. It must be an absolute file path.')
}
currentLogFile = logFilePath;
this.directory = path.dirname(logFilePath);
if (!this.transports.file) {
this.add(winston.transports.File, {
level: 'silly',
colorize: false,
silent: false,
prettyPrint: true,
json: false,
filename: logFilePath
});
}
return;
}
}
});

module.exports = logger;
Loading