Skip to content

Commit

Permalink
feat: Convert all files to typescript
Browse files Browse the repository at this point in the history
  • Loading branch information
lili2311 committed Jun 18, 2019
1 parent 77f7275 commit ab8639a
Show file tree
Hide file tree
Showing 11 changed files with 183 additions and 144 deletions.
28 changes: 12 additions & 16 deletions lib/index.js → lib/index.ts
@@ -1,18 +1,14 @@
var path = require('path');
var fs = require('fs');
var subProcess = require('./sub-process');
var parser = require('./parse-sbt');
var packageFormatVersion = 'mvn:0.0.1';
import * as path from 'path';
import * as fs from 'fs';

module.exports = {
inspect: inspect,
};
import * as subProcess from './sub-process';
import * as parser from './parse-sbt';
import * as types from './types';
const packageFormatVersion = 'mvn:0.0.1';

module.exports.__tests = {
buildArgs: buildArgs,
};
export async function inspect(root, targetFile, options):
Promise<types.PluginResult> {

function inspect(root, targetFile, options) {
if (!options) {
options = {dev: false};
}
Expand Down Expand Up @@ -71,18 +67,18 @@ function inspect(root, targetFile, options) {
});
}

// guess whether we have the couriser plugin by looking for sbt-coursier
// guess whether we have the couriser plugin by looking for sbt-coursier
// in project and project/project
function coursierPluginInProject(basePath) {
const sbtFileList = sbtFiles(path.join(basePath, 'project'))
.concat(sbtFiles(path.join(basePath, 'project', 'project')));
const searchResults = sbtFileList.map ((file) => {
return searchWithFs(file);
});
return searchResults.includes(true);
return searchResults.filter(Boolean).length > 0;
}

