diff --git a/package.json b/package.json index 119aba81..cbdfc6d4 100644 --- a/package.json +++ b/package.json @@ -14,22 +14,25 @@ "theme": "dark" }, "bugs": { - "url": "https://github.com/invincibleJai/fabric8-analytics-vsc-stackreports/issues", + "url": "https://github.com/invincibleJai/fabric8-analytics-vsc/issues", "email": "jakumar@redhat.com" }, "repository": { "type": "git", - "url": "https://github.com/invincibleJai/fabric8-analytics-vsc-stackreports" + "url": "https://github.com/invincibleJai/fabric8-analytics-vsc" }, "homepage": "https://github.com/invincibleJai/fabric8-analytics-vsc-stackreports/blob/master/README.md", "categories": [ "Other" ], "engines": { - "vscode": "^0.10.7" + "vscode": "^1.8.0" }, "activationEvents": [ - "onCommand:extension.fabric8AnalyticsWidget" + "onCommand:extension.fabric8AnalyticsWidget", + "onLanguage:plaintext", + "onLanguage:xml", + "onLanguage:json" ], "main": "./out/extension", "contributes": { @@ -54,20 +57,42 @@ "when": "resourceLangId == json" } ] - } + }, + "configuration": { + "type": "object", + "title": "Example configuration", + "properties": { + "languageServerExample.maxNumberOfProblems": { + "type": "number", + "default": 100, + "description": "Controls the maximum number of problems produced by the server." + }, + "languageServerExample.trace.server": { + "type": "string", + "enum": [ + "off", + "messages", + "verbose" + ], + "default": "off", + "description": "Traces the communication between VSCode and the languageServerExample service." + } + } + } }, "scripts": { "vscode:prepublish": "tsc -p ./", "compile": "tsc -watch -p ./", - "postinstall": "node ./node_modules/vscode/bin/install", - "tslint": "tslint -c tslint.json src/extension.ts" + "postinstall": "node ./node_modules/vscode/bin/install" }, "devDependencies": { - "typescript": "^2.1.4", - "vscode": "^1.0.0", - "@types/node": "*" + "@types/mocha": "^2.2.33", + "@types/node": "^6.0.52", + "typescript": "^2.1.5", + "vscode": "^1.0.3" }, "dependencies": { - "request": "2.79.0" + "request": "2.79.0", + "vscode-languageclient": "^3.3.0" } } \ No newline at end of file diff --git a/server/.DS_Store b/server/.DS_Store new file mode 100644 index 00000000..34528f8f Binary files /dev/null and b/server/.DS_Store differ diff --git a/server/collector.js b/server/collector.js new file mode 100644 index 00000000..5c44071a --- /dev/null +++ b/server/collector.js @@ -0,0 +1,202 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Pavel Odvody 2016 + * Licensed under the Apache-2.0 License. See License.txt in the project root for license information. + * ------------------------------------------------------------------------------------------ */ +'use strict'; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const json_1 = require("./json"); +const Xml2Object = require("xml2object"); +/* By default the collector is going to process these dependency keys */ +const DefaultClasses = ["dependencies", "devDependencies", "optionalDependencies"]; +/* Dependency class that can be created from `IKeyValueEntry` */ +class Dependency { + constructor(dependency) { + this.name = { + value: dependency.key, + position: dependency.key_position + }; + this.version = { + value: dependency.value.object, + position: dependency.value_position + }; + } +} +/* Process entries found in the JSON files and collect all dependency + * related information */ +class DependencyCollector { + constructor(classes) { + this.classes = classes; + this.classes = classes || DefaultClasses; + } + collect(file) { + return __awaiter(this, void 0, void 0, function* () { + let parser = new json_1.StreamingParser(file); + let dependencies = []; + let tree = yield parser.parse(); + let top_level = tree.children[0]; + /* Iterate over all keys, select those in which we're interested as defined + by `classes`, and map each item to a new `Dependency` object */ + for (const p of top_level.properties) { + if (this.classes.indexOf(p.key) > -1) { + for (const dependency of p.value.object) { + dependencies.push(new Dependency(dependency)); + } + } + } + return dependencies; + }); + } +} +exports.DependencyCollector = DependencyCollector; +class NaivePyParser { + constructor(objSam) { + this.dependencies = []; + this.isDependency = false; + this.versionStartLine = 0; + this.versionStartColumn = 0; + this.objSam = objSam; + this.parser = this.createParser12(); + } + createParser12() { + let deps = this.dependencies; + this.objSam.forEach(function (obj) { + //connection.console.log(s); + //let pkgName = Object.keys(obj)[0]; + let entry = new json_1.KeyValueEntry(obj["pkgName"], { line: 0, column: 0 }); + entry.value = new json_1.Variant(json_1.ValueType.String, obj["version"]); + entry.value_position = { line: obj["line"], column: obj["pos"] }; + let dep = new Dependency(entry); + deps.push(dep); + }); + //return deps; + } + parse() { + // try { + // this.stream.pipe(this.parser.saxStream); + // } catch (e) { + // console.error(e.message) + // } + return this.dependencies; + } +} +let objListMap = []; +let toObject = (arr) => { + let rv = []; + for (let i = 0; i < arr.length; ++i) { + if (arr[i] !== undefined) { + let line = arr[i].replace(/\s/g, ''); + let lineArr; + let lineStr; + if (line.indexOf('#') !== -1) { + lineArr = line.split("#"); + lineStr = lineArr[0]; + } + else { + lineStr = line; + } + let subArr = lineStr.split(/[==,>=]+/); + let subObj = {}; + subObj["pkgName"] = subArr[0]; + subObj["version"] = subArr[1] || ""; + subObj["line"] = i + 1; + subObj["column"] = subArr[0].length + 2; + rv.push(subObj); + } + } + objListMap = rv; + return rv; +}; +/* Process entries found in the txt files and collect all dependency + * related information */ +class ReqDependencyCollector { + constructor(classes = ["dependencies"]) { + this.classes = classes; + } + collect(contents) { + return __awaiter(this, void 0, void 0, function* () { + let tempArr = contents.split("\n"); + let objSam = toObject(tempArr); + let parser = new NaivePyParser(objSam); + let dependencies = parser.parse(); + return dependencies; + }); + } +} +exports.ReqDependencyCollector = ReqDependencyCollector; +class NaivePomXmlSaxParser { + constructor(stream) { + this.dependencies = []; + this.isDependency = false; + this.versionStartLine = 0; + this.versionStartColumn = 0; + this.stream = stream; + this.parser = this.createParser(); + } + createParser() { + let parser = new Xml2Object(["dependency"], { strict: true, trackPosition: true }); + let deps = this.dependencies; + let versionLine = this.versionStartLine; + let versionColumn = this.versionStartColumn; + parser.on("object", function (name, obj) { + if (obj.hasOwnProperty("groupId") && obj.hasOwnProperty("artifactId") && obj.hasOwnProperty("version")) { + let ga = `${obj["groupId"]}:${obj["artifactId"]}`; + let entry = new json_1.KeyValueEntry(ga, { line: 0, column: 0 }); + entry.value = new json_1.Variant(json_1.ValueType.String, obj["version"]); + entry.value_position = { line: versionLine, column: versionColumn }; + let dep = new Dependency(entry); + deps.push(dep); + } + }); + parser.saxStream.on("opentag", function (node) { + if (node.name == "dependency") { + this.isDependency = true; + } + if (this.isDependency && node.name == "version") { + versionLine = parser.saxStream._parser.line + 1; + versionColumn = parser.saxStream._parser.column + 1; + } + }); + parser.saxStream.on("closetag", function (nodeName) { + // TODO: nested deps! + if (nodeName == "dependency") { + this.isDependency = false; + } + }); + parser.on("error", function (e) { + // the XML document doesn't have to be well-formed, that's fine + parser.error = null; + }); + return parser; + } + parse() { + try { + this.stream.pipe(this.parser.saxStream); + } + catch (e) { + console.error(e.message); + } + return this.dependencies; + } +} +class PomXmlDependencyCollector { + constructor(classes = ["dependencies"]) { + this.classes = classes; + } + collect(file) { + return __awaiter(this, void 0, void 0, function* () { + let parser = new NaivePomXmlSaxParser(file); + let dependencies = parser.parse(); + return dependencies; + }); + } +} +exports.PomXmlDependencyCollector = PomXmlDependencyCollector; +//# sourceMappingURL=collector.js.map \ No newline at end of file diff --git a/server/collector.js.map b/server/collector.js.map new file mode 100644 index 00000000..f632a26b --- /dev/null +++ b/server/collector.js.map @@ -0,0 +1 @@ +{"version":3,"file":"collector.js","sourceRoot":"","sources":["../../server/src/collector.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAChG,YAAY,CAAC;;;;;;;;;;AACb,iCAAuG;AACvG,yCAAyC;AAGzC,wEAAwE;AACxE,MAAM,cAAc,GAAG,CAAC,cAAc,EAAE,iBAAiB,EAAE,sBAAsB,CAAC,CAAC;AAoBnF,gEAAgE;AAChE;IAGE,YAAY,UAA0B;QACpC,IAAI,CAAC,IAAI,GAAG;YACR,KAAK,EAAE,UAAU,CAAC,GAAG;YACrB,QAAQ,EAAE,UAAU,CAAC,YAAY;SACpC,CAAC;QACF,IAAI,CAAC,OAAO,GAA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SAAS,CAAC,CAAC;QAC5C,CAAC;QAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YACT,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,CAAA;QAC5B,CAAC;QACD,MAAM,CAAC,IAAI,CAAC,YAAY,CAAA;IAC5B,CAAC;CACJ;AAED;IACI,YAAmB,UAAyB,CAAC,cAAc,CAAC;QAAzC,YAAO,GAAP,OAAO,CAAkC;IAAG,CAAC;IAE1D,OAAO,CAAC,IAAY;;YACtB,IAAI,MAAM,GAAG,IAAI,oBAAoB,CAAC,IAAI,CAAC,CAAC;YAC5C,IAAI,YAAY,GAAuB,MAAM,CAAC,KAAK,EAAE,CAAC;YACtD,MAAM,CAAC,YAAY,CAAC;QACxB,CAAC;KAAA;CACJ;AAEmD,8DAAyB"} \ No newline at end of file diff --git a/server/consumers.js b/server/consumers.js new file mode 100644 index 00000000..66cf1308 --- /dev/null +++ b/server/consumers.js @@ -0,0 +1,133 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Pavel Odvody 2016 + * Licensed under the Apache-2.0 License. See License.txt in the project root for license information. + * ------------------------------------------------------------------------------------------ */ +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("./utils"); +const vscode_languageserver_1 = require("vscode-languageserver"); +; +/* Bind & return the part of `obj` as described by `desc` */ +let bind_object = (obj, desc) => { + let bind = obj; + for (let elem of desc.path) { + if (elem in bind) { + bind = bind[elem]; + } + else { + return null; + } + } + return bind; +}; +; +; +; +; +/* Diagnostics pipeline implementation */ +class DiagnosticsPipeline { + constructor(classes, dependency, config, diags) { + this.items = classes.map((i) => { return new i(dependency, config); }); + this.dependency = dependency; + this.config = config; + this.diagnostics = diags; + } + run(data) { + for (let item of this.items) { + if (item.consume(data)) { + for (let d of item.produce()) + this.diagnostics.push(d); + } + } + return this.diagnostics; + } +} +exports.DiagnosticsPipeline = DiagnosticsPipeline; +; +/* A consumer that uses the binding interface to consume a metadata object */ +class AnalysisConsumer { + constructor(config) { + this.config = config; + this.changeTo = null; + } + consume(data) { + if (this.binding != null) { + this.item = bind_object(data, this.binding); + } + else { + this.item = data; + } + if (this.changeToBinding != null) { + this.changeTo = bind_object(data, this.changeToBinding); + } + return this.item != null; + } +} +; +/* We've received an empty/unfinished result, display that analysis is pending */ +class EmptyResultEngine extends AnalysisConsumer { + constructor(context, config) { + super(config); + this.context = context; + } + produce() { + if (this.item == {} || + this.item.finished_at === undefined || + this.item.finished_at == null) { + return [{ + severity: vscode_languageserver_1.DiagnosticSeverity.Information, + range: utils_1.get_range(this.context.version), + message: `Package ${this.context.name.value}-${this.context.version.value} - analysis is pending`, + source: 'Component Analysis' + }]; + } + else { + return []; + } + } +} +exports.EmptyResultEngine = EmptyResultEngine; +/* Report CVEs in found dependencies */ +class SecurityEngine extends AnalysisConsumer { + constructor(context, config) { + super(config); + this.context = context; + this.binding = { path: ['result', 'recommendation', 'component-analyses', 'cve'] }; + /* recommendation to use a different version */ + this.changeToBinding = { path: ['result', 'recommendation', 'change_to'] }; + } + produce() { + if (this.item.length > 0) { + let cveList = []; + for (let cve of this.item) { + cveList.push(cve['id']); + } + let cves = cveList.join(' '); + let diagnostic = { + severity: vscode_languageserver_1.DiagnosticSeverity.Error, + range: utils_1.get_range(this.context.version), + message: `Package ${this.context.name.value}-${this.context.version.value} is vulnerable: ${cves}`, + source: 'Component Analysis' + }; + // TODO: this can be done lazily + if (this.changeTo != null) { + let command = { + title: "Switch to recommended version " + this.changeTo, + command: "lsp.applyTextEdit", + arguments: [{ range: diagnostic.range, newText: this.changeTo }] + }; + diagnostic.message += ". Recommendation: use version " + this.changeTo; + codeActionsMap[diagnostic.message] = command; + } + return [diagnostic]; + } + else { + return []; + } + } +} +exports.SecurityEngine = SecurityEngine; +; +let codeActionsMap = new Map(); +exports.codeActionsMap = codeActionsMap; +//# sourceMappingURL=consumers.js.map \ No newline at end of file diff --git a/server/consumers.js.map b/server/consumers.js.map new file mode 100644 index 00000000..e3e7229e --- /dev/null +++ b/server/consumers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"consumers.js","sourceRoot":"","sources":["../../server/src/consumers.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAChG,YAAY,CAAC;;AAEb,mCAAoC;AACpC,iEAA+E;AAM9E,CAAC;AAEF,4DAA4D;AAC5D,IAAI,WAAW,GAAG,CAAC,GAAQ,EAAE,IAAwB;IACjD,IAAI,IAAI,GAAG,GAAG,CAAC;IACf,GAAG,CAAC,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QACzB,EAAE,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC;YACf,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;QACtB,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;IACD,MAAM,CAAC,IAAI,CAAC;AAChB,CAAC,CAAC;AAQD,CAAC;AAMD,CAAC;AAG2D,CAAC;AAO7D,CAAC;AAKF,yCAAyC;AACzC;IAMI,YAAY,OAAmB,EAAE,UAAuB,EAAE,MAAW,EAAE,KAAwB;QAC3F,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,MAAM,CAAC,IAAI,CAAC,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QACvE,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAC7B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,WAAW,GAAG,KAAK,CAAC;IAC7B,CAAC;IAED,GAAG,CAAC,IAAS;QACT,GAAG,CAAC,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;YAC1B,EAAE,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;gBACrB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,EAAE,iBAAS,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;gBACtC,OAAO,EAAE,WAAW,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,mBAAmB,IAAI,EAAE;gBAClG,MAAM,EAAE,oBAAoB;aAC/B,CAAC;YAEF,gCAAgC;YAChC,EAAE,CAAC,CAAC,IAAI,CAAC,QAAQ,IAAI,IAAI,CAAC,CAAC,CAAC;gBACxB,IAAI,OAAO,GAAG;oBACV,KAAK,EAAE,gCAAgC,GAAG,IAAI,CAAC,QAAQ;oBACvD,OAAO,EAAE,mBAAmB;oBAC5B,SAAS,EAAE,CAAC,EAAC,KAAK,EAAE,UAAU,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC,QAAQ,EAAC,CAAC;iBACjE,CAAC;gBACF,UAAU,CAAC,OAAO,IAAI,gCAAgC,GAAG,IAAI,CAAC,QAAQ,CAAC;gBACvE,cAAc,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,OAAO,CAAA;YAChD,CAAC;YACD,MAAM,CAAC,CAAC,UAAU,CAAC,CAAA;QACvB,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,MAAM,CAAC,EAAE,CAAC;QACd,CAAC;IACL,CAAC;CACJ;AAI6B,wCAAc;AAJ3C,CAAC;AAEF,IAAI,cAAc,GAAG,IAAI,GAAG,EAAmB,CAAC;AAEiB,wCAAc"} \ No newline at end of file diff --git a/server/json.js b/server/json.js new file mode 100644 index 00000000..3cb3bf4f --- /dev/null +++ b/server/json.js @@ -0,0 +1,145 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Pavel Odvody 2016 + * Licensed under the Apache-2.0 License. See License.txt in the project root for license information. + * ------------------------------------------------------------------------------------------ */ +'use strict'; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", { value: true }); +/* Since the following modules are written in regular JS we can't use TS's import statement + so we need to `require` those the JS way */ +let Parser = require("stream-json/ClassicParser"), Streamer = require("stream-json/Streamer"), Emitter = require("stream-json/Emitter"), Packer = require("stream-json/Packer"); +/* Determine to which class the emitted token belongs */ +var TokenMarker; +(function (TokenMarker) { + TokenMarker[TokenMarker["Invalid"] = 0] = "Invalid"; + TokenMarker[TokenMarker["Key"] = 1] = "Key"; + TokenMarker[TokenMarker["Value"] = 2] = "Value"; +})(TokenMarker || (TokenMarker = {})); +; +/* Determine what is the value */ +var ValueType; +(function (ValueType) { + ValueType[ValueType["Invalid"] = 0] = "Invalid"; + ValueType[ValueType["String"] = 1] = "String"; + ValueType[ValueType["Integer"] = 2] = "Integer"; + ValueType[ValueType["Float"] = 3] = "Float"; + ValueType[ValueType["Array"] = 4] = "Array"; + ValueType[ValueType["Object"] = 5] = "Object"; + ValueType[ValueType["Boolean"] = 6] = "Boolean"; + ValueType[ValueType["Null"] = 7] = "Null"; +})(ValueType || (ValueType = {})); +exports.ValueType = ValueType; +; +; +; +; +class Variant { + constructor(type, object) { + this.type = type; + this.object = object; + } +} +exports.Variant = Variant; +class KeyValueEntry { + constructor(k, pos) { + this.key = k; + this.key_position = pos; + } +} +exports.KeyValueEntry = KeyValueEntry; +class Scope { + constructor(parent) { + this.children = []; + this.properties = []; + this.parent = parent; + this.marker = TokenMarker.Invalid; + this.last = null; + } + add_scope() { + let new_scope = new Scope(this); + this.children.push(new_scope); + /* We're creating a new scope, but since the current key has + undefined value it means the new scope (or the contents therein) *is* the value */ + if (this.last !== null && this.last.value == undefined) { + this.last.value = new Variant(ValueType.Object, new_scope.properties); + this.properties.push(this.last); + } + return new_scope; + } + consume(token) { + switch (this.marker) { + case TokenMarker.Key: + this.last = new KeyValueEntry(token.value, { line: token.line, column: token.pos }); + this.marker = TokenMarker.Invalid; + break; + case TokenMarker.Value: + this.last.value = new Variant(ValueType.String, token.value); + this.last.value_position = { line: token.line, column: token.pos }; + this.properties.push(this.last); + this.marker = TokenMarker.Invalid; + break; + default: + break; + } + } + leave() { + return this.parent; + } + /* used mainly for debug purposes */ + print() { + console.log(this.properties); + this.children.forEach((scope) => { scope.print(); }); + } +} +; +class StreamingParser { + constructor(file) { + this.file = file; + } + parse() { + return __awaiter(this, void 0, void 0, function* () { + let scope = new Scope(), parser = new Parser(), stream = new Streamer(), emitter = new Emitter(), packer = new Packer({ packKeys: true, packStrings: true, packNumbers: true }); + let root = scope; + /* In the following code we observe two event streams, one defined by parser + and the other one by emitter. The difference here is that parser produces raw tokens + with positional information as to where in the file the token is declared, but since + this stream is very low level and contains tokens like ", [, ] etc. we need to correlate + events from this stream with the events produced by the emitter stream which gives + us much finer granularity in handling the underlying JSON structure. + + The correlation of the events itself is handled by the `Scope` which in essence + implements a finite state machine to make sense of the two event streams. */ + parser.on("data", function (x) { + if (scope.marker != TokenMarker.Invalid) { + scope.consume(x); + } + }); + parser.on("error", function (e) { + // the JSON document doesn't have to be well-formed, that's fine + }); + emitter.on("startKey", function () { scope.marker = TokenMarker.Key; }); + /* We don't care about numbers, nulls, arrays and booleans thus far */ + emitter.on("startString", function () { scope.marker = TokenMarker.Value; }); + emitter.on("startObject", function () { scope = scope.add_scope(); }); + emitter.on("endObject", function () { scope = scope.leave(); }); + this.file + .pipe(parser) + .pipe(stream) + .pipe(packer) + .pipe(emitter); + return new Promise(resolve => { + emitter.on("finish", () => resolve(root)); + }); + }); + } +} +exports.StreamingParser = StreamingParser; +; +//# sourceMappingURL=json.js.map \ No newline at end of file diff --git a/server/json.js.map b/server/json.js.map new file mode 100644 index 00000000..c2477532 --- /dev/null +++ b/server/json.js.map @@ -0,0 +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AC,CAAC;YAEH,OAAO,CAAC,EAAE,CAAC,UAAU,EAAE,cAAkB,KAAK,CAAC,MAAM,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YAC5E,sEAAsE;YACtE,OAAO,CAAC,EAAE,CAAC,aAAa,EAAE,cAAa,KAAK,CAAC,MAAM,GAAG,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;YAC5E,OAAO,CAAC,EAAE,CAAC,aAAa,EAAE,cAAa,KAAK,GAAG,KAAK,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;YACrE,OAAO,CAAC,EAAE,CAAC,WAAW,EAAE,cAAa,KAAK,GAAG,KAAK,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;YAE/D,IAAI,CAAC,IAAI;iBACN,IAAI,CAAC,MAAM,CAAC;iBACZ,IAAI,CAAC,MAAM,CAAC;iBACZ,IAAI,CAAC,MAAM,CAAC;iBACZ,IAAI,CAAC,OAAO,CAAC,CAAC;YAEjB,MAAM,CAAC,IAAI,OAAO,CAAmB,OAAO;gBAC1C,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;YAC5C,CAAC,CAAC,CAAC;QACL,CAAC;KAAA;CACF;AAEQ,0CAAe;AAFvB,CAAC"} \ No newline at end of file diff --git a/server/package.json b/server/package.json new file mode 100644 index 00000000..a0689c2a --- /dev/null +++ b/server/package.json @@ -0,0 +1,32 @@ +{ + "name": "component-analysis-lsp-server", + "description": "LSP Server for Component Analysis", + "version": "0.0.4", + "author": "Pavel Odvody", + "contributors": [ + { + "name": "Michal Srb", + "email": "michal@redhat.com" + } + ], + "license": "Apache-2.0", + "engines": { + "node": "*" + }, + "dependencies": { + "vscode-languageserver": "^3.3.0", + "stream-json": "0.4.2", + "request": "^2.79.0", + "xml2object": "0.1.2", + "winston": "2.3.1" + }, + "devDependencies": { + "@types/node": "^8.0.8", + "typescript": "^2.1.4" + }, + "scripts": { + "build": "node node_modules/typescript/bin/tsc -p .", + "dist": "cp -r node_modules output/ && node -p -e \"require('./package.json').version\" > output/VERSION && rm -rf output/node_modules/typescript/ && tar cvjf ca-lsp-server.tar -C output/ .", + "watch": "installServerIntoExtension ../client ./package.json ./tsconfig.json && tsc --watch -p ." + } +} diff --git a/server/sentiment.js b/server/sentiment.js new file mode 100644 index 00000000..581f33a6 --- /dev/null +++ b/server/sentiment.js @@ -0,0 +1,128 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Pavel Odvody 2016 + * Licensed under the Apache-2.0 License. See License.txt in the project root for license information. + * ------------------------------------------------------------------------------------------ */ +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("./utils"); +const vscode_languageserver_1 = require("vscode-languageserver"); +; +/* Bind & return the part of `obj` as described by `desc` */ +let bind_object = (obj, desc) => { + let bind = obj; + for (let elem of desc.path) { + if (elem in bind) { + bind = bind[elem]; + } + else { + return null; + } + } + return bind; +}; +; +; +; +; +/* Diagnostics pipeline implementation */ +class DiagnosticsPipelineSenti { + constructor(classes, dependency, config, diags) { + this.items = classes.map((i) => { return new i(dependency, config); }); + this.dependency = dependency; + this.config = config; + this.diagnostics = diags; + } + run(data) { + for (let item of this.items) { + if (item.consume(data)) { + for (let d of item.produce()) + this.diagnostics.push(d); + } + } + return this.diagnostics; + } +} +exports.DiagnosticsPipelineSenti = DiagnosticsPipelineSenti; +; +/* A consumer that uses the binding interface to consume a metadata object */ +class AnalysisConsumer { + constructor(config) { + this.config = config; + this.changeTo = null; + } + consume(data) { + if (data && data.sentiment_details && data.sentiment_details.hasOwnProperty("latest_comment") && + data.sentiment_details.latest_comment != '' && data.sentiment_details.hasOwnProperty("overall_sentiment_score") && + data.sentiment_details.overall_sentiment_score != 0) { + let sentiCommentObj = { + "sentiment": "", + "comment": "" + }; + if (Number(data.sentiment_details.overall_sentiment_score.trim()) > 0) { + sentiCommentObj.sentiment = "Postive"; + } + else if (Number(data.sentiment_details.overall_sentiment_score.trim()) < 0) { + sentiCommentObj.sentiment = "Negative"; + } + else { + sentiCommentObj.sentiment = "Neutral"; + } + sentiCommentObj['timestamp'] = data.sentiment_details.latest_comment_time; + sentiCommentObj.comment = data.sentiment_details.latest_comment; + this.item = []; + this.item.push(sentiCommentObj); + } + return this.item != null; + } +} +; +/* We've received an empty/unfinished result, display that analysis is pending */ +class EmptyResultEngineSenti extends AnalysisConsumer { + constructor(context, config) { + super(config); + this.context = context; + } + produce() { + if (this.item == {} || + this.item.finished_at === undefined || + this.item.finished_at == null) { + return [{ + severity: vscode_languageserver_1.DiagnosticSeverity.Information, + range: utils_1.get_range(this.context.version), + message: `Package ${this.context.name.value}-${this.context.version.value} - analysis is pending`, + source: 'Sentiment Analysis' + }]; + } + else { + return []; + } + } +} +exports.EmptyResultEngineSenti = EmptyResultEngineSenti; +/* Report CVEs in found dependencies */ +class SecurityEngineSenti extends AnalysisConsumer { + constructor(context, config) { + super(config); + this.context = context; + } + produce() { + if (this.item.length > 0) { + let sentimentData = this.item; + let diagnostic = { + severity: vscode_languageserver_1.DiagnosticSeverity.Information, + range: utils_1.get_range(this.context.version), + message: `Sentiment : ${sentimentData[0].sentiment} , Last comment as on [${sentimentData[0]['timestamp']}]: ${sentimentData[0].comment}`, + source: 'Sentiment Analysis' + }; + return [diagnostic]; + } + else { + return []; + } + } +} +exports.SecurityEngineSenti = SecurityEngineSenti; +; +let codeActionsMapSenti = new Map(); +exports.codeActionsMapSenti = codeActionsMapSenti; +//# sourceMappingURL=sentiment.js.map \ No newline at end of file diff --git a/server/sentiment.js.map b/server/sentiment.js.map new file mode 100644 index 00000000..ced5f975 --- /dev/null +++ b/server/sentiment.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sentiment.js","sourceRoot":"","sources":["../../server/src/sentiment.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAChG,YAAY,CAAC;;AAEb,mCAAoC;AACpC,iEAA+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Q,EAAE,0CAAkB,CAAC,WAAW;gBACxC,KAAK,EAAE,iBAAS,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;gBACtC,OAAO,EAAE,eAAe,aAAa,CAAC,CAAC,CAAC,CAAC,SAAS,0BAA0B,aAAa,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,MAAM,aAAa,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE;gBACzI,MAAM,EAAE,oBAAoB;aAC/B,CAAC;YACF,MAAM,CAAC,CAAC,UAAU,CAAC,CAAA;QACvB,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,MAAM,CAAC,EAAE,CAAC;QACd,CAAC;IACL,CAAC;CACJ;AAIkC,kDAAmB;AAJrD,CAAC;AAEF,IAAI,mBAAmB,GAAG,IAAI,GAAG,EAAmB,CAAC;AAE2B,kDAAmB"} \ No newline at end of file diff --git a/server/server.js b/server/server.js new file mode 100644 index 00000000..8771a83e --- /dev/null +++ b/server/server.js @@ -0,0 +1,460 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Pavel Odvody 2016 + * Licensed under the Apache-2.0 License. See License.txt in the project root for license information. + * ------------------------------------------------------------------------------------------ */ +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +const path = require("path"); +const fs = require("fs"); +const vscode_languageserver_1 = require("vscode-languageserver"); +const utils_1 = require("./utils"); +const collector_1 = require("./collector"); +const consumers_1 = require("./consumers"); +const sentiment_1 = require("./sentiment"); +const stackanalysis_1 = require("./stackanalysis"); +const url = require('url'); +const https = require('https'); +const http = require('http'); +const request = require('request'); +const winston = require('winston'); +winston.level = 'debug'; +winston.add(winston.transports.File, { filename: 'bayesian.log' }); +winston.remove(winston.transports.Console); +winston.info('Starting Bayesian'); +/* +let log_file = fs.openSync('file_log.log', 'w'); +let _LOG = (data) => { + fs.writeFileSync('file_log.log', data + '\n'); +} +*/ +class AShowMessageParamsInstance { + constructor(type, message) { + this.type = type; + this.message = message; + } +} +var EventStream; +(function (EventStream) { + EventStream[EventStream["Invalid"] = 0] = "Invalid"; + EventStream[EventStream["Diagnostics"] = 1] = "Diagnostics"; + EventStream[EventStream["CodeLens"] = 2] = "CodeLens"; +})(EventStream || (EventStream = {})); +; +let connection = null; +/* use stdio for transfer if applicable */ +if (process.argv.indexOf('--stdio') == -1) + connection = vscode_languageserver_1.createConnection(new vscode_languageserver_1.IPCMessageReader(process), new vscode_languageserver_1.IPCMessageWriter(process)); +else + connection = vscode_languageserver_1.createConnection(); +let documents = new vscode_languageserver_1.TextDocuments(); +documents.listen(connection); +let workspaceRoot; +connection.onInitialize((params) => { + workspaceRoot = params.rootPath; + return { + capabilities: { + textDocumentSync: documents.syncKind, + codeActionProvider: true + } + }; +}); +; +; +; +class AnalysisFileHandler { + constructor(matcher, stream, callback) { + this.stream = stream; + this.callback = callback; + this.matcher = new RegExp(matcher); + } +} +; +class AnalysisFiles { + constructor() { + this.handlers = []; + this.file_data = new Map(); + } + on(stream, matcher, cb) { + this.handlers.push(new AnalysisFileHandler(matcher, stream, cb)); + return this; + } + run(stream, uri, file, contents) { + for (let handler of this.handlers) { + if (handler.stream == stream && handler.matcher.test(file)) { + return handler.callback(uri, file, contents); + } + } + } +} +; +; +class AnalysisLSPServer { + constructor(connection, files) { + this.connection = connection; + this.files = files; + } + handle_file_event(uri, contents) { + let path_name = url.parse(uri).pathname; + let file_name = path.basename(path_name); + this.files.file_data[uri] = contents; + this.files.run(EventStream.Diagnostics, uri, file_name, contents); + } + handle_code_lens_event(uri) { + let path_name = url.parse(uri).pathname; + let file_name = path.basename(path_name); + let lenses = []; + let contents = this.files.file_data[uri]; + return this.files.run(EventStream.CodeLens, uri, file_name, contents); + } +} +; +; +class Aggregator { + constructor(items, callback) { + this.callback = callback; + this.mapping = new Map(); + for (let item of items) { + this.mapping.set(item, false); + } + } + is_ready() { + let val = true; + for (let m of this.mapping.entries()) { + val = val && m[1]; + } + return val; + } + aggregate(dep) { + this.mapping.set(dep, true); + if (this.is_ready()) { + this.callback(); + } + } +} +; +class AnalysisConfig { + constructor() { + // TODO: this needs to be configurable + this.server_url = "https://recommender.api.openshift.io/api/v1"; + this.api_token = process.env.RECOMMENDER_API_TOKEN || "the-token"; + this.forbidden_licenses = []; + this.no_crypto = false; + this.home_dir = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME']; + } +} +; +let config = new AnalysisConfig(); +let files = new AnalysisFiles(); +let server = new AnalysisLSPServer(connection, files); +let rc_file = path.join(config.home_dir, '.analysis_rc'); +if (fs.existsSync(rc_file)) { + let rc = JSON.parse(fs.readFileSync(rc_file, 'utf8')); + if ('server' in rc) { + config.server_url = `${rc.server}/api/v1`; + } +} +let DiagnosticsEngines = [consumers_1.SecurityEngine]; +let DiagnosticsEnginesSenti = [sentiment_1.SecurityEngineSenti]; +let DiagnosticsEnginesStack = [stackanalysis_1.SecurityEngineStack]; +// TODO: in-memory caching only, this needs to be more robust +let metadataCache = new Map(); +let get_metadata = (ecosystem, name, version, cb) => { + let cacheKey = ecosystem + " " + name + " " + version; + let metadata = metadataCache[cacheKey]; + if (metadata != null) { + winston.info('cache hit for ' + cacheKey); + cb(metadata); + return; + } + let part = [ecosystem, name, version].join('/'); + const options = url.parse(config.server_url); + options['path'] += `/component-analyses/${part}/`; + options['headers'] = { 'Authorization': 'Bearer ' + config.api_token }; + winston.debug('get ' + ecosystem + options['host'] + options['path']); + //connection.console.log('get comp ana' + options['host'] + options['path']); + //winston.debug('token ' + config.api_token); + https.get(options, function (res) { + let body = ''; + res.on('data', function (chunk) { + body += chunk; + }); + res.on('end', function () { + winston.info('status ' + ecosystem + this.statusCode); + if (this.statusCode == 200 || this.statusCode == 202) { + let response = JSON.parse(body); + winston.debug('response ' + ecosystem + response); + //connection.console.log('response comp analysis' + response); + metadataCache[cacheKey] = response; + cb(response); + } + else { + cb(null); + } + }); + }).on('error', function (e) { + winston.info("Got error: " + e.message); + }); +}; +let sentiment_api_call = (ecosystem, name, version, cb) => { + http.get("http://sentiment-http-sentiment-score.dev.rdu2c.fabric8.io/api/v1.0/getsentimentanalysis/?package=" + name, function (res) { + let body = ''; + res.on('data', function (chunk) { + body += chunk; + }); + res.on('end', function () { + winston.info('status ' + this.statusCode); + if (this.statusCode == 200 || this.statusCode == 202) { + let response = JSON.parse(body); + winston.debug('response ' + response); + //metadataCache[cacheKey] = response; + cb(response); + } + else { + cb(null); + } + }); + }).on('error', function (e) { + winston.info("Got error: " + e.message); + }); +}; +let pollFunc = (fn, id, timeout, interval, cb) => { + let startTime = (new Date()).getTime(); + interval = interval || 20000; + //let canPoll = true; + (function p() { + //canPoll = ((new Date).getTime() - startTime) <= timeout; + fn(id, p, (response) => { + if (response) { + cb(response); + } + else { + setTimeout(p, 20000); + } + }); + })(); +}; +let makeStackAnalysisCall = (id, p, callbk) => { + if (id) { + const options = url.parse("http://bayesian-api-bayesian-preview.b6ff.rh-idev.openshiftapps.com"); + options['path'] += "/api/v1/stack-analyses-v2/" + id; + options['headers'] = { 'Authorization': 'Bearer ' + '' }; + http.get(options, function (res) { + let body = ''; + res.on('data', function (chunk) { + body += chunk; + }); + res.on('end', function () { + winston.info('status ' + this.statusCode); + if (this.statusCode == 200 || this.statusCode == 202) { + let response = JSON.parse(body); + if (response.hasOwnProperty("error")) { + winston.debug("stack-analyses-v2 in progress!!"); + callbk(null); + } + else { + winston.debug('response stack-analyses-v2' + response.result[0].user_stack_info.dependencies); + callbk(response.result[0].user_stack_info.dependencies); + } + } + else { + winston.debug("repeat!!"); + callbk(null); + } + }); + }).on('error', function (e) { + winston.info("Got error[stack-analyses-v2]: " + e.message); + callbk(null); + }); + } +}; +let stack_analysis_call_file_upload = (filename, contents, contentType, cb) => { + //const options = url.parse(config.server_url); + //options['method'] = 'POST'; + //options['uri'] = config.server_url +`/stack-analyses/`; + //options['headers'] = {'Authorization': 'Bearer ' + config.api_token}; + const options = {}; + options['uri'] = "http://bayesian-api-bayesian-preview.b6ff.rh-idev.openshiftapps.com/api/v1/stack-analyses-v2"; + options['headers'] = { 'Authorization': 'Bearer ' + '' }; + winston.debug('post file upload' + options['uri']); + var req = request.post(options, function (err, resp, body) { + if (err) { + cb(null); + winston.info("Got error file upload[stack-analyses-v2]: " + err); + } + else { + var k = JSON.parse(body); + cb(k.id); + } + }); + var form = req.form(); + //form.append('manifest[]', fs.createReadStream(filename)); + form.append('manifest[]', contents, { + filename: filename, + contentType: contentType + }); +}; +files.on(EventStream.Diagnostics, "^package\\.json$", (uri, name, contents) => { + /* Convert from readable stream into string */ + let stream = utils_1.stream_from_string(contents); + let collector = new collector_1.DependencyCollector(null); + collector.collect(stream).then((deps) => { + let diagnostics = []; + /* Aggregate asynchronous requests and send the diagnostics at once */ + let aggregator = new Aggregator(deps, () => { + connection.sendDiagnostics({ uri: uri, diagnostics: diagnostics }); + }); + for (let dependency of deps) { + get_metadata('npm', dependency.name.value, dependency.version.value, (response) => { + if (response != null) { + let pipeline = new consumers_1.DiagnosticsPipeline(DiagnosticsEngines, dependency, config, diagnostics); + pipeline.run(response); + } + aggregator.aggregate(dependency); + }); + //TODO :: sentiment analysis + // sentiment_api_call('npm', dependency.name.value, dependency.version.value, (response) => { + // if (response != null) { + // let pipeline = new DiagnosticsPipelineSenti(DiagnosticsEnginesSenti, dependency, config, diagnostics); + // pipeline.run(response); + // } + // aggregator.aggregate(dependency); + // }); + } + }); +}); +files.on(EventStream.Diagnostics, "^pom\\.xml$", (uri, name, contents) => { + /* Convert from readable stream into string */ + let stream = utils_1.stream_from_string(contents); + connection.console.log('mvn stream' + stream); + let collector = new collector_1.PomXmlDependencyCollector(); + collector.collect(stream).then((deps) => { + let diagnostics = []; + /* Aggregate asynchronous requests and send the diagnostics at once */ + let aggregator = new Aggregator(deps, () => { + connection.sendDiagnostics({ uri: uri, diagnostics: diagnostics }); + }); + for (let dependency of deps) { + //connection.console.log('mvn cmp name'+ dependency.name.value); + get_metadata('maven', dependency.name.value, dependency.version.value, (response) => { + if (response != null) { + let pipeline = new consumers_1.DiagnosticsPipeline(DiagnosticsEngines, dependency, config, diagnostics); + pipeline.run(response); + } + aggregator.aggregate(dependency); + }); + //winston.debug('on file '); + // sentiment_api_call('maven', dependency.name.value, dependency.version.value, (response) => { + // if (response != null) { + // let pipeline = new DiagnosticsPipelineSenti(DiagnosticsEnginesSenti, dependency, config, diagnostics); + // pipeline.run(response); + // } + // aggregator.aggregate(dependency); + // }); + } + }); +}); +let stackID; +files.on(EventStream.Diagnostics, "^requirements\\.txt$", (uri, name, contents) => { + let collector = new collector_1.ReqDependencyCollector(); + let StackArr = []; + let triggerDiagnosticAggregation = () => { + collector.collect(contents).then((deps) => { + let diagnostics = []; + /* Aggregate asynchronous requests and send the diagnostics at once */ + let aggregator = new Aggregator(deps, () => { + connection.sendDiagnostics({ uri: uri, diagnostics: diagnostics }); + }); + for (let dependency of deps) { + get_metadata('pypi', dependency.name.value, dependency.version.value, (response) => { + if (response != null) { + let pipeline = new consumers_1.DiagnosticsPipeline(DiagnosticsEngines, dependency, config, diagnostics); + pipeline.run(response); + } + aggregator.aggregate(dependency); + }); + // sentiment_api_call('pypi', dependency.name.value, dependency.version.value, (response) => { + // if (response != null) { + // let pipeline = new DiagnosticsPipelineSenti(DiagnosticsEnginesSenti, dependency, config, diagnostics); + // pipeline.run(response); + // } + // aggregator.aggregate(dependency); + // }); + // if(StackArr.length>0){ + // //connection.console.log("dep name ===> "+dependency.name.value); + // form_stack_data(dependency.name.value, StackArr, (response) => { + // if (response != null) { + // let aShowMessageParamsInstance = new AShowMessageParamsInstance(3,"Stack analysis is processed successfully!!"); + // connection.sendNotification(ShowMessageNotification.type,aShowMessageParamsInstance); + // let pipeline = new DiagnosticsPipelineStack(DiagnosticsEnginesStack, dependency, config, diagnostics); + // pipeline.run(response); + // } + // aggregator.aggregate(dependency); + // }); + // } + } + }); + }; + // if(stackID){ + // StackArr = []; + // stackID = false; + // stack_analysis_call_file_upload("requirements.txt", contents, "text/plain" ,(response) => { + // stackID = true; + // if (response != null) { + // StackArr = []; + // stackID = false; + // let aShowMessageParamsInstance = new AShowMessageParamsInstance(3,"Stack analysis triggerd for "+response); + // connection.sendNotification(ShowMessageNotification.type,aShowMessageParamsInstance); + // pollFunc(makeStackAnalysisCall, response, 95000, 20000, (response) => { + // StackArr = response; + // triggerDiagnosticAggregation(); + // }); + // } + // }); + // } + triggerDiagnosticAggregation(); +}); +let form_stack_data = (dependency, stackArr, cb) => { + for (var i = 0; i < stackArr.length; i++) { + if (stackArr[i].name == dependency) { + cb(stackArr[i]); + } + } + cb(null); +}; +let checkDelay; +connection.onDidSaveTextDocument((params) => { + winston.debug('on save ' + params.textDocument.uri); + clearTimeout(checkDelay); + server.handle_file_event(params.textDocument.uri, server.files.file_data[params.textDocument.uri]); +}); +connection.onDidChangeTextDocument((params) => { + winston.debug('on change ' + params.textDocument.uri); + /* Update internal state for code lenses */ + server.files.file_data[params.textDocument.uri] = params.contentChanges[0].text; + server.handle_file_event(params.textDocument.uri, server.files.file_data[params.textDocument.uri]); + clearTimeout(checkDelay); + checkDelay = setTimeout(() => { + server.handle_file_event(params.textDocument.uri, server.files.file_data[params.textDocument.uri]); + }, 500); +}); +connection.onDidOpenTextDocument((params) => { + winston.debug('on file open ' + params.textDocument.uri); + stackID = true; + server.handle_file_event(params.textDocument.uri, params.textDocument.text); +}); +connection.onCodeAction((params, token) => { + clearTimeout(checkDelay); + let commands = []; + for (let diagnostic of params.context.diagnostics) { + let command = consumers_1.codeActionsMap[diagnostic.message]; + if (command != null) { + commands.push(command); + } + } + return commands; +}); +connection.onDidCloseTextDocument((params) => { + clearTimeout(checkDelay); +}); +connection.listen(); +//# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/server/server.js.map b/server/server.js.map new file mode 100644 index 00000000..1a72bf4d --- /dev/null +++ b/server/server.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server.js","sourceRoot":"","sources":["../../server/src/server.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAChG,YAAY,CAAC;;AACb,6BAA6B;AAC7B,yBAAyB;AACzB,i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,UAAU,CAAC,qBAAqB,CAAC,CAAC,MAAM;IACpC,OAAO,CAAC,KAAK,CAAC,eAAe,GAAE,MAAM,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC;IACxD,OAAO,GAAG,IAAI,CAAC;IACf,MAAM,CAAC,iBAAiB,CAAC,MAAM,CAAC,YAAY,CAAC,GAAG,EAAE,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC;AAChF,CAAC,CAAC,CAAC;AAEH,UAAU,CAAC,YAAY,CAAC,CAAC,MAAM,EAAE,KAAK;IAClC,YAAY,CAAC,UAAU,CAAC,CAAC;IACzB,IAAI,QAAQ,GAAc,EAAE,CAAC;IAC7B,GAAG,CAAC,CAAC,IAAI,UAAU,IAAI,MAAM,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC;QAChD,IAAI,OAAO,GAAG,0BAAc,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QACjD,EAAE,CAAC,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC,CAAC;YAClB,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAA;QAC1B,CAAC;IACL,CAAC;IACD,MAAM,CAAC,QAAQ,CAAA;AACnB,CAAC,CAAC,CAAC;AAEH,UAAU,CAAC,sBAAsB,CAAC,CAAC,MAAM;IACrC,YAAY,CAAC,UAAU,CAAC,CAAC;AAC7B,CAAC,CAAC,CAAC;AAEH,UAAU,CAAC,MAAM,EAAE,CAAC"} \ No newline at end of file diff --git a/server/stackanalysis.js b/server/stackanalysis.js new file mode 100644 index 00000000..050ac26f --- /dev/null +++ b/server/stackanalysis.js @@ -0,0 +1,131 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Pavel Odvody 2016 + * Licensed under the Apache-2.0 License. See License.txt in the project root for license information. + * ------------------------------------------------------------------------------------------ */ +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +const utils_1 = require("./utils"); +const vscode_languageserver_1 = require("vscode-languageserver"); +; +/* Bind & return the part of `obj` as described by `desc` */ +let bind_object = (obj, desc) => { + let bind = obj; + for (let elem of desc.path) { + if (elem in bind) { + bind = bind[elem]; + } + else { + return null; + } + } + return bind; +}; +; +; +; +; +/* Diagnostics pipeline implementation */ +class DiagnosticsPipelineStack { + constructor(classes, dependency, config, diags) { + this.items = classes.map((i) => { return new i(dependency, config); }); + this.dependency = dependency; + this.config = config; + this.diagnostics = diags; + } + run(data) { + for (let item of this.items) { + if (item.consume(data)) { + for (let d of item.produce()) + this.diagnostics.push(d); + } + } + return this.diagnostics; + } +} +exports.DiagnosticsPipelineStack = DiagnosticsPipelineStack; +; +/* A consumer that uses the binding interface to consume a metadata object */ +class AnalysisConsumer { + constructor(config) { + this.config = config; + this.changeTo = null; + } + consume(data) { + if (data || data.osio_user_count && data.sentiment.hasOwnProperty("overall_score") || + data.licenses) { + let stackCommentObj = { + "sentiment": "", + "osio_user_count": "", + "licenses": [] + }; + if (data.sentiment.hasOwnProperty("overall_score")) { + if (Number(data.sentiment.overall_score) > 0) { + stackCommentObj.sentiment = "Postive"; + } + else if (Number(data.sentiment.overall_score) < 0) { + stackCommentObj.sentiment = "Negative"; + } + else { + stackCommentObj.sentiment = "Neutral"; + } + } + //stackCommentObj['timestamp'] = data.sentiment_details.latest_comment_time; + stackCommentObj.osio_user_count = data.osio_user_count; + stackCommentObj.licenses = data.licenses; + this.item = []; + this.item.push(stackCommentObj); + } + return this.item != null; + } +} +; +/* We've received an empty/unfinished result, display that analysis is pending */ +class EmptyResultEngineStack extends AnalysisConsumer { + constructor(context, config) { + super(config); + this.context = context; + } + produce() { + if (this.item == {} || + this.item.finished_at === undefined || + this.item.finished_at == null) { + return [{ + severity: vscode_languageserver_1.DiagnosticSeverity.Information, + range: utils_1.get_range(this.context.version), + message: `Package ${this.context.name.value}-${this.context.version.value} - analysis is pending`, + source: 'Sentiment Analysis' + }]; + } + else { + return []; + } + } +} +exports.EmptyResultEngineStack = EmptyResultEngineStack; +/* Report CVEs in found dependencies */ +class SecurityEngineStack extends AnalysisConsumer { + constructor(context, config) { + super(config); + this.context = context; + } + produce() { + if (this.item.length > 0) { + let sentimentData = this.item; + let diagnostic = { + severity: vscode_languageserver_1.DiagnosticSeverity.Information, + range: utils_1.get_range(this.context.version), + message: `osio user count : ${sentimentData[0].osio_user_count} , Licences : [${sentimentData[0].licenses}]`, + source: 'Stack Analysis' + }; + return [diagnostic]; + } + else { + return []; + } + } +} +exports.SecurityEngineStack = SecurityEngineStack; +; +let codeActionsMapStack = new Map(); +exports.codeActionsMapStack = codeActionsMapStack; +//# sourceMappingURL=stackanalysis.js.map \ No newline at end of file diff --git a/server/stackanalysis.js.map b/server/stackanalysis.js.map new file mode 100644 index 00000000..67ec510a --- /dev/null +++ b/server/stackanalysis.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stackanalysis.js","sourceRoot":"","sources":["../../server/src/stackanalysis.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAChG,YAAY,CAAC;;AAEb,mCAAoC;AACpC,iEAA+E;AAM9E,CAAC;AAEF,4DAA4D;AAC5D,IAAI,WAAW,GAAG,CAAC,GAAQ,EAAE,IAAwB;IACjD,IAAI,IAAI,GAAG,GAAG,CAAC;IACf,GAAG,CAAC,CAAC,IAAI,IAAI,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC;QACzB,EAAE,CAAC,CAAC,IAAI,IAAI,IAAI,CAAC,CAAC,CAAC;YACf,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,CAAC;QACtB,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,MAAM,CAAC,IAAI,CAAC;QAChB,CAAC;IACL,CAAC;IACD,MAAM,CAAC,IAAI,CAAC;AAChB,CAAC,CAAC;AAQD,CAAC;AAMD,CAAC;AAG2D,CAAC;AAO7D,CAAC;AAKF,yCAAyC;AACzC;IAMI,YAAY,OAAmB,EAAE,UAAuB,EAAE,MAAW,EAAE,KAAwB;QAC3F,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,G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AAI,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,wBAAwB;oBACjG,MAAM,EAAE,oBAAoB;iBAC/B,CAAC,CAAA;QACN,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,MAAM,CAAC,EAAE,CAAC;QACd,CAAC;IACL,CAAC;CACJ;AA2BuD,wDAAsB;AAzB9E,uCAAuC;AACvC,yBAA0B,SAAQ,gBAAgB;IAE9C,YAAmB,OAAoB,EAAE,MAAW;QAChD,KAAK,CAAC,MAAM,CAAC,CAAC;QADC,YAAO,GAAP,OAAO,CAAa;IAEvC,CAAC;IAED,OAAO;QACH,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC;YACvB,IAAI,aAAa,GAAe,IAAI,CAAC,IAAI,CAAC;YAC1C,IAAI,UAAU,GAAG;gBACb,QAAQ,EAAE,0CAAkB,CAAC,WAAW;gBACxC,KAAK,EAAE,iBAAS,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC;gBACtC,OAAO,EAAE,qBAAqB,aAAa,CAAC,CAAC,CAAC,CAAC,eAAe,kBAAkB,aAAa,CAAC,CAAC,CAAC,CAAC,QAAQ,GAAG;gBAC5G,MAAM,EAAE,gBAAgB;aAC3B,CAAC;YACF,MAAM,CAAC,CAAC,UAAU,CAAC,CAAA;QACvB,CAAC;QAAC,IAAI,CAAC,CAAC;YACJ,MAAM,CAAC,EAAE,CAAC;QACd,CAAC;IACL,CAAC;CACJ;AAIkC,kDAAmB;AAJrD,CAAC;AAEF,IAAI,mBAAmB,GAAG,IAAI,GAAG,EAAmB,CAAC;AAE2B,kDAAmB"} \ No newline at end of file diff --git a/server/utils.js b/server/utils.js new file mode 100644 index 00000000..a889aa5c --- /dev/null +++ b/server/utils.js @@ -0,0 +1,44 @@ +/* -------------------------------------------------------------------------------------------- + * Copyright (c) Pavel Odvody 2016 + * Licensed under the Apache-2.0 License. See License.txt in the project root for license information. + * ------------------------------------------------------------------------------------------ */ +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +const stream_1 = require("stream"); +exports.stream_from_string = (s) => { + let stream = new stream_1.Readable(); + stream.push(s); + stream.push(null); + return stream; +}; +/* VSCode and Che transmit the file buffer in a different manner, + * so we have to use different functions for computing the + * positions and ranges so that the lines are rendered properly. + */ +let _to_lsp_position_vscode = (pos) => { + return { line: pos.line / 2, character: pos.column - 1 }; +}; +let _get_range_vscode = (ps) => { + let length = ps.value.length; + return { + start: exports.to_lsp_position(ps.position), + end: { line: ps.position.line / 2, character: ps.position.column + length - 1 } + }; +}; +let _to_lsp_position_che = (pos) => { + return { line: pos.line - 1, character: pos.column - 1 }; +}; +let _get_range_che = (ps) => { + let length = ps.value.length; + return { + start: exports.to_lsp_position(ps.position), + end: { line: ps.position.line - 1, character: ps.position.column + length - 1 } + }; +}; +exports.to_lsp_position = (pos) => { + return _to_lsp_position_che(pos); +}; +exports.get_range = (ps) => { + return _get_range_che(ps); +}; +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/server/utils.js.map b/server/utils.js.map new file mode 100644 index 00000000..7adfdfce --- /dev/null +++ b/server/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../server/src/utils.ts"],"names":[],"mappings":"AAAA;;;gGAGgG;AAChG,YAAY,CAAC;;AACb,mCAA0C;AAK/B,QAAA,kBAAkB,GAAG,CAAC,CAAS;IACxC,IAAI,MAAM,GAAG,IAAI,iBAAQ,EAAE,CAAC;IAC5B,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACf,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAClB,MAAM,CAAC,MAAM,CAAC;AAChB,CAAC,CAAA;AAED;;;GAGG;AACH,IAAI,uBAAuB,GAAG,CAAC,GAAc;IAC3C,MAAM,CAAC,EAAC,IAAI,EAAE,GAAG,CAAC,IAAI,GAAC,CAAC,EAAE,SAAS,EAAE,GAAG,C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/src/extension.ts +++ b/src/extension.ts @@ -2,9 +2,47 @@ import * as vscode from 'vscode'; +import * as path from 'path'; +import { LanguageClient, LanguageClientOptions, SettingMonitor, ServerOptions, TransportKind } from 'vscode-languageclient'; export function activate(context: vscode.ExtensionContext) { + /******************* START:: LSP client ***********************/ + + // The server is implemented in node + let serverModule = context.asAbsolutePath(path.join('server', 'server.js')); + // The debug options for the server + let debugOptions = { execArgv: ["--nolazy", "--debug=6009"] }; + + let lastTagged = context.globalState.get('lastTagged', ''); + if(lastTagged) { + process.env['RECOMMENDER_API_TOKEN'] = lastTagged; + } + + // If the extension is launched in debug mode then the debug server options are used + // Otherwise the run options are used + let serverOptions: ServerOptions = { + run : { module: serverModule, transport: TransportKind.ipc }, + debug: { module: serverModule, transport: TransportKind.ipc, options: debugOptions } + } + + // Options to control the language client + let clientOptions: LanguageClientOptions = { + // Register the server for plain text documents 'plaintext','xml','json' + documentSelector: [], + synchronize: { + // Synchronize the setting section 'languageServerExample' to the server + configurationSection: 'languageServerExample', + // Notify the server about file changes to '.clientrc files contain in the workspace + fileEvents: vscode.workspace.createFileSystemWatcher('**/.clientrc') + } + } + + // Create the language client and start the client. + let disposableLSp = new LanguageClient('languageServerExample', 'Language Server Example', serverOptions, clientOptions).start(); + + /******************* END :: LSP client ***********************/ + let previewUri = vscode.Uri.parse('fabric8-analytics-widget://authority/fabric8-analytics-widget'); const loader = ` @@ -645,7 +683,7 @@ let render_stack_iframe = (sa) => { thatContext.globalState.update('lastTagged', ''); vscode.window.showErrorMessage(`Looks like your token is not proper, kindly re-run stack analysis`); cb(null); - }else { + } else { vscode.window.showErrorMessage(`Failed to trigger stack analysis, Status: ${httpResponse.statusCode}`); cb(null); } @@ -667,7 +705,7 @@ let render_stack_iframe = (sa) => { let editor = vscode.window.activeTextEditor; let text = editor.document.getText(); - //get_stack_metadata(editor.document.uri, {manifest: text, origin: 'lsp'}, (data) => { provider.signal(previewUri, data) }); + // get_stack_metadata(editor.document.uri, {manifest: text, origin: 'lsp'}, (data) => { provider.signal(previewUri, data) }); provider.signalInit(previewUri,null); let answer1: string; @@ -677,10 +715,11 @@ let render_stack_iframe = (sa) => { } let lastTagged = context.globalState.get('lastTagged', ''); - if(!lastTagged) { + if(!lastTagged) { vscode.window.showInputBox(options).then(value => { if (!value) return; STACK_API_TOKEN = value; + process.env['RECOMMENDER_API_TOKEN'] = STACK_API_TOKEN; context.globalState.update('lastTagged', STACK_API_TOKEN); return vscode.commands.executeCommand('vscode.previewHtml', previewUri, vscode.ViewColumn.One, 'fabric8-analytics stack report').then((success) => { get_stack_metadata(editor.document.uri, {manifest: text, origin: 'lsp'}, (data) => { provider.signal(previewUri, data) }); @@ -691,6 +730,7 @@ let render_stack_iframe = (sa) => { }); } else { STACK_API_TOKEN = lastTagged; + process.env['RECOMMENDER_API_TOKEN'] = lastTagged; return vscode.commands.executeCommand('vscode.previewHtml', previewUri, vscode.ViewColumn.One, 'fabric8-analytics stack report').then((success) => { get_stack_metadata(editor.document.uri, {manifest: text, origin: 'lsp'}, (data) => { provider.signal(previewUri, data) }); provider.signalInit(previewUri,null); @@ -698,10 +738,8 @@ let render_stack_iframe = (sa) => { vscode.window.showErrorMessage(reason); }); } - - }); let highlight = vscode.window.createTextEditorDecorationType({ backgroundColor: 'rgba(0,0,0,.35)' }); - context.subscriptions.push(disposable, registration); + context.subscriptions.push(disposable, registration, disposableLSp); }