Move bower/package.json dependency completions to javascript extension

This commit is contained in:
Martin Aeschlimann
2016-04-18 17:55:22 +02:00
parent 4fe233c752
commit 235cbcdf9d
33 changed files with 703 additions and 1844 deletions

View File

@@ -0,0 +1,29 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Extension",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--extensionDevelopmentPath=${workspaceRoot}"
],
"stopOnEntry": false,
"sourceMaps": true,
"outDir": "${workspaceRoot}/out",
"preLaunchTask": "npm"
},
{
"name": "Launch Tests",
"type": "extensionHost",
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceRoot}", "--extensionTestsPath=${workspaceRoot}/out/test" ],
"stopOnEntry": false,
"sourceMaps": true,
"outDir": "${workspaceRoot}/out/test",
"preLaunchTask": "npm"
}
]
}

View File

@@ -0,0 +1,30 @@
// Available variables which can be used inside of strings.
// ${workspaceRoot}: the root folder of the team
// ${file}: the current opened file
// ${fileBasename}: the current opened file's basename
// ${fileDirname}: the current opened file's dirname
// ${fileExtname}: the current opened file's extension
// ${cwd}: the current working directory of the spawned process
// A task runner that calls a custom npm script that compiles the extension.
{
"version": "0.1.0",
// we want to run npm
"command": "npm",
// the command is a shell script
"isShellCommand": true,
// show the output window only if unrecognized errors occur.
"showOutput": "silent",
// we run the custom script "compile" as defined in package.json
"args": ["run", "compile"],
// The tsc compiler is started in watching mode
"isWatching": true,
// use the standard tsc in watch mode problem matcher to find compile problems in the output.
"problemMatcher": "$tsc-watch"
}

View File