// provide a list of .sbt files in the specified directory
// provide a list of .sbt files in the specified directory
function sbtFiles(basePath) {
if (fs.existsSync(basePath) && fs.lstatSync(basePath).isDirectory()) {
return fs.readdirSync(basePath).filter((fileName) => {
Expand All @@ -99,7 +95,7 @@ function searchWithFs( filename ) {
return buffer.indexOf('sbt-coursier') > -1;
}

function buildArgs(sbtArgs, isCoursierProject) {
export function buildArgs(sbtArgs, isCoursierProject) {
// force plain output so we don't have to parse colour codes
let args = ['-Dsbt.log.noformat=true'];
if (sbtArgs) {
Expand Down
66 changes: 26 additions & 40 deletions lib/parse-sbt.js → lib/parse-sbt.ts
@@ -1,16 +1,17 @@
var tabdown = require('./tabdown');
const tabdown = require('./tabdown');
import * as types from './types';

function convertStrToTree(dependenciesTextTree) {
var lines = dependenciesTextTree.toString().split('\n') || [];
var newLines = lines
.map(function(line) {
const lines = dependenciesTextTree.toString().split('\n') || [];
const newLines = lines
.map((line) => {
return line.replace(/\u001b\[0m/g, '');
})
.filter(function(line) {
.filter((line) => {
if (line.indexOf('[info] ') === 0 && line.indexOf('+-') > -1) {
return true;
}
var match = line.match(/\[info\]\s[\w_\.\-]+:[\w_\.\-]+:[\w_\.\-]+/);
let match = line.match(/\[info\]\s[\w_\.\-]+:[\w_\.\-]+:[\w_\.\-]+/);
if (match && match[0].length === line.length) {
return true;
}
Expand All @@ -20,15 +21,15 @@ function convertStrToTree(dependenciesTextTree) {
}
return false;
})
.map(function(line) {
.map((line) => {
return line
.slice(7, line.length) // slice off '[info] '
.replace(' [S]', '')
.replace(/\|/g, ' ')
.replace('+-', '')
.replace(/\s\s/g, '\t');
});
var tree = tabdown.parse(newLines, '\t');
const tree = tabdown.parse(newLines, '\t');
return tree;
}

Expand Down Expand Up @@ -60,29 +61,28 @@ function convertCoursierStrToTree(dependenciesTextTree) {

function walkInTree(toNode, fromNode) {
if (fromNode.children && fromNode.children.length > 0) {
for (var j = 0; j < fromNode.children.length; j++) {
var externalNode = getPackageNameAndVersion(
for (const j of Object.keys(fromNode.children)) {
const externalNode = getPackageNameAndVersion(
fromNode.children[j].data);
if (externalNode) {
var newNode = {
const newNode = {
version: externalNode.version,
name: externalNode.name,
dependencies: [],
};
toNode.dependencies.push(newNode);
walkInTree(toNode.dependencies[toNode.dependencies.length - 1],
fromNode.children[j],
toNode);
fromNode.children[j]);
}
}
}
delete toNode.parent;
}

function getPackageNameAndVersion(packageDependency) {
var splited;
var version;
var app;
let splited;
let version;
let app;
if (packageDependency.indexOf('(evicted by:') > -1) {
return null;
}
Expand All @@ -95,7 +95,7 @@ function getPackageNameAndVersion(packageDependency) {
app = app.split('\t').join('');
app = app.trim();
version = version.trim();
return {name: app, version: version};
return {name: app, version};
}

function convertDepArrayToObject(depsArr) {
Expand All @@ -117,7 +117,7 @@ function createSnykTree(rootTree, name, version) {
// - use parsed package name and version
// - use single project as root
appTree = rootTree.root[0];
snykTree = getPackageNameAndVersion(getKeys(appTree).pop());
snykTree = getPackageNameAndVersion(Object.keys(appTree).pop());
snykTree.dependencies = [];
} else {
// multi build configuration
Expand All @@ -126,8 +126,8 @@ function createSnykTree(rootTree, name, version) {
appTree = rootTree;
snykTree = {
multiBuild: true, // multi build == fake broken diamond! == beware
name: name,
version: version,
name,
version,
dependencies: [],
};
}
Expand All @@ -148,31 +148,31 @@ function createCoursierSnykTree(rootTree, name, version) {
// - use parsed package name - we don't have version in output
// - use single project as root
const appTree = rootTree.root[0];
snykTree = getProjectName(getKeys(appTree).pop());
snykTree = getProjectName(Object.keys(appTree).pop());
snykTree.dependencies = [];
walkInTree(snykTree, appTree);
} else {
// multi build configuration
// - use provided package name and version
// - use complete tree as root
const dependencies = rootTree.root.map((appTree) => {
const subTree = getProjectName(getKeys(appTree).pop());
const subTree: any = getProjectName(Object.keys(appTree).pop());
subTree.dependencies = [];
walkInTree(subTree, appTree);
return subTree;
});
snykTree = {
multiBuild: true, // multi build == fake broken diamond! == beware
name: name,
version: version,
dependencies: dependencies,
name,
version,
dependencies,
};
}
snykTree.dependencies = convertDepArrayToObject(snykTree.dependencies);
return snykTree;
}

function parse(text, name, version, isCoursier) {
export function parse(text, name, version, isCoursier) {
if (isCoursier) {
const coursierRootTree = convertCoursierStrToTree(text);
return createCoursierSnykTree(coursierRootTree, name, version);
Expand All @@ -181,17 +181,3 @@ function parse(text, name, version, isCoursier) {
const rootTree = convertStrToTree(text);
return createSnykTree(rootTree, name, version);
}

module.exports = {
parse: parse,
};

function getKeys(obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
}
20 changes: 12 additions & 8 deletions lib/sub-process.js → lib/sub-process.ts
@@ -1,14 +1,19 @@
const treeKill = require('tree-kill');
const childProcess = require('child_process');
const debugModule = require('debug');
import * as childProcess from 'child_process';
import * as treeKill from 'tree-kill';
import * as debugModule from 'debug';

// To enable debugging output, run the CLI as `DEBUG=snyk-sbt-plugin snyk ...`
const debugLogging = debugModule('snyk-sbt-plugin');
// 5 minutes default, 0 to disable
const TIMEOUT = process.env.PROC_TIMEOUT || '300000';
const PROC_TIMEOUT = parseInt(TIMEOUT, 10);

const PROC_TIMEOUT = parseInt(process.env.PROC_TIMEOUT, 10) || 300000; // 5 minutes default, 0 to disable

module.exports.execute = (command, args, options) => {
const spawnOptions = {shell: true};
export const execute = (
command: string,
args: string[],
options: {cwd?: string},
): Promise<string> => {
const spawnOptions: {cwd?: string, shell: boolean} = {shell: true};
if (options && options.cwd) {
spawnOptions.cwd = options.cwd;
}
Expand All @@ -33,7 +38,6 @@ module.exports.execute = (command, args, options) => {
debugLogging(str);
});
if (strData.includes('(q)uit')) {
proc.stdin.setEncoding('utf-8');
proc.stdin.write('q\n');
debugLogging('sbt is requiring input. Provided (q)uit signal. ' +
'There is no current workaround for this, see: https://stackoverflow.com/questions/21484166');
Expand Down
44 changes: 21 additions & 23 deletions lib/tabdown.js → lib/tabdown.ts
@@ -1,10 +1,10 @@
exports.parse = function(lines) {
exports.parse = (lines) => {
function addHiddenProperties(scope, props) {
for (let p of Object.keys(props)) {
for (const p of Object.keys(props)) {
Object.defineProperty(scope, p, {enumerable: false, value: props[p]});
}
}
var TreeNode = function(data, depth) {
const TreeNode = function(data, depth) {
this.parent = null;
addHiddenProperties(this, {
data,
Expand All @@ -19,14 +19,14 @@ exports.parse = function(lines) {
return JSON.stringify(this.children);
};

var tree = new TreeNode(null, -1);
const tree = new TreeNode(null, -1);

var levels = [tree];
const levels = [tree];

function countTabs(line) {
var count = 0;
for (var i = 0; i < line.length; i++) {
var ch = line[i];
let count = 0;
for (const i of Object.keys(line)) {
const ch = line[i];
if ((ch === '\t')) {
count += 1;
} else if (/[^\s]/.test(ch)) {
Expand All @@ -36,18 +36,18 @@ exports.parse = function(lines) {
return -1; // no content
}

for (let i = 0; i < lines.length; i++) {
let line = lines[i];
for (const i of Object.keys(lines)) {
const line = lines[i];

var tabcount = countTabs(line);
const tabcount = countTabs(line);

if (tabcount >= 0) {
// then add node to tree
while (tabcount - levels[levels.length - 1].depth <= 0) {
levels.pop();
}
let depth = levels.length - 1;
var node = new TreeNode(line.substring(tabcount), depth);
const depth = levels.length - 1;
const node = new TreeNode(line.substring(tabcount), depth);
node.parent = levels[levels.length - 1];
node.parent.children.push(node);
levels.push(node);
Expand All @@ -56,30 +56,28 @@ exports.parse = function(lines) {
return tree;
};

exports.traverse = function(tree, cb) {
exports.traverse = (tree, cb) => {
function _traverse(node) {
cb(node);
for (let i = 0; i < node.children.length; i++) {
for (const i of node.children.length) {
_traverse(node.children[i]);
}
}
for (let i = 0; i < tree.children.length; i++) {
for (const i of tree.children) {
_traverse(tree.children[i]);
}
};

exports.print = function(tree) {
exports.traverse(tree, function(node) {
var str = '';
for (var i = 0; i < node.depth; i++) {
exports.print = (tree) => {
exports.traverse(tree, (node) => {
let str = '';
for (let i = 0; i < node.depth; i++) {
str += '\t';
}
str += node.data;
// tslint:disable
console.log(str);
});
};

exports.toJSON = function(tree) {
exports.toJSON = (tree) => {
return JSON.stringify(tree.children);
};
25 changes: 25 additions & 0 deletions lib/types.ts
@@ -0,0 +1,25 @@
export interface PluginResult {
plugin: PluginMetadata;
package: DepTree;
}

export interface DepDict {
[name: string]: DepTree;
}

export interface DepRoot {
depTree: DepTree; // to be soon replaced with depGraph
meta?: any;
}

export interface DepTree {
name: string;
version: string;
dependencies?: DepDict;
packageFormatVersion?: string;
}

export interface PluginMetadata {
name: string;
runtime: string;
}

0 comments on commit ab8639a

Please sign in to comment.