projectStatus.ts 6.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
/*---------------------------------------------------------------------------------------------
 *  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 * as vscode from 'vscode';
import {ITypescriptServiceClient} from '../typescriptService';
import {loadMessageBundle} from 'vscode-nls';
11
import {dirname, join} from 'path';
12
import {exists} from 'fs';
13 14 15 16 17 18 19 20 21 22

const localize = loadMessageBundle();
const selector = ['javascript', 'javascriptreact'];

interface Option extends vscode.MessageItem {
	execute(): void;
}

interface Hint {
	message: string;
23
	options: Option[];
24 25
}

26 27
const fileLimit = 500;

28
export function create(client: ITypescriptServiceClient, isOpen:(path:string)=>Promise<boolean>, memento: vscode.Memento) {
29 30

	const toDispose: vscode.Disposable[] = [];
31 32 33 34 35 36 37 38 39
	const projectHinted: { [k: string]: boolean } = Object.create(null);

	const projectHintIgnoreList = memento.get<string[]>('projectHintIgnoreList', []);
	for (let path of projectHintIgnoreList) {
		if (path === null) {
			path = undefined;
		}
		projectHinted[path] = true;
	}
40 41 42 43 44

	let currentHint: Hint;
	let item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, Number.MIN_VALUE);
	item.command = 'js.projectStatus.command';
	toDispose.push(vscode.commands.registerCommand('js.projectStatus.command', () => {
45 46 47
		let {message, options} = currentHint;
		return vscode.window.showInformationMessage(message, ...options).then(selection => {
			if (selection) {
48 49 50 51 52 53
				return selection.execute();
			}
		});
	}));

	toDispose.push(vscode.workspace.onDidChangeTextDocument(e => {
J
Johannes Rieken 已提交
54
		delete projectHinted[e.document.fileName];
55 56 57 58 59 60 61 62 63
	}));

	function onEditor(editor: vscode.TextEditor): void {
		if (!editor || !vscode.languages.match(selector, editor.document)) {
			item.hide();
			return;
		}

		const file = client.asAbsolutePath(editor.document.uri);
64 65 66
		if (!file) {
			return;
		}
67

68 69
		isOpen(file).then(value => {
			if (!value) {
70 71 72
				return;
			}

73 74 75 76 77 78 79 80
			return client.execute('projectInfo', { file, needFileNameList: true }).then(res => {

				let {configFileName, fileNames} = res.body;

				if (projectHinted[configFileName] === true) {
					return;
				}

81
				if (!configFileName && vscode.workspace.rootPath) {
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
					exists(join(vscode.workspace.rootPath, 'jsconfig.json'), exists => {
						// don't hint if there is a global jsconfig-file. We can get here due
						// to TypeScript bugs or jsconfig configurations
						if (exists) {
							return;
						}
						currentHint = {
							message: localize('hintCreate', "Create a jsconfig.json to enable richer IntelliSense and code navigation across the entire workspace."),
							options: [{
								title: localize('ignore.cmdCreate', 'Ignore'),
								execute: () => {
									client.logTelemetry('js.hintProjectCreation.ignored');
									projectHinted[configFileName] = true;
									projectHintIgnoreList.push(configFileName);
									memento.update('projectHintIgnoreList', projectHintIgnoreList);
									item.hide();
								}
							}, {
								title: localize('cmdCreate', "Create jsconfig.json"),
								execute: () => {
									client.logTelemetry('js.hintProjectCreation.accepted');
									projectHinted[configFileName] = true;
									item.hide();

106
									return vscode.workspace.openTextDocument(vscode.Uri.parse('untitled:' + encodeURIComponent(join(vscode.workspace.rootPath, 'jsconfig.json'))))
107 108 109 110 111 112 113 114 115 116 117
										.then(doc => vscode.window.showTextDocument(doc, vscode.ViewColumn.Three))
										.then(editor => editor.edit(builder => builder.insert(new vscode.Position(0, 0), defaultConfig)));
								}
							}]
						};
						item.text = '$(light-bulb)';
						item.tooltip = localize('hintCreate.tooltip', "Create a jsconfig.json to enable richer IntelliSense and code navigation across the entire workspace.");
						item.color = '#A5DF3B';
						item.show();
						client.logTelemetry('js.hintProjectCreation');
					});
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149

				} else if (fileNames.length > fileLimit) {

					let largeRoots = computeLargeRoots(configFileName, fileNames).map(f => `'/${f}/'`).join(', ');

					currentHint = {
						message: largeRoots.length > 0
							? localize('hintExclude', "For better performance exclude folders with many files, like: {0}", largeRoots)
							: localize('hintExclude.generic', "For better performance exclude folders with many files."),
						options: [{
							title: localize('open', "Configure Excludes"),
							execute: () => {
								client.logTelemetry('js.hintProjectExcludes.accepted');
								projectHinted[configFileName] = true;
								item.hide();

								return vscode.workspace.openTextDocument(configFileName)
									.then(vscode.window.showTextDocument);
							}
						}]
					};
					item.tooltip = currentHint.message;
					item.text = localize('large.label', "Configure Excludes");
					item.tooltip = localize('hintExclude.tooltip', "For better performance exclude folders with many files.");
					item.color = '#A5DF3B';
					item.show();
					client.logTelemetry('js.hintProjectExcludes');

				} else {
					item.hide();
				}
			});
150 151 152 153 154 155 156 157 158 159 160
		}).catch(err => {
			console.log(err);
		});
	}

	toDispose.push(vscode.window.onDidChangeActiveTextEditor(onEditor));
	onEditor(vscode.window.activeTextEditor);

	return vscode.Disposable.from(...toDispose);
}

161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
function computeLargeRoots(configFileName:string, fileNames: string[]): string[] {

	let roots: { [first: string]: number } = Object.create(null);
	let dir = dirname(configFileName);

	// console.log(dir, fileNames);

	for (let fileName of fileNames) {
		if (fileName.indexOf(dir) === 0) {
			let first = fileName.substring(dir.length + 1);
			first = first.substring(0, first.indexOf('/'));
			if (first) {
				roots[first] = (roots[first] || 0) + 1;
			}
		}
	}

	let data: { root: string; count: number }[] = [];
	for (let key in roots) {
		data.push({ root: key, count: roots[key] });
	}
182 183 184 185

	data
		.sort((a, b) => b.count - a.count)
		.filter(s => s.root === 'src' || s.root === 'test' || s.root === 'tests');
186 187 188 189 190 191 192 193 194 195 196 197 198 199

	let result: string[] = [];
	let sum = 0;
	for (let e of data) {
		sum += e.count;
		result.push(e.root);
		if (fileNames.length - sum < fileLimit) {
			break;
		}
	}

	return result;
}

200
const defaultConfig = `{
201
	${localize('jsconfig.heading', '// See https://go.microsoft.com/fwlink/?LinkId=759670\n\t// for the documentation about the jsconfig.json format')}
202
	"compilerOptions": {
203
		"target": "es6",
204 205
		"module": "commonjs",
		"allowSyntheticDefaultImports": true
206 207 208 209 210 211 212 213 214 215
	},
	"exclude": [
		"node_modules",
		"bower_components",
		"jspm_packages",
		"tmp",
		"temp"
	]
}
`;