Skip to content

Commit

Permalink
Merge pull request #231 from snyk/chore/refactoring
Browse files Browse the repository at this point in the history
chore: js -> ts
  • Loading branch information
Kirill89 committed Oct 5, 2018
2 parents b0bbb4d + 8d02572 commit 03ccd68
Show file tree
Hide file tree
Showing 7 changed files with 104 additions and 81 deletions.
64 changes: 34 additions & 30 deletions src/cli/args.js → src/cli/args.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,27 @@
module.exports = args;
import * as abbrev from 'abbrev';

var abbrev = require('abbrev');
var alias = abbrev('copy', 'version', 'debug', 'help', 'quiet', 'interactive',
'dev');
declare interface Global extends NodeJS.Global {
ignoreUnknownCA: boolean;
}

declare const global: Global;

const alias = abbrev('copy', 'version', 'debug', 'help', 'quiet', 'interactive', 'dev');
alias.d = 'debug'; // always make `-d` debug
alias.t = 'test';

function dashToCamelCase(dash) {
return dash.indexOf('-') < 0
? dash
: dash.replace(/-[a-z]/g, function (m) {
return m[1].toUpperCase();
});
: dash.replace(/-[a-z]/g, (m) => m[1].toUpperCase());
}

function args(processargv) {
export default function args(processargv) {
// all arguments after a '--' are taken as is and passed to the next process
// (see the snyk-mvn-plugin or snyk-gradle-plugin)
// these agrs are split by spaces and sent as an array of strings
// allows us to support flags with true or false only
var argv = processargv.slice(2).reduce(function reduce(acc, arg) {
const argv = processargv.slice(2).reduce((acc, arg) => {
if (acc._doubleDashArgs) {
acc._doubleDashArgs.push(arg);
} else if (arg === '--') {
Expand All @@ -34,7 +36,7 @@ function args(processargv) {
if (arg.indexOf('=') === -1) {
acc[arg] = true;
} else {
var parts = arg.split('=');
const parts = arg.split('=');
acc[parts.shift()] = parts.join('=');
}
} else {
Expand All @@ -50,22 +52,22 @@ function args(processargv) {
// by passing `-d` to the cli, we enable the debugging output, but this must
// be as early as possible in the cli logic to capture all the output
if (argv.debug) {
var enable = 'snyk';
let enable = 'snyk';
if (process.env.DEBUG) {
enable += ',' + process.env.DEBUG;
}
require('debug').enable(enable);
}

var debug = require('debug')('snyk');
const debug = require('debug')('snyk');

// this is done after the debug activation line above because we want to see
// the debug messaging when we use the `-d` flag
var cli = require('./commands');
const cli = require('./commands');

// the first argument is the command we'll execute, everything else will be
// an argument to our command, like `snyk help protect`
var command = argv._.shift();
let command: string = argv._.shift();

// alias switcheroo - allows us to have
if (cli.aliases[command]) {
Expand Down Expand Up @@ -94,12 +96,12 @@ function args(processargv) {
// so we need to mangle the commands into this format:
// snyk.config('set', 'api=x')
// snyk.config('get', 'api') // etc
var tmp = command.split(':');
command = tmp.shift();
const tmp = command.split(':');
command = tmp.shift()!;
argv._.unshift(tmp.shift());
}

var method = cli[command];
let method: () => Promise<string> = cli[command];

if (!method) {
// if we failed to find a command, then default to an error
Expand All @@ -108,30 +110,32 @@ function args(processargv) {
}

// TODO decide why we can't do this cart blanche...
if (command === 'protect' ||
command === 'test' ||
command === 'modules' ||
command === 'scenario' ||
command === 'monitor' ||
command === 'wizard' ||
command === 'ignore') {
if ([
'protect',
'test',
'modules',
'scenario',
'monitor',
'wizard',
'ignore',
].indexOf(command) !== -1) {
// copy all the options across to argv._ as an object
argv._.push(argv);
}

// arguments that needs transformation from dash-case to camelCase
// should be added here
[
for (const dashedArg of [
'package-manager',
'packages-folder',
'severity-threshold',
].forEach(function (dashedArg) {
]) {
if (argv[dashedArg]) {
var camelCased = dashToCamelCase(dashedArg);
const camelCased = dashToCamelCase(dashedArg);
argv[camelCased] = argv[dashedArg];
delete argv[dashedArg];
}
});
}

if (argv.insecure) {
global.ignoreUnknownCA = true;
Expand All @@ -140,8 +144,8 @@ function args(processargv) {
debug(command, argv);

return {
method: method,
command: command,
command,
method,
options: argv,
};
}
12 changes: 0 additions & 12 deletions src/cli/copy.js

This file was deleted.

11 changes: 11 additions & 0 deletions src/cli/copy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {execSync} from 'child_process';

const program = {
darwin: 'pbcopy',
linux: 'xclip -selection clipboard',
win32: 'clip',
}[process.platform];

export default function copy(str) {
return execSync(program, {input: str});
}
75 changes: 49 additions & 26 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,20 @@ import * as runtime from './runtime';
import * as analytics from '../lib/analytics';
import * as alerts from '../lib/alerts';
import * as sln from '../lib/sln';
import argsLib = require('./args');
import copy = require('./copy');
import argsLib from './args';
import copy from './copy';
import spinner = require('../lib/spinner');
import errors = require('../lib/error');
import ansiEscapes = require('ansi-escapes');

const args = argsLib(process.argv);
async function runCommand(args) {
const result = await args.method(...args.options._);

if (!runtime.isSupported(process.versions.node)) {
console.error(process.versions.node +
' is an unsupported nodejs runtime! Supported runtime range is \'' +
runtime.supportedRange + '\'');
console.error('Please upgrade your nodejs runtime version ' +
'and try again.');
process.exit(1);
}
let exitcode = 0;

if (args.options.file && args.options.file.match(/\.sln$/)) {
sln.updateArgs(args);
}

const cli = args.method.apply(null, args.options._).then((result) => {
const res = analytics({
args: args.options._,
command: args.command,
});

if (result && !args.options.quiet) {
if (args.options.copy) {
copy(result);
Expand All @@ -42,8 +29,11 @@ const cli = args.method.apply(null, args.options._).then((result) => {
console.log(result);
}
}

return res;
}).catch((error) => {
}

async function handleError(args, error) {
spinner.clearAll();
let command = 'bad-command';

Expand Down Expand Up @@ -83,7 +73,7 @@ const cli = args.method.apply(null, args.options._).then((result) => {
copy(result);
console.log('Result copied to clipboard');
} else {
if ((error.code + '').indexOf('AUTH_') === 0) {
if (`${error.code}`.indexOf('AUTH_') === 0) {
// remove the last few lines
const erase = ansiEscapes.eraseLines(4);
process.stdout.write(erase);
Expand All @@ -93,18 +83,51 @@ const cli = args.method.apply(null, args.options._).then((result) => {
}
}

exitcode = 1;
return res;
}).catch((e) => {
console.log('super fail', e.stack);
}).then((res) => {
}

function checkRuntime() {
if (!runtime.isSupported(process.versions.node)) {
console.error(`${process.versions.node} is an unsupported nodejs ` +
`runtime! Supported runtime range is '${runtime.supportedRange}'`);
console.error('Please upgrade your nodejs runtime version and try again.');
process.exit(1);
}
}

async function main() {
checkRuntime();

const args = argsLib(process.argv);

if (args.options.file && args.options.file.match(/\.sln$/)) {
sln.updateArgs(args);
}

let res = null;
let failed = false;

try {
res = await runCommand(args);
} catch (error) {
failed = true;
res = await handleError(args, error);
}

if (!args.options.json) {
console.log(alerts.displayAlerts());
}
if (!process.env.TAP && exitcode) {
return process.exit(1);

if (!process.env.TAP && failed) {
process.exit(1);
}

return res;
}

const cli = main().catch((e) => {
console.log('super fail', e.stack);
process.exit(1);
});

if (module.parent) {
Expand Down
12 changes: 0 additions & 12 deletions src/cli/runtime.js

This file was deleted.

9 changes: 9 additions & 0 deletions src/cli/runtime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import {gte} from 'semver';

const MIN_RUNTIME = '4.0.0';

export const supportedRange = '>= 4';

export function isSupported(runtimeVersion) {
return gte(runtimeVersion, MIN_RUNTIME);
}
2 changes: 1 addition & 1 deletion test/args.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
var test = require('tap').test;
var args = require('../src/cli/args');
var args = require('../src/cli/args').default;

test('test command line arguments', function(t) {
t.plan(1);
Expand Down

0 comments on commit 03ccd68

Please sign in to comment.