Archived
1
0

Update to VS Code 1.52.1

This commit is contained in:
Asher
2021-02-09 16:08:37 +00:00
1351 changed files with 56560 additions and 38990 deletions

View File

@ -15,7 +15,7 @@ import {
const localize = nls.loadMessageBundle();
export function runSelectedScript() {
export function runSelectedScript(context: vscode.ExtensionContext) {
let editor = vscode.window.activeTextEditor;
if (!editor) {
return;
@ -27,15 +27,15 @@ export function runSelectedScript() {
let script = findScriptAtPosition(contents, offset);
if (script) {
runScript(script, document);
runScript(context, script, document);
} else {
let message = localize('noScriptFound', 'Could not find a valid npm script at the selection.');
vscode.window.showErrorMessage(message);
}
}
export async function selectAndRunScriptFromFolder(selectedFolder: vscode.Uri) {
let taskList: FolderTaskItem[] = await detectNpmScriptsForFolder(selectedFolder);
export async function selectAndRunScriptFromFolder(context: vscode.ExtensionContext, selectedFolder: vscode.Uri) {
let taskList: FolderTaskItem[] = await detectNpmScriptsForFolder(context, selectedFolder);
if (taskList && taskList.length > 0) {
const quickPick = vscode.window.createQuickPick<FolderTaskItem>();

View File

@ -3,7 +3,7 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { MarkdownString, CompletionItemKind, CompletionItem, DocumentSelector, SnippetString, workspace } from 'vscode';
import { MarkdownString, CompletionItemKind, CompletionItem, DocumentSelector, SnippetString, workspace, Uri } from 'vscode';
import { IJSONContribution, ISuggestionsCollector } from './jsonContributions';
import { XHRRequest } from 'request-light';
import { Location } from 'jsonc-parser';
@ -37,7 +37,7 @@ export class BowerJSONContribution implements IJSONContribution {
return !!workspace.getConfiguration('npm').get('fetchOnlinePackageInfo');
}
public collectDefaultSuggestions(_resource: string, collector: ISuggestionsCollector): Thenable<any> {
public collectDefaultSuggestions(_resource: Uri, collector: ISuggestionsCollector): Thenable<any> {
const defaultValue = {
'name': '${1:name}',
'description': '${2:description}',
@ -53,7 +53,7 @@ export class BowerJSONContribution implements IJSONContribution {
return Promise.resolve(null);
}
public collectPropertySuggestions(_resource: string, location: Location, currentWord: string, addValue: boolean, isLast: boolean, collector: ISuggestionsCollector): Thenable<any> | null {
public collectPropertySuggestions(_resource: Uri, location: Location, currentWord: string, addValue: boolean, isLast: boolean, collector: ISuggestionsCollector): Thenable<any> | null {
if (!this.isEnabled()) {
return null;
}
@ -125,7 +125,7 @@ export class BowerJSONContribution implements IJSONContribution {
return null;
}
public collectValueSuggestions(_resource: string, location: Location, collector: ISuggestionsCollector): Promise<any> | null {
public collectValueSuggestions(_resource: Uri, location: Location, collector: ISuggestionsCollector): Promise<any> | null {
if (!this.isEnabled()) {
return null;
}
@ -141,7 +141,7 @@ export class BowerJSONContribution implements IJSONContribution {
return null;
}
public resolveSuggestion(item: CompletionItem): Thenable<CompletionItem | null> | null {
public resolveSuggestion(_resource: Uri | undefined, item: CompletionItem): Thenable<CompletionItem | null> | null {
if (item.kind === CompletionItemKind.Property && item.documentation === '') {
return this.getInfo(item.label).then(documentation => {
if (documentation) {
@ -182,7 +182,7 @@ export class BowerJSONContribution implements IJSONContribution {
});
}
public getInfoContribution(_resource: string, location: Location): Thenable<MarkdownString[] | null> | null {
public getInfoContribution(_resource: Uri, location: Location): Thenable<MarkdownString[] | null> | null {
if (!this.isEnabled()) {
return null;
}

View File

@ -4,14 +4,13 @@
*--------------------------------------------------------------------------------------------*/
import { Location, getLocation, createScanner, SyntaxKind, ScanError, JSONScanner } 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, MarkedString, DocumentSelector, languages, Disposable
CancellationToken, Range, MarkedString, DocumentSelector, languages, Disposable, Uri
} from 'vscode';
export interface ISuggestionsCollector {
@ -23,11 +22,11 @@ export interface ISuggestionsCollector {
export interface IJSONContribution {
getDocumentSelector(): DocumentSelector;
getInfoContribution(fileName: string, location: Location): Thenable<MarkedString[] | null> | null;
collectPropertySuggestions(fileName: string, location: Location, currentWord: string, addValue: boolean, isLast: boolean, result: ISuggestionsCollector): Thenable<any> | null;
collectValueSuggestions(fileName: string, location: Location, result: ISuggestionsCollector): Thenable<any> | null;
collectDefaultSuggestions(fileName: string, result: ISuggestionsCollector): Thenable<any>;
resolveSuggestion?(item: CompletionItem): Thenable<CompletionItem | null> | null;
getInfoContribution(resourceUri: Uri, location: Location): Thenable<MarkedString[] | null> | null;
collectPropertySuggestions(resourceUri: Uri, location: Location, currentWord: string, addValue: boolean, isLast: boolean, result: ISuggestionsCollector): Thenable<any> | null;
collectValueSuggestions(resourceUri: Uri, location: Location, result: ISuggestionsCollector): Thenable<any> | null;
collectDefaultSuggestions(resourceUri: Uri, result: ISuggestionsCollector): Thenable<any>;
resolveSuggestion?(resourceUri: Uri | undefined, item: CompletionItem): Thenable<CompletionItem | null> | null;
}
export function addJSONProviders(xhr: XHRRequest, canRunNPM: boolean): Disposable {
@ -47,7 +46,6 @@ export class JSONHoverProvider implements HoverProvider {
}
public provideHover(document: TextDocument, position: Position, _token: CancellationToken): Thenable<Hover> | null {
const fileName = basename(document.fileName);
const offset = document.offsetAt(position);
const location = getLocation(document.getText(), offset);
if (!location.previousNode) {
@ -55,7 +53,7 @@ export class JSONHoverProvider implements HoverProvider {
}
const node = location.previousNode;
if (node && node.offset <= offset && offset <= node.offset + node.length) {
const promise = this.jsonContribution.getInfoContribution(fileName, location);
const promise = this.jsonContribution.getInfoContribution(document.uri, location);
if (promise) {
return promise.then(htmlContent => {
const range = new Range(document.positionAt(node.offset), document.positionAt(node.offset + node.length));
@ -73,12 +71,14 @@ export class JSONHoverProvider implements HoverProvider {
export class JSONCompletionItemProvider implements CompletionItemProvider {
private lastResource: Uri | undefined;
constructor(private jsonContribution: IJSONContribution) {
}
public resolveCompletionItem(item: CompletionItem, _token: CancellationToken): Thenable<CompletionItem | null> {
if (this.jsonContribution.resolveSuggestion) {
const resolver = this.jsonContribution.resolveSuggestion(item);
const resolver = this.jsonContribution.resolveSuggestion(this.lastResource, item);
if (resolver) {
return resolver;
}
@ -87,8 +87,8 @@ export class JSONCompletionItemProvider implements CompletionItemProvider {
}
public provideCompletionItems(document: TextDocument, position: Position, _token: CancellationToken): Thenable<CompletionList | null> | null {
this.lastResource = document.uri;
const fileName = basename(document.fileName);
const currentWord = this.getCurrentWord(document, position);
let overwriteRange: Range;
@ -126,12 +126,12 @@ export class JSONCompletionItemProvider implements CompletionItemProvider {
const scanner = createScanner(document.getText(), true);
const addValue = !location.previousNode || !this.hasColonAfter(scanner, location.previousNode.offset + location.previousNode.length);
const isLast = this.isLast(scanner, document.offsetAt(position));
collectPromise = this.jsonContribution.collectPropertySuggestions(fileName, location, currentWord, addValue, isLast, collector);
collectPromise = this.jsonContribution.collectPropertySuggestions(document.uri, location, currentWord, addValue, isLast, collector);
} else {
if (location.path.length === 0) {
collectPromise = this.jsonContribution.collectDefaultSuggestions(fileName, collector);
collectPromise = this.jsonContribution.collectDefaultSuggestions(document.uri, collector);
} else {
collectPromise = this.jsonContribution.collectValueSuggestions(fileName, location, collector);
collectPromise = this.jsonContribution.collectValueSuggestions(document.uri, location, collector);
}
}
if (collectPromise) {

View File

@ -3,13 +3,14 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { MarkedString, CompletionItemKind, CompletionItem, DocumentSelector, SnippetString, workspace, MarkdownString } from 'vscode';
import { MarkedString, CompletionItemKind, CompletionItem, DocumentSelector, SnippetString, workspace, MarkdownString, Uri } from 'vscode';
import { IJSONContribution, ISuggestionsCollector } from './jsonContributions';
import { XHRRequest } from 'request-light';
import { Location } from 'jsonc-parser';
import * as cp from 'child_process';
import * as nls from 'vscode-nls';
import { dirname } from 'path';
const localize = nls.loadMessageBundle();
const LIMIT = 40;
@ -35,7 +36,7 @@ export class PackageJSONContribution implements IJSONContribution {
public constructor(private xhr: XHRRequest, private canRunNPM: boolean) {
}
public collectDefaultSuggestions(_fileName: string, result: ISuggestionsCollector): Thenable<any> {
public collectDefaultSuggestions(_resource: Uri, result: ISuggestionsCollector): Thenable<any> {
const defaultValue = {
'name': '${1:name}',
'description': '${2:description}',
@ -60,7 +61,7 @@ export class PackageJSONContribution implements IJSONContribution {
}
public collectPropertySuggestions(
_resource: string,
_resource: Uri,
location: Location,
currentWord: string,
addValue: boolean,
@ -183,7 +184,7 @@ export class PackageJSONContribution implements IJSONContribution {
return Promise.resolve(null);
}
public async collectValueSuggestions(_fileName: string, location: Location, result: ISuggestionsCollector): Promise<any> {
public async collectValueSuggestions(resource: Uri, location: Location, result: ISuggestionsCollector): Promise<any> {
if (!this.isEnabled()) {
return null;
}
@ -191,7 +192,7 @@ export class PackageJSONContribution implements IJSONContribution {
if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']) || location.matches(['optionalDependencies', '*']) || location.matches(['peerDependencies', '*']))) {
const currentKey = location.path[location.path.length - 1];
if (typeof currentKey === 'string') {
const info = await this.fetchPackageInfo(currentKey);
const info = await this.fetchPackageInfo(currentKey, resource);
if (info && info.version) {
let name = JSON.stringify(info.version);
@ -236,9 +237,9 @@ export class PackageJSONContribution implements IJSONContribution {
return str;
}
public resolveSuggestion(item: CompletionItem): Thenable<CompletionItem | null> | null {
public resolveSuggestion(resource: Uri | undefined, item: CompletionItem): Thenable<CompletionItem | null> | null {
if (item.kind === CompletionItemKind.Property && !item.documentation) {
return this.fetchPackageInfo(item.label).then(info => {
return this.fetchPackageInfo(item.label, resource).then(info => {
if (info) {
item.documentation = this.getDocumentation(info.description, info.version, info.homepage);
return item;
@ -266,13 +267,13 @@ export class PackageJSONContribution implements IJSONContribution {
return false;
}
private async fetchPackageInfo(pack: string): Promise<ViewPackageInfo | undefined> {
private async fetchPackageInfo(pack: string, resource: Uri | undefined): Promise<ViewPackageInfo | undefined> {
if (!this.isValidNPMName(pack)) {
return undefined; // avoid unnecessary lookups
}
let info: ViewPackageInfo | undefined;
if (this.canRunNPM) {
info = await this.npmView(pack);
info = await this.npmView(pack, resource);
}
if (!info && this.onlineEnabled()) {
info = await this.npmjsView(pack);
@ -280,10 +281,11 @@ export class PackageJSONContribution implements IJSONContribution {
return info;
}
private npmView(pack: string): Promise<ViewPackageInfo | undefined> {
private npmView(pack: string, resource: Uri | undefined): Promise<ViewPackageInfo | undefined> {
return new Promise((resolve, _reject) => {
const args = ['view', '--json', pack, 'description', 'dist-tags.latest', 'homepage', 'version'];
cp.execFile(process.platform === 'win32' ? 'npm.cmd' : 'npm', args, (error, stdout) => {
let cwd = resource && resource.scheme === 'file' ? dirname(resource.fsPath) : undefined;
cp.execFile(process.platform === 'win32' ? 'npm.cmd' : 'npm', args, { cwd }, (error, stdout) => {
if (!error) {
try {
const content = JSON.parse(stdout);
@ -325,14 +327,14 @@ export class PackageJSONContribution implements IJSONContribution {
return undefined;
}
public getInfoContribution(_fileName: string, location: Location): Thenable<MarkedString[] | null> | null {
public getInfoContribution(resource: Uri, location: Location): Thenable<MarkedString[] | null> | null {
if (!this.isEnabled()) {
return null;
}
if ((location.matches(['dependencies', '*']) || location.matches(['devDependencies', '*']) || location.matches(['optionalDependencies', '*']) || location.matches(['peerDependencies', '*']))) {
const pack = location.path[location.path.length - 1];
if (typeof pack === 'string') {
return this.fetchPackageInfo(pack).then(info => {
return this.fetchPackageInfo(pack, resource).then(info => {
if (info) {
return [this.getDocumentation(info.description, info.version, info.homepage)];
}

View File

@ -31,6 +31,7 @@ export async function activate(context: vscode.ExtensionContext): Promise<void>
const canRunNPM = canRunNpmInCurrentWorkspace();
context.subscriptions.push(addJSONProviders(httpRequest.xhr, canRunNPM));
registerTaskProvider(context);
treeDataProvider = registerExplorer(context);
@ -48,7 +49,6 @@ export async function activate(context: vscode.ExtensionContext): Promise<void>
}
}));
registerTaskProvider(context);
registerHoverProvider(context);
context.subscriptions.push(vscode.commands.registerCommand('npm.runSelectedScript', runSelectedScript));
@ -58,7 +58,7 @@ export async function activate(context: vscode.ExtensionContext): Promise<void>
}));
context.subscriptions.push(vscode.commands.registerCommand('npm.packageManager', (args) => {
if (args instanceof vscode.Uri) {
return getPackageManager(args);
return getPackageManager(context, args);
}
return '';
}));
@ -71,6 +71,7 @@ function canRunNpmInCurrentWorkspace() {
return false;
}
let taskProvider: NpmTaskProvider;
function registerTaskProvider(context: vscode.ExtensionContext): vscode.Disposable | undefined {
if (vscode.workspace.workspaceFolders) {
let watcher = vscode.workspace.createFileSystemWatcher('**/package.json');
@ -82,8 +83,8 @@ function registerTaskProvider(context: vscode.ExtensionContext): vscode.Disposab
let workspaceWatcher = vscode.workspace.onDidChangeWorkspaceFolders((_e) => invalidateScriptCaches());
context.subscriptions.push(workspaceWatcher);
let provider: vscode.TaskProvider = new NpmTaskProvider();
let disposable = vscode.tasks.registerTaskProvider('npm', provider);
taskProvider = new NpmTaskProvider(context);
let disposable = vscode.tasks.registerTaskProvider('npm', taskProvider);
context.subscriptions.push(disposable);
return disposable;
}
@ -92,7 +93,7 @@ function registerTaskProvider(context: vscode.ExtensionContext): vscode.Disposab
function registerExplorer(context: vscode.ExtensionContext): NpmScriptsTreeDataProvider | undefined {
if (vscode.workspace.workspaceFolders) {
let treeDataProvider = new NpmScriptsTreeDataProvider(context);
let treeDataProvider = new NpmScriptsTreeDataProvider(context, taskProvider!);
const view = vscode.window.createTreeView('npm', { treeDataProvider: treeDataProvider, showCollapseAll: true });
context.subscriptions.push(view);
return treeDataProvider;

View File

@ -7,14 +7,18 @@ import { JSONVisitor, visit } from 'jsonc-parser';
import * as path from 'path';
import {
commands, Event, EventEmitter, ExtensionContext,
Range,
Selection, Task,
TaskGroup, tasks, TextDocument, ThemeIcon, TreeDataProvider, TreeItem, TreeItemCollapsibleState, Uri,
TaskGroup, tasks, TextDocument, TextDocumentShowOptions, ThemeIcon, TreeDataProvider, TreeItem, TreeItemCollapsibleState, Uri,
window, workspace, WorkspaceFolder
} from 'vscode';
import * as nls from 'vscode-nls';
import {
createTask, getTaskName, isAutoDetectionEnabled, isWorkspaceFolder, NpmTaskDefinition,
startDebugging
NpmTaskProvider,
startDebugging,
TaskLocation,
TaskWithLocation
} from './tasks';
const localize = nls.loadMessageBundle();
@ -43,7 +47,7 @@ class PackageJSON extends TreeItem {
folder: Folder;
scripts: NpmScript[] = [];
static getLabel(_folderName: string, relativePath: string): string {
static getLabel(relativePath: string): string {
if (relativePath.length > 0) {
return path.join(relativePath, packageName);
}
@ -51,7 +55,7 @@ class PackageJSON extends TreeItem {
}
constructor(folder: Folder, relativePath: string) {
super(PackageJSON.getLabel(folder.label!, relativePath), TreeItemCollapsibleState.Expanded);
super(PackageJSON.getLabel(relativePath), TreeItemCollapsibleState.Expanded);
this.folder = folder;
this.path = relativePath;
this.contextValue = 'packageJSON';
@ -74,15 +78,20 @@ class NpmScript extends TreeItem {
task: Task;
package: PackageJSON;
constructor(_context: ExtensionContext, packageJson: PackageJSON, task: Task) {
constructor(_context: ExtensionContext, packageJson: PackageJSON, task: Task, public taskLocation?: TaskLocation) {
super(task.name, TreeItemCollapsibleState.None);
const command: ExplorerCommands = workspace.getConfiguration('npm').get<ExplorerCommands>('scriptExplorerAction') || 'open';
const commandList = {
'open': {
title: 'Edit Script',
command: 'npm.openScript',
arguments: [this]
command: 'vscode.open',
arguments: [
taskLocation?.document,
taskLocation ? <TextDocumentShowOptions>{
selection: new Range(taskLocation.line, taskLocation.line)
} : undefined
]
},
'run': {
title: 'Run Script',
@ -123,7 +132,7 @@ export class NpmScriptsTreeDataProvider implements TreeDataProvider<TreeItem> {
private _onDidChangeTreeData: EventEmitter<TreeItem | null> = new EventEmitter<TreeItem | null>();
readonly onDidChangeTreeData: Event<TreeItem | null> = this._onDidChangeTreeData.event;
constructor(context: ExtensionContext) {
constructor(context: ExtensionContext, public taskProvider: NpmTaskProvider) {
const subscriptions = context.subscriptions;
this.extensionContext = context;
subscriptions.push(commands.registerCommand('npm.runScript', this.runScript, this));
@ -137,7 +146,7 @@ export class NpmScriptsTreeDataProvider implements TreeDataProvider<TreeItem> {
}
private async debugScript(script: NpmScript) {
startDebugging(script.task.definition.script, path.dirname(script.package.resourceUri!.fsPath), script.getFolder());
startDebugging(this.extensionContext, script.task.definition.script, path.dirname(script.package.resourceUri!.fsPath), script.getFolder());
}
private findScript(document: TextDocument, script?: NpmScript): number {
@ -181,7 +190,7 @@ export class NpmScriptsTreeDataProvider implements TreeDataProvider<TreeItem> {
if (!uri) {
return;
}
let task = createTask('install', 'install', selection.folder.workspaceFolder, uri, undefined, []);
let task = await createTask(this.extensionContext, 'install', 'install', selection.folder.workspaceFolder, uri, undefined, []);
tasks.executeTask(task);
}
@ -228,7 +237,7 @@ export class NpmScriptsTreeDataProvider implements TreeDataProvider<TreeItem> {
async getChildren(element?: TreeItem): Promise<TreeItem[]> {
if (!this.taskTree) {
let taskItems = await tasks.fetchTasks({ type: 'npm' });
const taskItems = await this.taskProvider.tasksWithLocation;
if (taskItems) {
this.taskTree = this.buildTaskTree(taskItems);
if (this.taskTree.length === 0) {
@ -265,7 +274,7 @@ export class NpmScriptsTreeDataProvider implements TreeDataProvider<TreeItem> {
return fullName === task.name;
}
private buildTaskTree(tasks: Task[]): Folder[] | PackageJSON[] | NoScripts[] {
private buildTaskTree(tasks: TaskWithLocation[]): Folder[] | PackageJSON[] | NoScripts[] {
let folders: Map<String, Folder> = new Map();
let packages: Map<String, PackageJSON> = new Map();
@ -273,22 +282,22 @@ export class NpmScriptsTreeDataProvider implements TreeDataProvider<TreeItem> {
let packageJson = null;
tasks.forEach(each => {
if (isWorkspaceFolder(each.scope) && !this.isInstallTask(each)) {
folder = folders.get(each.scope.name);
if (isWorkspaceFolder(each.task.scope) && !this.isInstallTask(each.task)) {
folder = folders.get(each.task.scope.name);
if (!folder) {
folder = new Folder(each.scope);
folders.set(each.scope.name, folder);
folder = new Folder(each.task.scope);
folders.set(each.task.scope.name, folder);
}
let definition: NpmTaskDefinition = <NpmTaskDefinition>each.definition;
let definition: NpmTaskDefinition = <NpmTaskDefinition>each.task.definition;
let relativePath = definition.path ? definition.path : '';
let fullPath = path.join(each.scope.name, relativePath);
let fullPath = path.join(each.task.scope.name, relativePath);
packageJson = packages.get(fullPath);
if (!packageJson) {
packageJson = new PackageJSON(folder, relativePath);
folder.addPackage(packageJson);
packages.set(fullPath, packageJson);
}
let script = new NpmScript(this.extensionContext, packageJson, each);
let script = new NpmScript(this.extensionContext, packageJson, each.task, each.location);
packageJson.addScript(script);
}
});

View File

@ -0,0 +1,80 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import findWorkspaceRoot = require('../node_modules/find-yarn-workspace-root');
import findUp = require('find-up');
import * as path from 'path';
import whichPM = require('which-pm');
import { Uri, workspace } from 'vscode';
async function pathExists(filePath: string) {
try {
await workspace.fs.stat(Uri.file(filePath));
} catch {
return false;
}
return true;
}
async function isPNPMPreferred(pkgPath: string) {
if (await pathExists(path.join(pkgPath, 'pnpm-lock.yaml'))) {
return true;
}
if (await pathExists(path.join(pkgPath, 'shrinkwrap.yaml'))) {
return true;
}
if (await findUp('pnpm-lock.yaml', { cwd: pkgPath })) {
return true;
}
return false;
}
async function isYarnPreferred(pkgPath: string) {
if (await pathExists(path.join(pkgPath, 'yarn.lock'))) {
return true;
}
try {
if (typeof findWorkspaceRoot(pkgPath) === 'string') {
return true;
}
} catch (err) { }
return false;
}
const isNPMPreferred = (pkgPath: string) => {
return pathExists(path.join(pkgPath, 'package-lock.json'));
};
export async function findPreferredPM(pkgPath: string): Promise<{ name: string, multiplePMDetected: boolean }> {
const detectedPackageManagers: string[] = [];
if (await isNPMPreferred(pkgPath)) {
detectedPackageManagers.push('npm');
}
if (await isYarnPreferred(pkgPath)) {
detectedPackageManagers.push('yarn');
}
if (await isPNPMPreferred(pkgPath)) {
detectedPackageManagers.push('pnpm');
}
const pmUsedForInstallation: { name: string } | null = await whichPM(pkgPath);
if (pmUsedForInstallation && !detectedPackageManagers.includes(pmUsedForInstallation.name)) {
detectedPackageManagers.push(pmUsedForInstallation.name);
}
const multiplePMDetected = detectedPackageManagers.length > 1;
return {
name: detectedPackageManagers[0] || 'npm',
multiplePMDetected
};
}

View File

@ -30,7 +30,7 @@ export function invalidateHoverScriptsCache(document?: TextDocument) {
export class NpmScriptHoverProvider implements HoverProvider {
constructor(context: ExtensionContext) {
constructor(private context: ExtensionContext) {
context.subscriptions.push(commands.registerCommand('npm.runScriptFromHover', this.runScriptFromHover, this));
context.subscriptions.push(commands.registerCommand('npm.debugScriptFromHover', this.debugScriptFromHover, this));
context.subscriptions.push(workspace.onDidChangeTextDocument((e) => {
@ -98,13 +98,13 @@ export class NpmScriptHoverProvider implements HoverProvider {
return `${prefix}[${label}](command:${cmd}?${encodedArgs} "${tooltip}")`;
}
public runScriptFromHover(args: any) {
public async runScriptFromHover(args: any) {
let script = args.script;
let documentUri = args.documentUri;
let folder = workspace.getWorkspaceFolder(documentUri);
if (folder) {
let task = createTask(script, `run ${script}`, folder, documentUri);
tasks.executeTask(task);
let task = await createTask(this.context, script, `run ${script}`, folder, documentUri);
await tasks.executeTask(task);
}
}
@ -113,7 +113,7 @@ export class NpmScriptHoverProvider implements HoverProvider {
let documentUri = args.documentUri;
let folder = workspace.getWorkspaceFolder(documentUri);
if (folder) {
startDebugging(script, dirname(documentUri.fsPath), folder);
startDebugging(this.context, script, dirname(documentUri.fsPath), folder);
}
}
}

View File

@ -5,13 +5,14 @@
import {
TaskDefinition, Task, TaskGroup, WorkspaceFolder, RelativePattern, ShellExecution, Uri, workspace,
DebugConfiguration, debug, TaskProvider, TextDocument, tasks, TaskScope, QuickPickItem
DebugConfiguration, debug, TaskProvider, TextDocument, tasks, TaskScope, QuickPickItem, window, Position, ExtensionContext, env
} from 'vscode';
import * as path from 'path';
import * as fs from 'fs';
import * as minimatch from 'minimatch';
import * as nls from 'vscode-nls';
import { JSONVisitor, visit, ParseErrorCode } from 'jsonc-parser';
import { findPreferredPM } from './preferred-pm';
const localize = nls.loadMessageBundle();
@ -27,20 +28,35 @@ export interface FolderTaskItem extends QuickPickItem {
type AutoDetect = 'on' | 'off';
let cachedTasks: Task[] | undefined = undefined;
let cachedTasks: TaskWithLocation[] | undefined = undefined;
const INSTALL_SCRIPT = 'install';
export interface TaskLocation {
document: Uri,
line: Position
}
export interface TaskWithLocation {
task: Task,
location?: TaskLocation
}
export class NpmTaskProvider implements TaskProvider {
constructor() {
constructor(private context: ExtensionContext) {
}
public provideTasks() {
return provideNpmScripts();
get tasksWithLocation(): Promise<TaskWithLocation[]> {
return provideNpmScripts(this.context);
}
public resolveTask(_task: Task): Task | undefined {
public async provideTasks() {
const tasks = await provideNpmScripts(this.context);
return tasks.map(task => task.task);
}
public resolveTask(_task: Task): Promise<Task> | undefined {
const npmTask = (<any>_task.definition).script;
if (npmTask) {
const kind: NpmTaskDefinition = (<any>_task.definition);
@ -54,7 +70,7 @@ export class NpmTaskProvider implements TaskProvider {
} else {
packageJsonUri = _task.scope.uri.with({ path: _task.scope.uri.path + '/package.json' });
}
return createTask(kind, `${kind.script === INSTALL_SCRIPT ? '' : 'run '}${kind.script}`, _task.scope, packageJsonUri);
return createTask(this.context, kind, `${kind.script === INSTALL_SCRIPT ? '' : 'run '}${kind.script}`, _task.scope, packageJsonUri);
}
return undefined;
}
@ -107,8 +123,27 @@ export function isWorkspaceFolder(value: any): value is WorkspaceFolder {
return value && typeof value !== 'number';
}
export function getPackageManager(folder: Uri): string {
return workspace.getConfiguration('npm', folder).get<string>('packageManager', 'npm');
export async function getPackageManager(extensionContext: ExtensionContext, folder: Uri): Promise<string> {
let packageManagerName = workspace.getConfiguration('npm', folder).get<string>('packageManager', 'npm');
if (packageManagerName === 'auto') {
const { name, multiplePMDetected } = await findPreferredPM(folder.fsPath);
packageManagerName = name;
const neverShowWarning = 'npm.multiplePMWarning.neverShow';
if (multiplePMDetected && !extensionContext.globalState.get<boolean>(neverShowWarning)) {
const multiplePMWarning = localize('npm.multiplePMWarning', 'Using {0} as the preferred package manager. Found multiple lockfiles for {1}.', packageManagerName, folder.fsPath);
const neverShowAgain = localize('npm.multiplePMWarning.doNotShow', "Do not show again");
const learnMore = localize('npm.multiplePMWarning.learnMore', "Learn more");
window.showInformationMessage(multiplePMWarning, learnMore, neverShowAgain).then(result => {
switch (result) {
case neverShowAgain: extensionContext.globalState.update(neverShowWarning, true); break;
case learnMore: env.openExternal(Uri.parse('https://nodejs.dev/learn/the-package-lock-json-file'));
}
});
}
}
return packageManagerName;
}
export async function hasNpmScripts(): Promise<boolean> {
@ -132,10 +167,10 @@ export async function hasNpmScripts(): Promise<boolean> {
}
}
async function detectNpmScripts(): Promise<Task[]> {
async function detectNpmScripts(context: ExtensionContext): Promise<TaskWithLocation[]> {
let emptyTasks: Task[] = [];
let allTasks: Task[] = [];
let emptyTasks: TaskWithLocation[] = [];
let allTasks: TaskWithLocation[] = [];
let visitedPackageJsonFiles: Set<string> = new Set();
let folders = workspace.workspaceFolders;
@ -149,7 +184,7 @@ async function detectNpmScripts(): Promise<Task[]> {
let paths = await workspace.findFiles(relativePattern, '**/{node_modules,.vscode-test}/**');
for (const path of paths) {
if (!isExcluded(folder, path) && !visitedPackageJsonFiles.has(path.fsPath)) {
let tasks = await provideNpmScriptsForFolder(path);
let tasks = await provideNpmScriptsForFolder(context, path);
visitedPackageJsonFiles.add(path.fsPath);
allTasks.push(...tasks);
}
@ -163,7 +198,7 @@ async function detectNpmScripts(): Promise<Task[]> {
}
export async function detectNpmScriptsForFolder(folder: Uri): Promise<FolderTaskItem[]> {
export async function detectNpmScriptsForFolder(context: ExtensionContext, folder: Uri): Promise<FolderTaskItem[]> {
let folderTasks: FolderTaskItem[] = [];
@ -174,9 +209,9 @@ export async function detectNpmScriptsForFolder(folder: Uri): Promise<FolderTask
let visitedPackageJsonFiles: Set<string> = new Set();
for (const path of paths) {
if (!visitedPackageJsonFiles.has(path.fsPath)) {
let tasks = await provideNpmScriptsForFolder(path);
let tasks = await provideNpmScriptsForFolder(context, path);
visitedPackageJsonFiles.add(path.fsPath);
folderTasks.push(...tasks.map(t => ({ label: t.name, task: t })));
folderTasks.push(...tasks.map(t => ({ label: t.task.name, task: t.task })));
}
}
return folderTasks;
@ -185,9 +220,9 @@ export async function detectNpmScriptsForFolder(folder: Uri): Promise<FolderTask
}
}
export async function provideNpmScripts(): Promise<Task[]> {
export async function provideNpmScripts(context: ExtensionContext): Promise<TaskWithLocation[]> {
if (!cachedTasks) {
cachedTasks = await detectNpmScripts();
cachedTasks = await detectNpmScripts(context);
}
return cachedTasks;
}
@ -223,8 +258,8 @@ function isDebugScript(script: string): boolean {
return match !== null;
}
async function provideNpmScriptsForFolder(packageJsonUri: Uri): Promise<Task[]> {
let emptyTasks: Task[] = [];
async function provideNpmScriptsForFolder(context: ExtensionContext, packageJsonUri: Uri): Promise<TaskWithLocation[]> {
let emptyTasks: TaskWithLocation[] = [];
let folder = workspace.getWorkspaceFolder(packageJsonUri);
if (!folder) {
@ -235,11 +270,13 @@ async function provideNpmScriptsForFolder(packageJsonUri: Uri): Promise<Task[]>
return emptyTasks;
}
const result: Task[] = [];
const result: TaskWithLocation[] = [];
const prePostScripts = getPrePostScripts(scripts);
Object.keys(scripts).forEach(each => {
const task = createTask(each, `run ${each}`, folder!, packageJsonUri, scripts![each]);
for (const each of scripts.keys()) {
const scriptValue = scripts.get(each)!;
const task = await createTask(context, each, `run ${each}`, folder!, packageJsonUri, scriptValue.script);
const lowerCaseTaskName = each.toLowerCase();
if (isBuildTask(lowerCaseTaskName)) {
task.group = TaskGroup.Build;
@ -251,13 +288,14 @@ async function provideNpmScriptsForFolder(packageJsonUri: Uri): Promise<Task[]>
}
// todo@connor4312: all scripts are now debuggable, what is a 'debug script'?
if (isDebugScript(scripts![each])) {
if (isDebugScript(scriptValue.script)) {
task.group = TaskGroup.Rebuild; // hack: use Rebuild group to tag debug scripts
}
result.push(task);
});
result.push({ task, location: scriptValue.location });
}
// always add npm install (without a problem matcher)
result.push(createTask(INSTALL_SCRIPT, INSTALL_SCRIPT, folder, packageJsonUri, 'install dependencies from package', []));
result.push({ task: await createTask(context, INSTALL_SCRIPT, INSTALL_SCRIPT, folder, packageJsonUri, 'install dependencies from package', []) });
return result;
}
@ -268,7 +306,7 @@ export function getTaskName(script: string, relativePath: string | undefined) {
return script;
}
export function createTask(script: NpmTaskDefinition | string, cmd: string, folder: WorkspaceFolder, packageJsonUri: Uri, detail?: string, matcher?: any): Task {
export async function createTask(context: ExtensionContext, script: NpmTaskDefinition | string, cmd: string, folder: WorkspaceFolder, packageJsonUri: Uri, detail?: string, matcher?: any): Promise<Task> {
let kind: NpmTaskDefinition;
if (typeof script === 'string') {
kind = { type: 'npm', script: script };
@ -276,27 +314,27 @@ export function createTask(script: NpmTaskDefinition | string, cmd: string, fold
kind = script;
}
function getCommandLine(folder: WorkspaceFolder, cmd: string): string {
let packageManager = getPackageManager(folder.uri);
const packageManager = await getPackageManager(context, folder.uri);
async function getCommandLine(cmd: string): Promise<string> {
if (workspace.getConfiguration('npm', folder.uri).get<boolean>('runSilent')) {
return `${packageManager} --silent ${cmd}`;
}
return `${packageManager} ${cmd}`;
}
function getRelativePath(folder: WorkspaceFolder, packageJsonUri: Uri): string {
function getRelativePath(packageJsonUri: Uri): string {
let rootUri = folder.uri;
let absolutePath = packageJsonUri.path.substring(0, packageJsonUri.path.length - 'package.json'.length);
return absolutePath.substring(rootUri.path.length + 1);
}
let relativePackageJson = getRelativePath(folder, packageJsonUri);
let relativePackageJson = getRelativePath(packageJsonUri);
if (relativePackageJson.length) {
kind.path = getRelativePath(folder, packageJsonUri);
kind.path = relativePackageJson;
}
let taskName = getTaskName(kind.script, relativePackageJson);
let cwd = path.dirname(packageJsonUri.fsPath);
const task = new Task(kind, folder, taskName, 'npm', new ShellExecution(getCommandLine(folder, cmd), { cwd: cwd }), matcher);
const task = new Task(kind, folder, taskName, 'npm', new ShellExecution(await getCommandLine(cmd), { cwd: cwd }), matcher);
task.detail = detail;
return task;
}
@ -337,33 +375,22 @@ async function exists(file: string): Promise<boolean> {
});
}
async function readFile(file: string): Promise<string> {
return new Promise<string>((resolve, reject) => {
fs.readFile(file, (err, data) => {
if (err) {
reject(err);
}
resolve(data.toString());
});
});
}
export function runScript(script: string, document: TextDocument) {
export async function runScript(context: ExtensionContext, script: string, document: TextDocument) {
let uri = document.uri;
let folder = workspace.getWorkspaceFolder(uri);
if (folder) {
let task = createTask(script, `run ${script}`, folder, uri);
let task = await createTask(context, script, `run ${script}`, folder, uri);
tasks.executeTask(task);
}
}
export function startDebugging(scriptName: string, cwd: string, folder: WorkspaceFolder) {
export async function startDebugging(context: ExtensionContext, scriptName: string, cwd: string, folder: WorkspaceFolder) {
const config: DebugConfiguration = {
type: 'pwa-node',
request: 'launch',
name: `Debug ${scriptName}`,
cwd,
runtimeExecutable: getPackageManager(folder.uri),
runtimeExecutable: await getPackageManager(context, folder.uri),
runtimeArgs: [
'run',
scriptName,
@ -378,10 +405,11 @@ export function startDebugging(scriptName: string, cwd: string, folder: Workspac
export type StringMap = { [s: string]: string; };
async function findAllScripts(buffer: string): Promise<StringMap> {
let scripts: StringMap = {};
async function findAllScripts(document: TextDocument, buffer: string): Promise<Map<string, { script: string, location: TaskLocation }>> {
let scripts: Map<string, { script: string, location: TaskLocation }> = new Map();
let script: string | undefined = undefined;
let inScripts = false;
let scriptOffset = 0;
let visitor: JSONVisitor = {
onError(_error: ParseErrorCode, _offset: number, _length: number) {
@ -395,17 +423,18 @@ async function findAllScripts(buffer: string): Promise<StringMap> {
onLiteralValue(value: any, _offset: number, _length: number) {
if (script) {
if (typeof value === 'string') {
scripts[script] = value;
scripts.set(script, { script: value, location: { document: document.uri, line: document.positionAt(scriptOffset) } });
}
script = undefined;
}
},
onObjectProperty(property: string, _offset: number, _length: number) {
onObjectProperty(property: string, offset: number, _length: number) {
if (property === 'scripts') {
inScripts = true;
}
else if (inScripts && !script) {
script = property;
scriptOffset = offset;
} else { // nested object which is invalid, ignore the script
script = undefined;
}
@ -493,7 +522,7 @@ export function findScriptAtPosition(buffer: string, offset: number): string | u
return foundScript;
}
export async function getScripts(packageJsonUri: Uri): Promise<StringMap | undefined> {
export async function getScripts(packageJsonUri: Uri): Promise<Map<string, { script: string, location: TaskLocation }> | undefined> {
if (packageJsonUri.scheme !== 'file') {
return undefined;
@ -505,8 +534,9 @@ export async function getScripts(packageJsonUri: Uri): Promise<StringMap | undef
}
try {
let contents = await readFile(packageJson);
let json = findAllScripts(contents);//JSON.parse(contents);
const document: TextDocument = await workspace.openTextDocument(packageJsonUri);
let contents = document.getText();
let json = findAllScripts(document, contents);//JSON.parse(contents);
return json;
} catch (e) {
let localizedParseError = localize('npm.parseError', 'Npm task detection: failed to parse the file {0}', packageJsonUri.fsPath);