@@ -2,8 +2,19 @@
"name": "javascript",
"version": "0.1.0",
"publisher": "vscode",
"engines": {
"vscode": "*"
"engines": { "vscode": "0.10.x" },
"activationEvents": [
"onLanguage:javascript", "onLanguage:json"
],
"main": "./out/javascriptMain",
"dependencies": {
"vscode-nls": "^1.0.4",
"request-light": "^0.0.3",
"jsonc-parser": "^0.0.1"
},
"scripts": {
"compile": "gulp compile-extension:javascript",
"watch": "gulp watch-extension:javascript"
},
"contributes": {
"languages": [

View File

@@ -0,0 +1,177 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {MarkedString, CompletionItemKind, CompletionItem, DocumentSelector} from 'vscode';
import {IJSONContribution, ISuggestionsCollector} from './jsonContributions';
import {XHRRequest} from 'request-light';
import {Location} from 'jsonc-parser';
import * as nls from 'vscode-nls';
const localize = nls.loadMessageBundle();
export class BowerJSONContribution implements IJSONContribution {
private topRanked = ['twitter','bootstrap','angular-1.1.6','angular-latest','angulerjs','d3','myjquery','jq','abcdef1234567890','jQuery','jquery-1.11.1','jquery',
'sushi-vanilla-x-data','font-awsome','Font-Awesome','font-awesome','fontawesome','html5-boilerplate','impress.js','homebrew',
'backbone','moment1','momentjs','moment','linux','animate.css','animate-css','reveal.js','jquery-file-upload','blueimp-file-upload','threejs','express','chosen',
'normalize-css','normalize.css','semantic','semantic-ui','Semantic-UI','modernizr','underscore','underscore1',
'material-design-icons','ionic','chartjs','Chart.js','nnnick-chartjs','select2-ng','select2-dist','phantom','skrollr','scrollr','less.js','leancss','parser-lib',
'hui','bootstrap-languages','async','gulp','jquery-pjax','coffeescript','hammer.js','ace','leaflet','jquery-mobile','sweetalert','typeahead.js','soup','typehead.js',
'sails','codeigniter2'];
public constructor(private xhr: XHRRequest) {
}
public getDocumentSelector(): DocumentSelector {
return [{ language: 'json', pattern: '**/bower.json' }, { language: 'json', pattern: '**/.bower.json' }];
}
public collectDefaultSuggestions(resource: string, collector: ISuggestionsCollector): Thenable<any> {
let defaultValue = {
'name': '{{name}}',
'description': '{{description}}',
'authors': [ '{{author}}' ],
'version': '{{1.0.0}}',
'main': '{{pathToMain}}',
'dependencies': {}
};
let proposal = new CompletionItem(localize('json.bower.default', 'Default bower.json'));
proposal.kind = CompletionItemKind.Class;
proposal.insertText = JSON.stringify(defaultValue, null, '\t');
collector.add(proposal);
return Promise.resolve(null);
}
public collectPropertySuggestions(resource: string, location: Location, currentWord: string, addValue: boolean, isLast:boolean, collector: ISuggestionsCollector) : Thenable<any> {
if ((location.matches(['dependencies']) || location.matches(['devDependencies']))) {
if (currentWord.length > 0) {
let queryUrl = 'https://bower.herokuapp.com/packages/search/' + encodeURIComponent(currentWord);
return this.xhr({
url : queryUrl
}).then((success) => {
if (success.status === 200) {
try {
let obj = JSON.parse(success.responseText);
if (Array.isArray(obj)) {
let results = <{name:string; description:string;}[]> obj;
for (let i = 0; i < results.length; i++) {
let name = results[i].name;
let description = results[i].description || '';
let insertText = JSON.stringify(name);
if (addValue) {
insertText += ': "{{latest}}"';
if (!isLast) {
insertText += ',';
}
}
let proposal = new CompletionItem(name);
proposal.kind = CompletionItemKind.Property;
proposal.insertText = insertText;
proposal.documentation = description;
collector.add(proposal);
}
collector.setAsIncomplete();
}
} catch (e) {
// ignore
}
} else {
collector.error(localize('json.bower.error.repoaccess', 'Request to the bower repository failed: {0}', success.responseText));
return 0;
}
}, (error) => {
collector.error(localize('json.bower.error.repoaccess', 'Request to the bower repository failed: {0}', error.responseText));
return 0;
});
} else {
this.topRanked.forEach((name) => {
let insertText = JSON.stringify(name);
if (addValue) {
insertText += ': "{{latest}}"';
if (!isLast) {
insertText += ',';
}
}
let proposal = new CompletionItem(name);
proposal.kind = CompletionItemKind.Property;
proposal.insertText = insertText;
proposal.documentation = '';
collector.add(proposal);
});
collector.setAsIncomplete();
return Promise.resolve(null);
}
}
return null;
}
public collectValueSuggestions(resource: string, location: Location, collector: ISuggestionsCollector): Thenable<any> {
// not implemented. Could be do done calling the bower command. Waiting for web API: https://github.com/bower/registry/issues/26
let proposal = new CompletionItem(localize('json.bower.latest.version', 'latest'));
proposal.insertText = '"{{latest}}"';
proposal.kind = CompletionItemKind.Value;
proposal.documentation = 'The latest version of the package';
collector.add(proposal);
return Promise.resolve(null);
}
public resolveSuggestion(item: CompletionItem) : Thenable<CompletionItem> {
if (item.kind === CompletionItemKind.Property && item.documentation === '') {
return this.getInfo(item.label).then(documentation => {
if (documentation) {
item.documentation = documentation;
return item;
}
return null;
});
};
return null;
}
private getInfo(pack: string): Thenable<string> {
let queryUrl = 'https://bower.herokuapp.com/packages/' + encodeURIComponent(pack);
return this.xhr({
url : queryUrl
}).then((success) => {
try {
let obj = JSON.parse(success.responseText);
if (obj && obj.url) {
let url : string = obj.url;
if (url.indexOf('git://') === 0) {
url = url.substring(6);
}
if (url.lastIndexOf('.git') === url.length - 4) {
url = url.substring(0, url.length - 4);
}
return url;
}
} catch (e) {
// ignore
}
return void 0;
}, (error) => {
return void 0;
});
}
public getInfoContribution(resource: string, location: Location): Thenable<MarkedString[]> {
if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']))) {
let pack = location.segments[location.segments.length - 1];
let htmlContent : MarkedString[] = [];
htmlContent.push(localize('json.bower.package.hover', '{0}', pack));
return this.getInfo(pack).then(documentation => {
if (documentation) {
htmlContent.push(documentation);
}
return htmlContent;
});
}
return null;
}
}

View File

@@ -0,0 +1,154 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {Location, getLocation, createScanner, SyntaxKind} from 'jsonc-parser';
import {basename} from 'path';
import {BowerJSONContribution} from './bowerJSONContribution';
import {PackageJSONContribution} from './packageJSONContribution';
import {XHRRequest} from 'request-light';
import {CompletionItem, CompletionItemProvider, CompletionList, TextDocument, Position, Hover, HoverProvider,
CancellationToken, Range, TextEdit, MarkedString, DocumentSelector, languages} from 'vscode';
export interface ISuggestionsCollector {
add(suggestion: CompletionItem): void;
error(message:string): void;
log(message:string): void;
setAsIncomplete(): void;
}
export interface IJSONContribution {
getDocumentSelector(): DocumentSelector;
getInfoContribution(fileName: string, location: Location) : Thenable<MarkedString[]>;
collectPropertySuggestions(fileName: string, location: Location, currentWord: string, addValue: boolean, isLast:boolean, result: ISuggestionsCollector) : Thenable<any>;
collectValueSuggestions(fileName: string, location: Location, result: ISuggestionsCollector): Thenable<any>;
collectDefaultSuggestions(fileName: string, result: ISuggestionsCollector): Thenable<any>;
resolveSuggestion?(item: CompletionItem): Thenable<CompletionItem>;
}
export function addJSONProviders(xhr: XHRRequest, subscriptions: { dispose(): any }[]) {
let contributions = [new PackageJSONContribution(xhr), new BowerJSONContribution(xhr)];
contributions.forEach(contribution => {
let selector = contribution.getDocumentSelector();
subscriptions.push(languages.registerCompletionItemProvider(selector, new JSONCompletionItemProvider(contribution), '.', '$'));
subscriptions.push(languages.registerHoverProvider(selector, new JSONHoverProvider(contribution)));
});
}
export class JSONHoverProvider implements HoverProvider {
constructor(private jsonContribution: IJSONContribution) {
}
public provideHover(document: TextDocument, position: Position, token: CancellationToken): Thenable<Hover> {
let fileName = basename(document.fileName);
let offset = document.offsetAt(position);
let location = getLocation(document.getText(), offset);
let node = location.previousNode;
if (node && node.offset <= offset && offset <= node.offset + node.length) {
let promise = this.jsonContribution.getInfoContribution(fileName, location);
if (promise) {
return promise.then(htmlContent => {
let range = new Range(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
let result: Hover = {
contents: htmlContent,
range: range
};
return result;
});
}
}
return null;
}
}
export class JSONCompletionItemProvider implements CompletionItemProvider {
constructor(private jsonContribution: IJSONContribution) {
}
public resolveCompletionItem(item: CompletionItem, token: CancellationToken) : Thenable<CompletionItem> {
if (this.jsonContribution.resolveSuggestion) {
let resolver = this.jsonContribution.resolveSuggestion(item);
if (resolver) {
return resolver;
}
}
return Promise.resolve(item);
}
public provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken): Thenable<CompletionList> {
let fileName = basename(document.fileName);
let currentWord = this.getCurrentWord(document, position);
let overwriteRange = null;
let items: CompletionItem[] = [];
let isIncomplete = false;
let offset = document.offsetAt(position);
let location = getLocation(document.getText(), offset);
let node = location.previousNode;
if (node && node.offset <= offset && offset <= node.offset + node.length && (node.type === 'property' || node.type === 'string' || node.type === 'number' || node.type === 'boolean' || node.type === 'null')) {
overwriteRange = new Range(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
} else {
overwriteRange = new Range(document.positionAt(offset - currentWord.length), position);
}
let proposed: { [key: string]: boolean } = {};
let collector: ISuggestionsCollector = {
add: (suggestion: CompletionItem) => {
if (!proposed[suggestion.label]) {
proposed[suggestion.label] = true;
if (overwriteRange) {
suggestion.textEdit = TextEdit.replace(overwriteRange, suggestion.insertText);
}
items.push(suggestion);
}
},
setAsIncomplete: () => isIncomplete = true,
error: (message: string) => console.error(message),
log: (message: string) => console.log(message)
};
let collectPromise : Thenable<any> = null;
if (location.completeProperty) {
let addValue = !location.previousNode || !location.previousNode.columnOffset;
let scanner = createScanner(document.getText(), true);
scanner.setPosition(offset);
scanner.scan();
let isLast = scanner.getToken() === SyntaxKind.CloseBraceToken || scanner.getToken() === SyntaxKind.EOF;
collectPromise = this.jsonContribution.collectPropertySuggestions(fileName, location, currentWord, addValue, isLast, collector);
} else {
if (location.segments.length === 0) {
collectPromise = this.jsonContribution.collectDefaultSuggestions(fileName, collector);
} else {
collectPromise = this.jsonContribution.collectValueSuggestions(fileName, location, collector);
}
}
if (collectPromise) {
return collectPromise.then(() => {
if (items.length > 0) {
return new CompletionList(items, isIncomplete);
}
return null;
});
}
return null;
}
private getCurrentWord(document: TextDocument, position: Position) {
var i = position.character - 1;
var text = document.lineAt(position.line).text;
while (i >= 0 && ' \t\n\r\v":{[,'.indexOf(text.charAt(i)) === -1) {
i--;
}
return text.substring(i+1, position.character);
}
}

View File

@@ -0,0 +1,220 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {MarkedString, CompletionItemKind, CompletionItem, DocumentSelector} from 'vscode';
import {IJSONContribution, ISuggestionsCollector} from './jsonContributions';
import {XHRRequest} from 'request-light';
import {Location} from 'jsonc-parser';
import * as nls from 'vscode-nls';
const localize = nls.loadMessageBundle();
let LIMIT = 40;
export class PackageJSONContribution implements IJSONContribution {
private mostDependedOn = [ 'lodash', 'async', 'underscore', 'request', 'commander', 'express', 'debug', 'chalk', 'colors', 'q', 'coffee-script',
'mkdirp', 'optimist', 'through2', 'yeoman-generator', 'moment', 'bluebird', 'glob', 'gulp-util', 'minimist', 'cheerio', 'jade', 'redis', 'node-uuid',
'socket', 'io', 'uglify-js', 'winston', 'through', 'fs-extra', 'handlebars', 'body-parser', 'rimraf', 'mime', 'semver', 'mongodb', 'jquery',
'grunt', 'connect', 'yosay', 'underscore', 'string', 'xml2js', 'ejs', 'mongoose', 'marked', 'extend', 'mocha', 'superagent', 'js-yaml', 'xtend',
'shelljs', 'gulp', 'yargs', 'browserify', 'minimatch', 'react', 'less', 'prompt', 'inquirer', 'ws', 'event-stream', 'inherits', 'mysql', 'esprima',
'jsdom', 'stylus', 'when', 'readable-stream', 'aws-sdk', 'concat-stream', 'chai', 'Thenable', 'wrench'];
public getDocumentSelector(): DocumentSelector {
return [{ language: 'json', pattern: '**/package.json' }];
}
public constructor(private xhr: XHRRequest) {
}
public collectDefaultSuggestions(fileName: string, result: ISuggestionsCollector): Thenable<any> {
let defaultValue = {
'name': '{{name}}',
'description': '{{description}}',
'author': '{{author}}',
'version': '{{1.0.0}}',
'main': '{{pathToMain}}',
'dependencies': {}
};
let proposal = new CompletionItem(localize('json.package.default', 'Default package.json'));
proposal.kind = CompletionItemKind.Module;
proposal.insertText = JSON.stringify(defaultValue, null, '\t');
result.add(proposal);
return Promise.resolve(null);
}
public collectPropertySuggestions(resource: string, location: Location, currentWord: string, addValue: boolean, isLast:boolean, collector: ISuggestionsCollector) : Thenable<any> {
if ((location.matches(['dependencies']) || location.matches(['devDependencies']) || location.matches(['optionalDependencies']) || location.matches(['peerDependencies']))) {
let queryUrl : string;
if (currentWord.length > 0) {
queryUrl = 'https://skimdb.npmjs.com/registry/_design/app/_view/browseAll?group_level=1&limit=' + LIMIT + '&start_key=%5B%22' + encodeURIComponent(currentWord) + '%22%5D&end_key=%5B%22'+ encodeURIComponent(currentWord + 'z') + '%22,%7B%7D%5D';
return this.xhr({
url : queryUrl
}).then((success) => {
if (success.status === 200) {
try {
let obj = JSON.parse(success.responseText);
if (obj && Array.isArray(obj.rows)) {
let results = <{ key: string[]; }[]> obj.rows;
for (let i = 0; i < results.length; i++) {
let keys = results[i].key;
if (Array.isArray(keys) && keys.length > 0) {
let name = keys[0];
let insertText = JSON.stringify(name);
if (addValue) {
insertText += ': "{{*}}"';
if (!isLast) {
insertText += ',';
}
}
let proposal = new CompletionItem(name);
proposal.kind = CompletionItemKind.Property;
proposal.insertText = insertText;
proposal.documentation = '';
collector.add(proposal);
}
}
if (results.length === LIMIT) {
collector.setAsIncomplete();
}
}
} catch (e) {
// ignore
}
} else {
collector.error(localize('json.npm.error.repoaccess', 'Request to the NPM repository failed: {0}', success.responseText));
return 0;
}
}, (error) => {
collector.error(localize('json.npm.error.repoaccess', 'Request to the NPM repository failed: {0}', error.responseText));
return 0;
});
} else {
this.mostDependedOn.forEach((name) => {
let insertText = JSON.stringify(name);
if (addValue) {
insertText += ': "{{*}}"';
if (!isLast) {
insertText += ',';
}
}
let proposal = new CompletionItem(name);
proposal.kind = CompletionItemKind.Property;
proposal.insertText = insertText;
proposal.documentation = '';
collector.add(proposal);
});
collector.setAsIncomplete();
return Promise.resolve(null);
}
}
return null;
}
public collectValueSuggestions(fileName: string, location: Location, result: ISuggestionsCollector): Thenable<any> {
if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']) || location.matches(['optionalDependencies', '*']) || location.matches(['peerDependencies', '*']))) {
let currentKey = location.segments[location.segments.length - 1];
let queryUrl = 'http://registry.npmjs.org/' + encodeURIComponent(currentKey) + '/latest';
return this.xhr({
url : queryUrl
}).then((success) => {
try {
let obj = JSON.parse(success.responseText);
if (obj && obj.version) {
let version = obj.version;
let name = JSON.stringify(version);
let proposal = new CompletionItem(name);
proposal.kind = CompletionItemKind.Property;
proposal.insertText = name;
proposal.documentation = localize('json.npm.latestversion', 'The currently latest version of the package');
result.add(proposal);
name = JSON.stringify('^' + version);
proposal = new CompletionItem(name);
proposal.kind = CompletionItemKind.Property;
proposal.insertText = name;
proposal.documentation = localize('json.npm.majorversion', 'Matches the most recent major version (1.x.x)');
result.add(proposal);
name = JSON.stringify('~' + version);
proposal = new CompletionItem(name);
proposal.kind = CompletionItemKind.Property;
proposal.insertText = name;
proposal.documentation = localize('json.npm.minorversion', 'Matches the most recent minor version (1.2.x)');
result.add(proposal);
}
} catch (e) {
// ignore
}
return 0;
}, (error) => {
return 0;
});
}
return null;
}
public resolveSuggestion(item: CompletionItem) : Thenable<CompletionItem> {
if (item.kind === CompletionItemKind.Property && item.documentation === '') {
return this.getInfo(item.label).then(infos => {
if (infos.length > 0) {
item.documentation = infos[0];
if (infos.length > 1) {
item.detail = infos[1];
}
return item;
}
return null;
});
};
return null;
}
private getInfo(pack: string): Thenable<string[]> {
let queryUrl = 'http://registry.npmjs.org/' + encodeURIComponent(pack) + '/latest';
return this.xhr({
url : queryUrl
}).then((success) => {
try {
let obj = JSON.parse(success.responseText);
if (obj) {
let result = [];
if (obj.description) {
result.push(obj.description);
}
if (obj.version) {
result.push(localize('json.npm.version.hover', 'Latest version: {0}', obj.version));
}
return result;
}
} catch (e) {
// ignore
}
return [];
}, (error) => {
return [];
});
}
public getInfoContribution(fileName: string, location: Location): Thenable<MarkedString[]> {
if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']) || location.matches(['optionalDependencies', '*']) || location.matches(['peerDependencies', '*']))) {
let pack = location.segments[location.segments.length - 1];
let htmlContent : MarkedString[] = [];
htmlContent.push(localize('json.npm.package.hover', '{0}', pack));
return this.getInfo(pack).then(infos => {
infos.forEach(info => {
htmlContent.push(info);
});
return htmlContent;
});
}
return null;
}
}

View File

@@ -0,0 +1,27 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
import {addJSONProviders} from './features/jsonContributions';
import * as httpRequest from 'request-light';
import {ExtensionContext, env, workspace} from 'vscode';
import * as nls from 'vscode-nls';
export function activate(context: ExtensionContext): any {
nls.config({locale: env.language});
configureHttpRequest();
workspace.onDidChangeConfiguration(e => configureHttpRequest());
addJSONProviders(httpRequest.xhr, context.subscriptions);
}
function configureHttpRequest() {
let httpSettings = workspace.getConfiguration('http');
httpRequest.configure(httpSettings.get<string>('proxy'), httpSettings.get<boolean>('proxyStrictSSL'));
}

View File

@@ -0,0 +1,10 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/// <reference path='../../../../src/vs/vscode.d.ts'/>
/// <reference path='../../../../src/typings/mocha.d.ts'/>
/// <reference path='../../../../extensions/node.d.ts'/>
/// <reference path='../../../../extensions/lib.core.d.ts'/>
/// <reference path='../../../../extensions/declares.d.ts'/>

View File

@@ -0,0 +1,11 @@
{
"compilerOptions": {
"noLib": true,
"target": "es5",
"module": "commonjs",
"outDir": "./out"
},
"exclude": [
"node_modules"
]
}