Merge branch 'master' into master

This commit is contained in:
João Moreno
2019-02-18 11:34:04 +01:00
committed by GitHub
633 changed files with 12811 additions and 7023 deletions
+1 -1
View File
@@ -63,7 +63,7 @@
assignLabel: false
},
file-explorer: {
assignees: [ bpasero ],
assignees: [ isidorn ],
assignLabel: false
},
file-glob: [],
+15 -9
View File
@@ -42,13 +42,19 @@
"emmet.excludeLanguages": [],
"typescript.preferences.importModuleSpecifier": "non-relative",
"typescript.preferences.quoteStyle": "single",
"json.schemas": [{
"fileMatch": [ "cgmanifest.json" ],
"url": "./.vscode/cgmanifest.schema.json"
}, {
"fileMatch": [ "cglicenses.json" ],
"url": "./.vscode/cglicenses.schema.json"
}
],
"git.ignoreLimitWarning": true
"json.schemas": [
{
"fileMatch": [
"cgmanifest.json"
],
"url": "./.vscode/cgmanifest.schema.json"
},
{
"fileMatch": [
"cglicenses.json"
],
"url": "./.vscode/cglicenses.schema.json"
}
],
"git.ignoreLimitWarning": true
}
+2 -1
View File
@@ -1,6 +1,7 @@
# Visual Studio Code - Open Source
[![Build Status](https://dev.azure.com/vscode/VSCode/_apis/build/status/VS%20Code?branchName=master)](https://aka.ms/vscode-builds)
<!-- [![Build Status](https://dev.azure.com/vscode/VSCode/_apis/build/status/VS%20Code?branchName=master)](https://aka.ms/vscode-builds) -->
[![Build Status](https://dev.azure.com/vscode/VSCode/_apis/build/status/VS%20Code?branchName=master)](https://dev.azure.com/vscode/VSCode/_build/latest?definitionId=12)
[![Feature Requests](https://img.shields.io/github/issues/Microsoft/vscode/feature-request.svg)](https://github.com/Microsoft/vscode/issues?q=is%3Aopen+is%3Aissue+label%3Afeature-request+sort%3Areactions-%2B1-desc)
[![Bugs](https://img.shields.io/github/issues/Microsoft/vscode/bug.svg)](https://github.com/Microsoft/vscode/issues?utf8=✓&q=is%3Aissue+is%3Aopen+label%3Abug)
[![Gitter](https://img.shields.io/badge/chat-on%20gitter-yellow.svg)](https://gitter.im/Microsoft/vscode)
+3 -3
View File
@@ -1,7 +1,7 @@
[
{
"name": "ms-vscode.node-debug",
"version": "1.31.2",
"version": "1.32.1",
"repo": "https://github.com/Microsoft/vscode-node-debug",
"metadata": {
"id": "b6ded8fb-a0a0-4c1c-acbd-ab2a3bc995a6",
@@ -16,7 +16,7 @@
},
{
"name": "ms-vscode.node-debug2",
"version": "1.31.5",
"version": "1.31.6",
"repo": "https://github.com/Microsoft/vscode-node-debug2",
"metadata": {
"id": "36d19e17-7569-4841-a001-947eb18602b2",
@@ -31,7 +31,7 @@
},
{
"name": "ms-vscode.references-view",
"version": "0.0.25",
"version": "0.0.26",
"repo": "https://github.com/Microsoft/vscode-reference-view",
"metadata": {
"id": "dc489f46-520d-4556-ae85-1f9eab3c412d",
+3 -5
View File
@@ -6,15 +6,13 @@
'use strict';
const util = require('./lib/util');
const task = require('./lib/task');
const compilation = require('./lib/compilation');
const { compileExtensionsBuildTask } = require('./gulpfile.extensions');
// Full compile, including nls and inline sources in sourcemaps, for build
const compileClientBuildTask = util.task.series(util.rimraf('out-build'), compilation.compileTask('src', 'out-build', true));
compileClientBuildTask.displayName = 'compile-client-build';
const compileClientBuildTask = task.define('compile-client-build', task.series(util.rimraf('out-build'), compilation.compileTask('src', 'out-build', true)));
// All Build
const compileBuildTask = util.task.parallel(compileClientBuildTask, compileExtensionsBuildTask);
compileBuildTask.displayName = 'compile-build';
const compileBuildTask = task.define('compile-build', task.parallel(compileClientBuildTask, compileExtensionsBuildTask));
exports.compileBuildTask = compileBuildTask;
+20 -28
View File
@@ -6,6 +6,7 @@
const gulp = require('gulp');
const path = require('path');
const util = require('./lib/util');
const task = require('./lib/task');
const common = require('./lib/optimize');
const es = require('event-stream');
const File = require('vinyl');
@@ -60,7 +61,7 @@ var BUNDLED_FILE_HEADER = [
const languages = i18n.defaultLanguages.concat([]); // i18n.defaultLanguages.concat(process.env.VSCODE_QUALITY !== 'stable' ? i18n.extraLanguages : []);
const extractEditorSrcTask = function () {
const extractEditorSrcTask = task.define('extract-editor-src', () => {
console.log(`If the build fails, consider tweaking shakeLevel below to a lower value.`);
const apiusages = monacoapi.execute().usageContent;
const extrausages = fs.readFileSync(path.join(root, 'build', 'monaco', 'monaco.usage.recipe')).toString();
@@ -95,13 +96,11 @@ const extractEditorSrcTask = function () {
importIgnorePattern: /(^vs\/css!)|(promise-polyfill\/polyfill)/,
destRoot: path.join(root, 'out-editor-src')
});
};
extractEditorSrcTask.displayName = 'extract-editor-src';
});
const compileEditorAMDTask = compilation.compileTask('out-editor-src', 'out-editor-build', true);
compileEditorAMDTask.displayName = 'compile-editor-amd';
const compileEditorAMDTask = task.define('compile-editor-amd', compilation.compileTask('out-editor-src', 'out-editor-build', true));
const optimizeEditorAMDTask = common.optimizeTask({
const optimizeEditorAMDTask = task.define('optimize-editor-amd', common.optimizeTask({
src: 'out-editor-build',
entryPoints: editorEntryPoints,
resources: editorResources,
@@ -118,13 +117,11 @@ const optimizeEditorAMDTask = common.optimizeTask({
bundleInfo: true,
out: 'out-editor',
languages: languages
});
optimizeEditorAMDTask.displayName = 'optimize-editor-amd';
}));
const minifyEditorAMDTask = common.minifyTask('out-editor');
minifyEditorAMDTask.displayName = 'minify-editor-amd';
const minifyEditorAMDTask = task.define('minify-editor-amd', common.minifyTask('out-editor'));
const createESMSourcesAndResourcesTask = function () {
const createESMSourcesAndResourcesTask = task.define('extract-editor-esm', () => {
standalone.createESMSourcesAndResources2({
srcFolder: './out-editor-src',
outFolder: './out-editor-esm',
@@ -145,10 +142,9 @@ const createESMSourcesAndResourcesTask = function () {
'vs/nls.mock.ts': 'vs/nls.ts'
}
});
};
createESMSourcesAndResourcesTask.displayName = 'extract-editor-esm';
});
const compileEditorESMTask = function () {
const compileEditorESMTask = task.define('compile-editor-esm', () => {
if (process.platform === 'win32') {
const result = cp.spawnSync(`..\\node_modules\\.bin\\tsc.cmd`, {
cwd: path.join(__dirname, '../out-editor-esm')
@@ -162,8 +158,7 @@ const compileEditorESMTask = function () {
console.log(result.stdout.toString());
console.log(result.stderr.toString());
}
};
compileEditorESMTask.displayName = 'compile-editor-esm';
});
function toExternalDTS(contents) {
let lines = contents.split('\n');
@@ -209,7 +204,7 @@ function filterStream(testFunc) {
});
}
const finalEditorResourcesTask = function () {
const finalEditorResourcesTask = task.define('final-editor-resources', () => {
return es.merge(
// other assets
es.merge(
@@ -286,12 +281,11 @@ const finalEditorResourcesTask = function () {
return /\.js\.map$/.test(path);
})).pipe(gulp.dest('out-monaco-editor-core/min-maps'))
);
};
finalEditorResourcesTask.displayName = 'final-editor-resources';
});
gulp.task('editor-distro',
util.task.series(
util.task.parallel(
task.series(
task.parallel(
util.rimraf('out-editor-src'),
util.rimraf('out-editor-build'),
util.rimraf('out-editor-esm'),
@@ -300,13 +294,13 @@ gulp.task('editor-distro',
util.rimraf('out-editor-min')
),
extractEditorSrcTask,
util.task.parallel(
util.task.series(
task.parallel(
task.series(
compileEditorAMDTask,
optimizeEditorAMDTask,
minifyEditorAMDTask
),
util.task.series(
task.series(
createESMSourcesAndResourcesTask,
compileEditorESMTask
)
@@ -367,12 +361,10 @@ function createTscCompileTask(watch) {
};
}
const monacoTypecheckWatchTask = createTscCompileTask(true);
monacoTypecheckWatchTask.displayName = 'monaco-typecheck-watch';
const monacoTypecheckWatchTask = task.define('monaco-typecheck-watch', createTscCompileTask(true));
exports.monacoTypecheckWatchTask = monacoTypecheckWatchTask;
const monacoTypecheckTask = createTscCompileTask(false);
monacoTypecheckTask.displayName = 'monaco-typecheck';
const monacoTypecheckTask = task.define('monaco-typecheck', createTscCompileTask(false));
exports.monacoTypecheckTask = monacoTypecheckTask;
//#endregion
+15 -17
View File
@@ -12,6 +12,7 @@ const tsb = require('gulp-tsb');
const es = require('event-stream');
const filter = require('gulp-filter');
const util = require('./lib/util');
const task = require('./lib/task');
const watcher = require('./lib/watch');
const createReporter = require('./lib/reporter').createReporter;
const glob = require('glob');
@@ -100,18 +101,18 @@ const tasks = compilations.map(function (tsconfigFile) {
const srcOpts = { cwd: path.dirname(__dirname), base: srcBase };
const cleanTask = () => util.primraf(out);
const cleanTask = task.define(`clean-extension-${name}`, util.rimraf(out));
const compileTask = util.task.series(cleanTask, () => {
const compileTask = task.define(`compile-extension:${name}`, task.series(cleanTask, () => {
const pipeline = createPipeline(false, true);
const input = gulp.src(src, srcOpts);
return input
.pipe(pipeline())
.pipe(gulp.dest(out));
});
}));
const watchTask = util.task.series(cleanTask, () => {
const watchTask = task.define(`watch-extension:${name}`, task.series(cleanTask, () => {
const pipeline = createPipeline(false);
const input = gulp.src(src, srcOpts);
const watchInput = watcher(src, srcOpts);
@@ -119,20 +120,20 @@ const tasks = compilations.map(function (tsconfigFile) {
return watchInput
.pipe(util.incremental(pipeline, input))
.pipe(gulp.dest(out));
});
}));
const compileBuildTask = util.task.series(cleanTask, () => {
const compileBuildTask = task.define(`compile-build-extension-${name}`, task.series(cleanTask, () => {
const pipeline = createPipeline(true, true);
const input = gulp.src(src, srcOpts);
return input
.pipe(pipeline())
.pipe(gulp.dest(out));
});
}));
// Tasks
gulp.task('compile-extension:' + name, compileTask);
gulp.task('watch-extension:' + name, watchTask);
gulp.task(compileTask);
gulp.task(watchTask);
return {
compileTask: compileTask,
@@ -141,16 +142,13 @@ const tasks = compilations.map(function (tsconfigFile) {
};
});
const compileExtensionsTask = util.task.parallel(...tasks.map(t => t.compileTask));
compileExtensionsTask.displayName = 'compile-extensions';
gulp.task(compileExtensionsTask.displayName, compileExtensionsTask);
const compileExtensionsTask = task.define('compile-extensions', task.parallel(...tasks.map(t => t.compileTask)));
gulp.task(compileExtensionsTask);
exports.compileExtensionsTask = compileExtensionsTask;
const watchExtensionsTask = util.task.parallel(...tasks.map(t => t.watchTask));
watchExtensionsTask.displayName = 'watch-extensions';
gulp.task(watchExtensionsTask.displayName, watchExtensionsTask);
const watchExtensionsTask = task.define('watch-extensions', task.parallel(...tasks.map(t => t.watchTask)));
gulp.task(watchExtensionsTask);
exports.watchExtensionsTask = watchExtensionsTask;
const compileExtensionsBuildTask = util.task.parallel(...tasks.map(t => t.compileBuildTask));
compileExtensionsBuildTask.displayName = 'compile-extensions-build';
const compileExtensionsBuildTask = task.define('compile-extensions-build', task.parallel(...tasks.map(t => t.compileBuildTask)));
exports.compileExtensionsBuildTask = compileExtensionsBuildTask;
+32 -34
View File
@@ -20,6 +20,7 @@ const filter = require('gulp-filter');
const json = require('gulp-json-editor');
const _ = require('underscore');
const util = require('./lib/util');
const task = require('./lib/task');
const ext = require('./lib/extensions');
const buildfile = require('../src/buildfile');
const common = require('./lib/optimize');
@@ -87,8 +88,8 @@ const BUNDLED_FILE_HEADER = [
' *--------------------------------------------------------*/'
].join('\n');
const optimizeVSCodeTask = util.task.series(
util.task.parallel(
const optimizeVSCodeTask = task.define('optimize-vscode', task.series(
task.parallel(
util.rimraf('out-vscode'),
compileBuildTask
),
@@ -101,11 +102,10 @@ const optimizeVSCodeTask = util.task.series(
out: 'out-vscode',
bundleInfo: undefined
})
);
optimizeVSCodeTask.displayName = 'optimize-vscode';
));
const optimizeIndexJSTask = util.task.series(
const optimizeIndexJSTask = task.define('optimize-index-js', task.series(
optimizeVSCodeTask,
() => {
const fullpath = path.join(process.cwd(), 'out-vscode/bootstrap-window.js');
@@ -113,18 +113,16 @@ const optimizeIndexJSTask = util.task.series(
const newContents = contents.replace('[/*BUILD->INSERT_NODE_MODULES*/]', JSON.stringify(nodeModules));
fs.writeFileSync(fullpath, newContents);
}
);
optimizeIndexJSTask.displayName = 'optimize-index-js';
));
const sourceMappingURLBase = `https://ticino.blob.core.windows.net/sourcemaps/${commit}`;
const minifyVSCodeTask = util.task.series(
util.task.parallel(
const minifyVSCodeTask = task.define('minify-vscode', task.series(
task.parallel(
util.rimraf('out-vscode-min'),
optimizeIndexJSTask
),
common.minifyTask('out-vscode', `${sourceMappingURLBase}/core`)
);
minifyVSCodeTask.displayName = 'minify-vscode';
));
// Package
@@ -213,12 +211,11 @@ function getElectron(arch) {
};
}
gulp.task('electron', util.task.series(util.rimraf('.build/electron'), getElectron(process.arch)));
gulp.task('electron-ia32', util.task.series(util.rimraf('.build/electron'), getElectron('ia32')));
gulp.task('electron-x64', util.task.series(util.rimraf('.build/electron'), getElectron('x64')));
gulp.task('electron-arm', util.task.series(util.rimraf('.build/electron'), getElectron('armv7l')));
gulp.task('electron-arm64', util.task.series(util.rimraf('.build/electron'), getElectron('arm64')));
gulp.task(task.define('electron', task.series(util.rimraf('.build/electron'), getElectron(process.arch))));
gulp.task(task.define('electron-ia32', task.series(util.rimraf('.build/electron'), getElectron('ia32'))));
gulp.task(task.define('electron-x64', task.series(util.rimraf('.build/electron'), getElectron('x64'))));
gulp.task(task.define('electron-arm', task.series(util.rimraf('.build/electron'), getElectron('armv7l'))));
gulp.task(task.define('electron-arm64', task.series(util.rimraf('.build/electron'), getElectron('arm64'))));
/**
* Compute checksums for some files.
@@ -457,15 +454,14 @@ BUILD_TARGETS.forEach(buildTarget => {
const sourceFolderName = `out-vscode${dashed(minified)}`;
const destinationFolderName = `VSCode${dashed(platform)}${dashed(arch)}`;
const vscodeTask = util.task.series(
util.task.parallel(
const vscodeTask = task.define(`vscode${dashed(platform)}${dashed(arch)}${dashed(minified)}`, task.series(
task.parallel(
minified ? minifyVSCodeTask : optimizeVSCodeTask,
util.rimraf(path.join(buildRoot, destinationFolderName))
),
packageTask(platform, arch, sourceFolderName, destinationFolderName, opts)
);
vscodeTask.displayName = `vscode${dashed(platform)}${dashed(arch)}${dashed(minified)}`;
gulp.task(vscodeTask.displayName, vscodeTask);
));
gulp.task(vscodeTask);
});
});
@@ -490,8 +486,9 @@ const apiHostname = process.env.TRANSIFEX_API_URL;
const apiName = process.env.TRANSIFEX_API_NAME;
const apiToken = process.env.TRANSIFEX_API_TOKEN;
gulp.task('vscode-translations-push',
util.task.series(
gulp.task(task.define(
'vscode-translations-push',
task.series(
optimizeVSCodeTask,
function () {
const pathToMetadata = './out-vscode/nls.metadata.json';
@@ -506,10 +503,11 @@ gulp.task('vscode-translations-push',
).pipe(i18n.pushXlfFiles(apiHostname, apiName, apiToken));
}
)
);
));
gulp.task('vscode-translations-export',
util.task.series(
gulp.task(task.define(
'vscode-translations-export',
task.series(
optimizeVSCodeTask,
function () {
const pathToMetadata = './out-vscode/nls.metadata.json';
@@ -523,7 +521,7 @@ gulp.task('vscode-translations-export',
).pipe(vfs.dest('../vscode-translations-export'));
}
)
);
));
gulp.task('vscode-translations-pull', function () {
return es.merge([...i18n.defaultLanguages, ...i18n.extraLanguages].map(language => {
@@ -574,7 +572,7 @@ gulp.task('upload-vscode-sourcemaps', () => {
});
// This task is only run for the MacOS build
const generateVSCodeConfigurationTask = () => {
const generateVSCodeConfigurationTask = task.define('generate-vscode-configuration', () => {
return new Promise((resolve, reject) => {
const buildDir = process.env['AGENT_BUILDDIRECTORY'];
if (!buildDir) {
@@ -609,12 +607,12 @@ const generateVSCodeConfigurationTask = () => {
reject(err);
});
});
};
generateVSCodeConfigurationTask.displayName = 'generate-vscode-configuration';
});
const allConfigDetailsPath = path.join(os.tmpdir(), 'configuration.json');
gulp.task('upload-vscode-configuration',
util.task.series(
gulp.task(task.define(
'upload-vscode-configuration',
task.series(
generateVSCodeConfigurationTask,
() => {
if (!shouldSetupSettingsSearch()) {
@@ -641,7 +639,7 @@ gulp.task('upload-vscode-configuration',
}));
}
)
);
));
function shouldSetupSettingsSearch() {
const branch = process.env.BUILD_SOURCEBRANCH;
+13 -18
View File
@@ -12,6 +12,7 @@ const shell = require('gulp-shell');
const es = require('event-stream');
const vfs = require('vinyl-fs');
const util = require('./lib/util');
const task = require('./lib/task');
const packageJson = require('../package.json');
const product = require('../product.json');
const rpmDependencies = require('../resources/linux/rpm/dependencies.json');
@@ -241,30 +242,24 @@ BUILD_TARGETS.forEach((buildTarget) => {
{
const debArch = getDebPackageArch(arch);
const prepareDebTask = util.task.series(util.rimraf(`.build/linux/deb/${debArch}`), prepareDebPackage(arch));
prepareDebTask.displayName = `vscode-linux-${arch}-prepare-deb`;
// gulp.task(prepareDebTask.displayName, prepareDebTask);
const buildDebTask = util.task.series(prepareDebTask, buildDebPackage(arch));
buildDebTask.displayName = `vscode-linux-${arch}-build-deb`;
gulp.task(buildDebTask.displayName, buildDebTask);
const prepareDebTask = task.define(`vscode-linux-${arch}-prepare-deb`, task.series(util.rimraf(`.build/linux/deb/${debArch}`), prepareDebPackage(arch)));
// gulp.task(prepareDebTask);
const buildDebTask = task.define(`vscode-linux-${arch}-build-deb`, task.series(prepareDebTask, buildDebPackage(arch)));
gulp.task(buildDebTask);
}
{
const rpmArch = getRpmPackageArch(arch);
const prepareRpmTask = util.task.series(util.rimraf(`.build/linux/rpm/${rpmArch}`), prepareRpmPackage(arch));
prepareRpmTask.displayName = `vscode-linux-${arch}-prepare-rpm`;
// gulp.task(prepareRpmTask.displayName, prepareRpmTask);
const buildRpmTask = util.task.series(prepareRpmTask, buildRpmPackage(arch));
buildRpmTask.displayName = `vscode-linux-${arch}-build-rpm`;
gulp.task(buildRpmTask.displayName, buildRpmTask);
const prepareRpmTask = task.define(`vscode-linux-${arch}-prepare-rpm`, task.series(util.rimraf(`.build/linux/rpm/${rpmArch}`), prepareRpmPackage(arch)));
// gulp.task(prepareRpmTask);
const buildRpmTask = task.define(`vscode-linux-${arch}-build-rpm`, task.series(prepareRpmTask, buildRpmPackage(arch)));
gulp.task(buildRpmTask);
}
{
const prepareSnapTask = util.task.series(util.rimraf(`.build/linux/snap/${arch}`), prepareSnapPackage(arch));
prepareSnapTask.displayName = `vscode-linux-${arch}-prepare-snap`;
gulp.task(prepareSnapTask.displayName, prepareSnapTask);
const buildSnapTask = util.task.series(prepareSnapTask, buildSnapPackage(arch));
buildSnapTask.displayName = `vscode-linux-${arch}-build-snap`;
gulp.task(buildSnapTask.displayName, buildSnapTask);
const prepareSnapTask = task.define(`vscode-linux-${arch}-prepare-snap`, task.series(util.rimraf(`.build/linux/snap/${arch}`), prepareSnapPackage(arch)));
gulp.task(prepareSnapTask);
const buildSnapTask = task.define(`vscode-linux-${arch}-build-snap`, task.series(prepareSnapTask, buildSnapPackage(arch)));
gulp.task(buildSnapTask);
}
});
+7 -6
View File
@@ -12,6 +12,7 @@ const assert = require('assert');
const cp = require('child_process');
const _7z = require('7zip')['7z'];
const util = require('./lib/util');
const task = require('./lib/task');
const pkg = require('../package.json');
const product = require('../product.json');
const vfs = require('vinyl-fs');
@@ -105,8 +106,8 @@ function buildWin32Setup(arch, target) {
}
function defineWin32SetupTasks(arch, target) {
const cleanTask = () => util.primraf(setupDir(arch, target));
gulp.task(`vscode-win32-${arch}-${target}-setup`, util.task.series(cleanTask, buildWin32Setup(arch, target)));
const cleanTask = util.rimraf(setupDir(arch, target));
gulp.task(task.define(`vscode-win32-${arch}-${target}-setup`, task.series(cleanTask, buildWin32Setup(arch, target))));
}
defineWin32SetupTasks('ia32', 'system');
@@ -124,8 +125,8 @@ function archiveWin32Setup(arch) {
};
}
gulp.task('vscode-win32-ia32-archive', util.task.series(util.rimraf(zipDir('ia32')), archiveWin32Setup('ia32')));
gulp.task('vscode-win32-x64-archive', util.task.series(util.rimraf(zipDir('x64')), archiveWin32Setup('x64')));
gulp.task(task.define('vscode-win32-ia32-archive', task.series(util.rimraf(zipDir('ia32')), archiveWin32Setup('ia32'))));
gulp.task(task.define('vscode-win32-x64-archive', task.series(util.rimraf(zipDir('x64')), archiveWin32Setup('x64'))));
function copyInnoUpdater(arch) {
return () => {
@@ -141,5 +142,5 @@ function patchInnoUpdater(arch) {
};
}
gulp.task('vscode-win32-ia32-inno-updater', util.task.series(copyInnoUpdater('ia32'), patchInnoUpdater('ia32')));
gulp.task('vscode-win32-x64-inno-updater', util.task.series(copyInnoUpdater('x64'), patchInnoUpdater('x64')));
gulp.task(task.define('vscode-win32-ia32-inno-updater', task.series(copyInnoUpdater('ia32'), patchInnoUpdater('ia32'))));
gulp.task(task.define('vscode-win32-x64-inno-updater', task.series(copyInnoUpdater('x64'), patchInnoUpdater('x64'))));
+12
View File
@@ -38,6 +38,10 @@
"name": "vs/workbench/contrib/codeEditor",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/contrib/codeinset",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/contrib/comments",
"project": "vscode-workbench"
@@ -118,6 +122,10 @@
"name": "vs/workbench/contrib/snippets",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/contrib/format",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/contrib/stats",
"project": "vscode-workbench"
@@ -210,6 +218,10 @@
"name": "vs/workbench/services/files",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/integrity",
"project": "vscode-workbench"
},
{
"name": "vs/workbench/services/keybinding",
"project": "vscode-workbench"
+2 -4
View File
@@ -27,7 +27,7 @@ function writeFile(filePath, contents) {
fs.writeFileSync(filePath, contents);
}
function extractEditor(options) {
const tsConfig = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.json')).toString());
const tsConfig = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.monaco.json')).toString());
let compilerOptions;
if (tsConfig.extends) {
compilerOptions = Object.assign({}, require(path.join(options.sourcesRoot, tsConfig.extends)).compilerOptions, tsConfig.compilerOptions);
@@ -36,13 +36,11 @@ function extractEditor(options) {
compilerOptions = tsConfig.compilerOptions;
}
tsConfig.compilerOptions = compilerOptions;
compilerOptions.noEmit = false;
compilerOptions.noUnusedLocals = false;
compilerOptions.preserveConstEnums = false;
compilerOptions.declaration = false;
compilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;
delete compilerOptions.types;
delete tsConfig.extends;
tsConfig.exclude = [];
options.compilerOptions = compilerOptions;
let result = tss.shake(options);
for (let fileName in result) {
+2 -4
View File
@@ -31,7 +31,7 @@ function writeFile(filePath: string, contents: Buffer | string): void {
}
export function extractEditor(options: tss.ITreeShakingOptions & { destRoot: string }): void {
const tsConfig = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.json')).toString());
const tsConfig = JSON.parse(fs.readFileSync(path.join(options.sourcesRoot, 'tsconfig.monaco.json')).toString());
let compilerOptions: { [key: string]: any };
if (tsConfig.extends) {
compilerOptions = Object.assign({}, require(path.join(options.sourcesRoot, tsConfig.extends)).compilerOptions, tsConfig.compilerOptions);
@@ -40,14 +40,12 @@ export function extractEditor(options: tss.ITreeShakingOptions & { destRoot: str
}
tsConfig.compilerOptions = compilerOptions;
compilerOptions.noEmit = false;
compilerOptions.noUnusedLocals = false;
compilerOptions.preserveConstEnums = false;
compilerOptions.declaration = false;
compilerOptions.moduleResolution = ts.ModuleResolutionKind.Classic;
delete compilerOptions.types;
delete tsConfig.extends;
tsConfig.exclude = [];
options.compilerOptions = compilerOptions;
+96
View File
@@ -0,0 +1,96 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
const fancyLog = require("fancy-log");
const ansiColors = require("ansi-colors");
function _isPromise(p) {
if (typeof p.then === 'function') {
return true;
}
return false;
}
function _renderTime(time) {
return `${Math.round(time)} ms`;
}
async function _execute(task) {
const name = task.taskName || task.displayName || `<anonymous>`;
if (!task._tasks) {
fancyLog('Starting', ansiColors.cyan(name), '...');
}
const startTime = process.hrtime();
await _doExecute(task);
const elapsedArr = process.hrtime(startTime);
const elapsedNanoseconds = (elapsedArr[0] * 1e9 + elapsedArr[1]);
if (!task._tasks) {
fancyLog(`Finished`, ansiColors.cyan(name), 'after', ansiColors.magenta(_renderTime(elapsedNanoseconds / 1e6)));
}
}
async function _doExecute(task) {
// Always invoke as if it were a callback task
return new Promise((resolve, reject) => {
if (task.length === 1) {
// this is a calback task
task((err) => {
if (err) {
return reject(err);
}
resolve();
});
return;
}
const taskResult = task();
if (typeof taskResult === 'undefined') {
// this is a sync task
resolve();
return;
}
if (_isPromise(taskResult)) {
// this is a promise returning task
taskResult.then(resolve, reject);
return;
}
// this is a stream returning task
taskResult.on('end', _ => resolve());
taskResult.on('error', err => reject(err));
});
}
function series(...tasks) {
const result = async () => {
for (let i = 0; i < tasks.length; i++) {
await _execute(tasks[i]);
}
};
result._tasks = tasks;
return result;
}
exports.series = series;
function parallel(...tasks) {
const result = async () => {
await Promise.all(tasks.map(t => _execute(t)));
};
result._tasks = tasks;
return result;
}
exports.parallel = parallel;
function define(name, task) {
if (task._tasks) {
// This is a composite task
const lastTask = task._tasks[task._tasks.length - 1];
if (lastTask._tasks || lastTask.taskName) {
// This is a composite task without a real task function
// => generate a fake task function
return define(name, series(task, () => Promise.resolve()));
}
lastTask.taskName = name;
task.displayName = name;
return task;
}
// This is a simple task
task.taskName = name;
task.displayName = name;
return task;
}
exports.define = define;
+125
View File
@@ -0,0 +1,125 @@
/*---------------------------------------------------------------------------------------------
* 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 fancyLog from 'fancy-log';
import * as ansiColors from 'ansi-colors';
export interface BaseTask {
displayName?: string;
taskName?: string;
_tasks?: Task[];
}
export interface PromiseTask extends BaseTask {
(): Promise<void>;
}
export interface StreamTask extends BaseTask {
(): NodeJS.ReadWriteStream;
}
export interface CallbackTask extends BaseTask {
(cb?: (err?: any) => void): void;
}
export type Task = PromiseTask | StreamTask | CallbackTask;
function _isPromise(p: Promise<void> | NodeJS.ReadWriteStream): p is Promise<void> {
if (typeof (<any>p).then === 'function') {
return true;
}
return false;
}
function _renderTime(time: number): string {
return `${Math.round(time)} ms`;
}
async function _execute(task: Task): Promise<void> {
const name = task.taskName || task.displayName || `<anonymous>`;
if (!task._tasks) {
fancyLog('Starting', ansiColors.cyan(name), '...');
}
const startTime = process.hrtime();
await _doExecute(task);
const elapsedArr = process.hrtime(startTime);
const elapsedNanoseconds = (elapsedArr[0] * 1e9 + elapsedArr[1]);
if (!task._tasks) {
fancyLog(`Finished`, ansiColors.cyan(name), 'after', ansiColors.magenta(_renderTime(elapsedNanoseconds / 1e6)));
}
}
async function _doExecute(task: Task): Promise<void> {
// Always invoke as if it were a callback task
return new Promise((resolve, reject) => {
if (task.length === 1) {
// this is a calback task
task((err) => {
if (err) {
return reject(err);
}
resolve();
});
return;
}
const taskResult = task();
if (typeof taskResult === 'undefined') {
// this is a sync task
resolve();
return;
}
if (_isPromise(taskResult)) {
// this is a promise returning task
taskResult.then(resolve, reject);
return;
}
// this is a stream returning task
taskResult.on('end', _ => resolve());
taskResult.on('error', err => reject(err));
});
}
export function series(...tasks: Task[]): PromiseTask {
const result = async () => {
for (let i = 0; i < tasks.length; i++) {
await _execute(tasks[i]);
}
};
result._tasks = tasks;
return result;
}
export function parallel(...tasks: Task[]): PromiseTask {
const result = async () => {
await Promise.all(tasks.map(t => _execute(t)));
};
result._tasks = tasks;
return result;
}
export function define(name: string, task: Task): Task {
if (task._tasks) {
// This is a composite task
const lastTask = task._tasks[task._tasks.length - 1];
if (lastTask._tasks || lastTask.taskName) {
// This is a composite task without a real task function
// => generate a fake task function
return define(name, series(task, () => Promise.resolve()));
}
lastTask.taskName = name;
task.displayName = name;
return task;
}
// This is a simple task
task.taskName = name;
task.displayName = name;
return task;
}
+2 -68
View File
@@ -180,76 +180,10 @@ function rimraf(dir) {
return cb(err);
});
};
return cb => retry(cb);
retry.taskName = `clean-${path.basename(dir)}`;
return retry;
}
exports.rimraf = rimraf;
/**
* Like rimraf (with 5 retries), but with a promise instead of a callback.
*/
function primraf(dir) {
const fn = rimraf(dir);
return new Promise((resolve, reject) => {
fn((err) => {
if (err) {
return reject(err);
}
resolve();
});
});
}
exports.primraf = primraf;
var task;
(function (task_1) {
function _isPromise(p) {
if (typeof p.then === 'function') {
return true;
}
return false;
}
async function _execute(task) {
// Always invoke as if it were a callback task
return new Promise((resolve, reject) => {
if (task.length === 1) {
// this is a calback task
task((err) => {
if (err) {
return reject(err);
}
resolve();
});
return;
}
const taskResult = task();
if (typeof taskResult === 'undefined') {
// this is a sync task
resolve();
return;
}
if (_isPromise(taskResult)) {
// this is a promise returning task
taskResult.then(resolve, reject);
return;
}
// this is a stream returning task
taskResult.on('end', _ => resolve());
taskResult.on('error', err => reject(err));
});
}
function series(...tasks) {
return async () => {
for (let i = 0; i < tasks.length; i++) {
await _execute(tasks[i]);
}
};
}
task_1.series = series;
function parallel(...tasks) {
return async () => {
await Promise.all(tasks.map(t => _execute(t)));
};
}
task_1.parallel = parallel;
})(task = exports.task || (exports.task = {}));
function getVersion(root) {
let version = process.env['BUILD_SOURCEVERSION'];
if (!version || !/^[0-9a-f]{40}$/i.test(version)) {
+2 -80
View File
@@ -233,86 +233,8 @@ export function rimraf(dir: string): (cb: any) => void {
return cb(err);
});
};
return cb => retry(cb);
}
/**
* Like rimraf (with 5 retries), but with a promise instead of a callback.
*/
export function primraf(dir: string): Promise<void> {
const fn = rimraf(dir);
return new Promise((resolve, reject) => {
fn((err: any) => {
if (err) {
return reject(err);
}
resolve();
});
});
}
export type PromiseTask = () => Promise<void>;
export type StreamTask = () => NodeJS.ReadWriteStream;
export type CallbackTask = (cb?: (err?: any) => void) => void;
export type Task = PromiseTask | StreamTask | CallbackTask;
export namespace task {
function _isPromise(p: Promise<void> | NodeJS.ReadWriteStream): p is Promise<void> {
if (typeof (<any>p).then === 'function') {
return true;
}
return false;
}
async function _execute(task: Task): Promise<void> {
// Always invoke as if it were a callback task
return new Promise((resolve, reject) => {
if (task.length === 1) {
// this is a calback task
task((err) => {
if (err) {
return reject(err);
}
resolve();
});
return;
}
const taskResult = task();
if (typeof taskResult === 'undefined') {
// this is a sync task
resolve();
return;
}
if (_isPromise(taskResult)) {
// this is a promise returning task
taskResult.then(resolve, reject);
return;
}
// this is a stream returning task
taskResult.on('end', _ => resolve());
taskResult.on('error', err => reject(err));
});
}
export function series(...tasks: Task[]): PromiseTask {
return async () => {
for (let i = 0; i < tasks.length; i++) {
await _execute(tasks[i]);
}
};
}
export function parallel(...tasks: Task[]): PromiseTask {
return async () => {
await Promise.all(tasks.map(t => _execute(t)));
};
}
retry.taskName = `clean-${path.basename(dir)}`;
return retry;
}
export function getVersion(root: string): string | undefined {
@@ -22,9 +22,6 @@ const fadedDecoration = vscode.window.createTextEditorDecorationType({
let pendingLaunchJsonDecoration: NodeJS.Timer;
export function activate(context: vscode.ExtensionContext): void {
//keybindings.json command-suggestions
context.subscriptions.push(registerKeybindingsCompletions());
//settings.json suggestions
context.subscriptions.push(registerSettingsCompletions());
@@ -94,23 +91,6 @@ function autoFixSettingsJSON(willSaveEvent: vscode.TextDocumentWillSaveEvent): v
vscode.workspace.applyEdit(edit));
}
function registerKeybindingsCompletions(): vscode.Disposable {
const commands = vscode.commands.getCommands(true);
return vscode.languages.registerCompletionItemProvider({ pattern: '**/keybindings.json' }, {
provideCompletionItems(document, position, _token) {
const location = getLocation(document.getText(), document.offsetAt(position));
if (location.path[1] === 'command') {
const range = document.getWordRangeAtPosition(position) || new vscode.Range(position, position);
return commands.then(ids => ids.map(id => newSimpleCompletionItem(JSON.stringify(id), range)));
}
return undefined;
}
});
}
function registerSettingsCompletions(): vscode.Disposable {
return vscode.languages.registerCompletionItemProvider({ language: 'jsonc', pattern: '**/settings.json' }, {
provideCompletionItems(document, position, token) {
@@ -207,16 +187,6 @@ function provideInstalledExtensionProposals(extensionsContent: IExtensionsConten
return undefined;
}
function newSimpleCompletionItem(label: string, range: vscode.Range, description?: string, insertText?: string): vscode.CompletionItem {
const item = new vscode.CompletionItem(label);
item.kind = vscode.CompletionItemKind.Value;
item.detail = description;
item.insertText = insertText || label;
item.range = range;
return item;
}
function updateLaunchJsonDecorations(editor: vscode.TextEditor | undefined): void {
if (!editor || path.basename(editor.document.fileName) !== 'launch.json') {
return;
@@ -81,35 +81,39 @@ export function activate(context: ExtensionContext) {
documentSelector.forEach(selector => {
context.subscriptions.push(languages.registerSelectionRangeProvider(selector, {
async provideSelectionRanges(document: TextDocument, position: Position): Promise<SelectionRange[]> {
async provideSelectionRanges(document: TextDocument, positions: Position[]): Promise<SelectionRange[][]> {
const textDocument = client.code2ProtocolConverter.asTextDocumentIdentifier(document);
const rawRanges = await client.sendRequest<Range[]>('$/textDocument/selectionRange', { textDocument, position });
if (Array.isArray(rawRanges)) {
return rawRanges.map(r => {
return {
range: client.protocol2CodeConverter.asRange(r),
kind: SelectionRangeKind.Declaration
};
});
}
return [];
return Promise.all(positions.map(async position => {
const rawRanges = await client.sendRequest<Range[]>('$/textDocument/selectionRange', { textDocument, position });
if (Array.isArray(rawRanges)) {
return rawRanges.map(r => {
return {
range: client.protocol2CodeConverter.asRange(r),
kind: SelectionRangeKind.Declaration
};
});
}
return [];
}));
}
}));
});
});
const selectionRangeProvider = {
async provideSelectionRanges(document: TextDocument, position: Position): Promise<SelectionRange[]> {
async provideSelectionRanges(document: TextDocument, positions: Position[]): Promise<SelectionRange[][]> {
const textDocument = TextDocumentIdentifier.create(document.uri.toString());
const rawRanges: Range[] = await client.sendRequest('$/textDocument/selectionRange', { textDocument, position });
return Promise.all(positions.map(async position => {
const rawRanges: Range[] = await client.sendRequest('$/textDocument/selectionRange', { textDocument, position });
return rawRanges.map(r => {
const actualRange = new Range(new Position(r.start.line, r.start.character), new Position(r.end.line, r.end.character));
return {
range: actualRange,
kind: SelectionRangeKind.Declaration
};
});
return rawRanges.map(r => {
const actualRange = new Range(new Position(r.start.line, r.start.character), new Position(r.end.line, r.end.character));
return {
range: actualRange,
kind: SelectionRangeKind.Declaration
};
});
}));
}
};
documentSelector.forEach(selector => {
@@ -49,7 +49,7 @@ export function getCustomDataPathsFromAllExtensions(): string[] {
const contributes = extension.packageJSON && extension.packageJSON.contributes;
if (contributes && contributes.css && contributes.css.experimental.customData && Array.isArray(contributes.css.experimental.customData)) {
const relativePaths: string[] = contributes.css.customData;
const relativePaths: string[] = contributes.css.experimental.customData;
relativePaths.forEach(rp => {
dataPaths.push(path.resolve(extension.extensionPath, rp));
});
+5 -1
View File
@@ -54,7 +54,11 @@ function doWrapping(individualLines: boolean, args: any) {
return;
}
}
const syntax = 'html';
args = args || {};
if (!args['language']) {
args['language'] = editor.document.languageId;
}
const syntax = getSyntaxFromArgs(args) || 'html';
const rootNode = parseDocument(editor.document, false);
let inPreview = false;
@@ -134,19 +134,7 @@ suite('Tests for Wrap with Abbreviations', () => {
<!-- /.hello -->
</ul>
`;
return withRandomFileEditor(contents, 'html', (editor, _) => {
editor.selections = [new Selection(2, 0, 2, 0)];
const promise = wrapWithAbbreviation({ abbreviation: 'li.hello|c' });
if (!promise) {
assert.equal(1, 2, 'Wrap returned undefined instead of promise.');
return Promise.resolve();
}
return promise.then(() => {
assert.equal(editor.document.getText(), expectedContents);
return Promise.resolve();
});
});
return testWrapWithAbbreviation([new Selection(2, 0, 2, 0)], 'li.hello|c', expectedContents, contents);
});
test('Wrap with abbreviation entire node when cursor is on opening tag', () => {
@@ -162,19 +150,7 @@ suite('Tests for Wrap with Abbreviations', () => {
</div>
</div>
`;
return withRandomFileEditor(contents, 'html', (editor, _) => {
editor.selections = [new Selection(1, 1, 1, 1)];
const promise = wrapWithAbbreviation({ abbreviation: 'div' });
if (!promise) {
assert.equal(1, 2, 'Wrap returned undefined instead of promise.');
return Promise.resolve();
}
return promise.then(() => {
assert.equal(editor.document.getText(), expectedContents);
return Promise.resolve();
});
});
return testWrapWithAbbreviation([new Selection(1, 1, 1, 1)], 'div', expectedContents, contents);
});
test('Wrap with abbreviation entire node when cursor is on closing tag', () => {
@@ -190,19 +166,7 @@ suite('Tests for Wrap with Abbreviations', () => {
</div>
</div>
`;
return withRandomFileEditor(contents, 'html', (editor, _) => {
editor.selections = [new Selection(3, 1, 3, 1)];
const promise = wrapWithAbbreviation({ abbreviation: 'div' });
if (!promise) {
assert.equal(1, 2, 'Wrap returned undefined instead of promise.');
return Promise.resolve();
}
return promise.then(() => {
assert.equal(editor.document.getText(), expectedContents);
return Promise.resolve();
});
});
return testWrapWithAbbreviation([new Selection(3, 1, 3, 1)], 'div', expectedContents, contents);
});
test('Wrap with multiline abbreviation doesnt add extra spaces', () => {
@@ -215,19 +179,7 @@ suite('Tests for Wrap with Abbreviations', () => {
<li><a href="">hello</a></li>
</ul>
`;
return withRandomFileEditor(contents, 'html', (editor, _) => {
editor.selections = [new Selection(1, 2, 1, 2)];
const promise = wrapWithAbbreviation({ abbreviation: 'ul>li>a' });
if (!promise) {
assert.equal(1, 2, 'Wrap returned undefined instead of promise.');
return Promise.resolve();
}
return promise.then(() => {
assert.equal(editor.document.getText(), expectedContents);
return Promise.resolve();
});
});
return testWrapWithAbbreviation([new Selection(1, 2, 1, 2)], 'ul>li>a', expectedContents, contents);
});
test('Wrap individual lines with abbreviation', () => {
@@ -245,18 +197,7 @@ suite('Tests for Wrap with Abbreviations', () => {
</ul>
</ul>
`;
return withRandomFileEditor(contents, 'html', (editor, _) => {
editor.selections = [new Selection(2, 2, 3, 33)];
const promise = wrapIndividualLinesWithAbbreviation({ abbreviation: 'ul>li.hello$*' });
if (!promise) {
assert.equal(1, 2, 'Wrap Individual Lines with Abbreviation returned undefined.');
return Promise.resolve();
}
return promise.then(() => {
assert.equal(editor.document.getText(), wrapIndividualLinesExpected);
return Promise.resolve();
});
});
return testWrapIndividualLinesWithAbbreviation([new Selection(2, 2, 3, 33)], 'ul>li.hello$*', wrapIndividualLinesExpected, contents);
});
test('Wrap individual lines with abbreviation with extra space selected', () => {
@@ -274,18 +215,7 @@ suite('Tests for Wrap with Abbreviations', () => {
</ul>
</ul>
`;
return withRandomFileEditor(contents, 'html', (editor, _) => {
editor.selections = [new Selection(2, 1, 4, 0)];
const promise = wrapIndividualLinesWithAbbreviation({ abbreviation: 'ul>li.hello$*' });
if (!promise) {
assert.equal(1, 2, 'Wrap Individual Lines with Abbreviation returned undefined.');
return Promise.resolve();
}
return promise.then(() => {
assert.equal(editor.document.getText(), wrapIndividualLinesExpected);
return Promise.resolve();
});
});
return testWrapIndividualLinesWithAbbreviation([new Selection(2, 1, 4, 0)], 'ul>li.hello$*', wrapIndividualLinesExpected, contents);
});
test('Wrap individual lines with abbreviation with comment filter', () => {
@@ -305,18 +235,7 @@ suite('Tests for Wrap with Abbreviations', () => {
</ul>
</ul>
`;
return withRandomFileEditor(contents, 'html', (editor, _) => {
editor.selections = [new Selection(2, 2, 3, 33)];
const promise = wrapIndividualLinesWithAbbreviation({ abbreviation: 'ul>li.hello*|c' });
if (!promise) {
assert.equal(1, 2, 'Wrap Individual Lines with Abbreviation returned undefined.');
return Promise.resolve();
}
return promise.then(() => {
assert.equal(editor.document.getText(), wrapIndividualLinesExpected);
return Promise.resolve();
});
});
return testWrapIndividualLinesWithAbbreviation([new Selection(2, 2, 3, 33)], 'ul>li.hello*|c', wrapIndividualLinesExpected, contents);
});
test('Wrap individual lines with abbreviation and trim', () => {
@@ -334,19 +253,7 @@ suite('Tests for Wrap with Abbreviations', () => {
</ul>
</ul>
`;
return withRandomFileEditor(contents, 'html', (editor, _) => {
editor.selections = [new Selection(2, 3, 3, 16)];
const promise = wrapIndividualLinesWithAbbreviation({ abbreviation: 'ul>li.hello$*|t' });
if (!promise) {
assert.equal(1, 2, 'Wrap Individual Lines with Abbreviation returned undefined.');
return Promise.resolve();
}
return promise.then(() => {
assert.equal(editor.document.getText(), wrapIndividualLinesExpected);
return Promise.resolve();
});
});
return testWrapIndividualLinesWithAbbreviation([new Selection(2, 3, 3, 16)], 'ul>li.hello$*|t', wrapIndividualLinesExpected, contents);
});
test('Wrap with abbreviation and format set to false', () => {
@@ -384,11 +291,35 @@ suite('Tests for Wrap with Abbreviations', () => {
return testWrapWithAbbreviation([new Selection(2, 4, 3, 9), new Selection(5, 4, 6, 9)], 'div', wrapMultiLineExpected, htmlContentsForWrapMultiLineTests);
});
test('Wrap multiline with abbreviation uses className for jsx files', () => {
const wrapMultiLineJsxExpected = `
<ul class="nav main">
<div className="hello">
<li class="item1">img</li>
<li class="item2">$hithere</li>
</div>
</ul>
`;
return testWrapWithAbbreviation([new Selection(2,2,3,33)], '.hello', wrapMultiLineJsxExpected, htmlContentsForWrapTests, 'jsx');
});
test('Wrap individual line with abbreviation uses className for jsx files', () => {
const wrapIndividualLinesJsxExpected = `
<ul class="nav main">
<div className="hello1"><li class="item1">img</li></div>
<div className="hello2"><li class="item2">$hithere</li></div>
</ul>
`;
return testWrapIndividualLinesWithAbbreviation([new Selection(2,2,3,33)], '.hello$*', wrapIndividualLinesJsxExpected, htmlContentsForWrapTests, 'jsx');
});
});
function testWrapWithAbbreviation(selections: Selection[], abbreviation: string, expectedContents: string, input: string = htmlContentsForWrapTests): Thenable<any> {
return withRandomFileEditor(input, 'html', (editor, _) => {
function testWrapWithAbbreviation(selections: Selection[], abbreviation: string, expectedContents: string, input: string = htmlContentsForWrapTests, fileExtension: string = 'html'): Thenable<any> {
return withRandomFileEditor(input, fileExtension, (editor, _) => {
editor.selections = selections;
const promise = wrapWithAbbreviation({ abbreviation });
if (!promise) {
@@ -402,3 +333,19 @@ function testWrapWithAbbreviation(selections: Selection[], abbreviation: string,
});
});
}
function testWrapIndividualLinesWithAbbreviation(selections: Selection[], abbreviation: string, expectedContents: string, input: string = htmlContentsForWrapTests, fileExtension: string = 'html'): Thenable<any> {
return withRandomFileEditor(input, fileExtension, (editor, _) => {
editor.selections = selections;
const promise = wrapIndividualLinesWithAbbreviation({ abbreviation });
if (!promise) {
assert.equal(1, 2, 'Wrap individual lines with Abbreviation returned undefined.');
return Promise.resolve();
}
return promise.then(() => {
assert.equal(editor.document.getText(), expectedContents);
return Promise.resolve();
});
});
}
+1 -1
View File
@@ -122,7 +122,7 @@ class FolderDetector {
if (platform === 'win32' && await exists(path.join(rootPath!, 'node_modules', '.bin', 'gulp.cmd'))) {
const globalGulp = path.join(process.env.APPDATA ? process.env.APPDATA : '', 'npm', 'gulp.cmd');
if (await exists(globalGulp)) {
gulpCommand = globalGulp;
gulpCommand = '"' + globalGulp + '"';
} else {
gulpCommand = path.join('.', 'node_modules', '.bin', 'gulp.cmd');
}
@@ -55,7 +55,7 @@ export function getCustomDataPathsFromAllExtensions(): string[] {
contributes.html.experimental.customData &&
Array.isArray(contributes.html.experimental.customData)
) {
const relativePaths: string[] = contributes.html.customData;
const relativePaths: string[] = contributes.html.experimental.customData;
relativePaths.forEach(rp => {
dataPaths.push(path.resolve(extension.extensionPath, rp));
});
@@ -90,18 +90,20 @@ export function activate(context: ExtensionContext) {
documentSelector.forEach(selector => {
context.subscriptions.push(languages.registerSelectionRangeProvider(selector, {
async provideSelectionRanges(document: TextDocument, position: Position): Promise<SelectionRange[]> {
async provideSelectionRanges(document: TextDocument, positions: Position[]): Promise<SelectionRange[][]> {
const textDocument = client.code2ProtocolConverter.asTextDocumentIdentifier(document);
const rawRanges = await client.sendRequest<Range[]>('$/textDocument/selectionRange', { textDocument, position });
if (Array.isArray(rawRanges)) {
return rawRanges.map(r => {
return {
range: client.protocol2CodeConverter.asRange(r),
kind: SelectionRangeKind.Declaration
};
});
}
return [];
return Promise.all(positions.map(async position => {
const rawRanges = await client.sendRequest<Range[]>('$/textDocument/selectionRange', { textDocument, position });
if (Array.isArray(rawRanges)) {
return rawRanges.map(r => {
return {
range: client.protocol2CodeConverter.asRange(r),
kind: SelectionRangeKind.Declaration
};
});
}
return [];
}));
}
}));
});
@@ -4,7 +4,7 @@
"If you want to provide a fix or improvement, please create a pull request against the original repository.",
"Once accepted there, we are happy to receive an update request."
],
"version": "https://github.com/Microsoft/TypeScript-TmLanguage/commit/a42e5cbe14945ccc0493f62b1e2d63eddcdaa6f6",
"version": "https://github.com/Microsoft/TypeScript-TmLanguage/commit/06d49b5ea993412a21aad630a17c6e7e7081c30f",
"name": "JavaScript (with React support)",
"scopeName": "source.js",
"patterns": [
@@ -4396,7 +4396,7 @@
"patterns": [
{
"name": "string.regexp.js",
"begin": "(?<!\\+\\+|--|})(?<=[=(:,\\[?+!]|^return|[^\\._$[:alnum:]]return|^case|[^\\._$[:alnum:]]case|=>|&&|\\|\\||\\*\\/)\\s*(\\/)(?![\\/*])(?=(?:[^\\/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"begin": "(?<!\\+\\+|--|})(?<=[=(:,\\[?+!]|^return|[^\\._$[:alnum:]]return|^case|[^\\._$[:alnum:]]case|=>|&&|\\|\\||\\*\\/)\\s*(\\/)(?![\\/*])(?=(?:[^\\/\\\\\\[\\()]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\]|\\(([^\\)\\\\]|\\\\.)+\\))+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"beginCaptures": {
"1": {
"name": "punctuation.definition.string.begin.js"
@@ -4419,7 +4419,7 @@
},
{
"name": "string.regexp.js",
"begin": "(?<![_$[:alnum:])\\]]|\\+\\+|--|})\\/(?![\\/*])(?=(?:[^\\/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"begin": "(?<![_$[:alnum:])\\]]|\\+\\+|--|}|\\*\\/)\\/(?![\\/*])(?=(?:[^\\/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.js"
@@ -4,7 +4,7 @@
"If you want to provide a fix or improvement, please create a pull request against the original repository.",
"Once accepted there, we are happy to receive an update request."
],
"version": "https://github.com/Microsoft/TypeScript-TmLanguage/commit/a42e5cbe14945ccc0493f62b1e2d63eddcdaa6f6",
"version": "https://github.com/Microsoft/TypeScript-TmLanguage/commit/06d49b5ea993412a21aad630a17c6e7e7081c30f",
"name": "JavaScript (with React support)",
"scopeName": "source.js.jsx",
"patterns": [
@@ -4396,7 +4396,7 @@
"patterns": [
{
"name": "string.regexp.js.jsx",
"begin": "(?<!\\+\\+|--|})(?<=[=(:,\\[?+!]|^return|[^\\._$[:alnum:]]return|^case|[^\\._$[:alnum:]]case|=>|&&|\\|\\||\\*\\/)\\s*(\\/)(?![\\/*])(?=(?:[^\\/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"begin": "(?<!\\+\\+|--|})(?<=[=(:,\\[?+!]|^return|[^\\._$[:alnum:]]return|^case|[^\\._$[:alnum:]]case|=>|&&|\\|\\||\\*\\/)\\s*(\\/)(?![\\/*])(?=(?:[^\\/\\\\\\[\\()]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\]|\\(([^\\)\\\\]|\\\\.)+\\))+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"beginCaptures": {
"1": {
"name": "punctuation.definition.string.begin.js.jsx"
@@ -4419,7 +4419,7 @@
},
{
"name": "string.regexp.js.jsx",
"begin": "(?<![_$[:alnum:])\\]]|\\+\\+|--|})\\/(?![\\/*])(?=(?:[^\\/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"begin": "(?<![_$[:alnum:])\\]]|\\+\\+|--|}|\\*\\/)\\/(?![\\/*])(?=(?:[^\\/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.js.jsx"
@@ -13,5 +13,6 @@ server/build/**
server/yarn.lock
server/.npmignore
yarn.lock
CONTRIBUTING.md
server/extension.webpack.config.js
extension.webpack.config.js
@@ -0,0 +1,39 @@
## Setup
- Clone [Microsoft/vscode](https://github.com/microsoft/vscode)
- Run `yarn` at `/`, this will install
- Dependencies for `/extension/json-language-features/`
- Dependencies for `/extension/json-language-features/server/`
- devDependencies such as `gulp`
- Open `/extensions/json-language-features/` as the workspace in VS Code
- Run the [`Launch Extension`](https://github.com/Microsoft/vscode/blob/master/extensions/json-language-features/.vscode/launch.json) debug target in the Debug View. This will:
- Launch the `preLaunchTask` task to compile the extension
- Launch a new VS Code instance with the `json-language-features` extension loaded
- You should see a notification saying the development version of `json-language-features` overwrites the bundled version of `json-language-features`
- Open a `.json` file to activate the extension. The extension will start the JSON language server process.
- Add `"json.trace.server": "verbose"` to the settings to observe the communication between client and server.
- Debug the language server process by using `Attach to Node Process` command in the VS Code window opened on `json-language-features`
- Run `Reload Window` command in the launched instance to reload the extension
### Contribute to vscode-json-languageservice
[Microsoft/vscode-json-languageservice](https://github.com/Microsoft/vscode-json-languageservice) is the library that implements the language smarts for JSON.
The JSON language server forwards most the of requests to the service library.
If you want to fix JSON issues or make improvements, you should make changes at [Microsoft/vscode-json-languageservice](https://github.com/Microsoft/vscode-json-languageservice).
However, within this extension, you can run a development version of `vscode-json-languageservice` to debug code or test language features interactively:
#### Linking `vscode-json-languageservice` in `json-language-features/server/`
- Clone [Microsoft/vscode-json-languageservice](https://github.com/Microsoft/vscode-json-languageservice)
- Run `yarn` in `vscode-json-languageservice`
- Run `yarn link` in `vscode-json-languageservice`. This will compile and link `vscode-json-languageservice`
- In `json-language-features/server/`, run `npm link vscode-json-languageservice`
#### Testing the development version of `vscode-json-languageservice`
- Open both `vscode-json-languageservice` and this extension in a single workspace with [multi-root workspace](https://code.visualstudio.com/docs/editor/multi-root-workspaces) feature
- Run `yarn watch` at `json-languagefeatures/server/` to recompile this extension with the linked version of `vscode-json-languageservice`
- Make some changes in `vscode-json-languageservice`
- Now when you run `Launch Extension` debug target, the launched instance will use your development version of `vscode-json-languageservice`. You can interactively test the language features.
@@ -8,7 +8,7 @@ import * as fs from 'fs';
import * as nls from 'vscode-nls';
const localize = nls.loadMessageBundle();
import { workspace, window, languages, commands, ExtensionContext, extensions, Uri, LanguageConfiguration, Diagnostic, StatusBarAlignment, TextEditor, TextDocument, Position, SelectionRange, Range, SelectionRangeKind } from 'vscode';
import { workspace, window, languages, commands, ExtensionContext, extensions, Uri, LanguageConfiguration, Diagnostic, StatusBarAlignment, TextEditor, TextDocument, Position, SelectionRange } from 'vscode';
import { LanguageClient, LanguageClientOptions, RequestType, ServerOptions, TransportKind, NotificationType, DidChangeConfigurationNotification, HandleDiagnosticsSignature } from 'vscode-languageclient';
import TelemetryReporter from 'vscode-extension-telemetry';
@@ -200,15 +200,17 @@ export function activate(context: ExtensionContext) {
documentSelector.forEach(selector => {
toDispose.push(languages.registerSelectionRangeProvider(selector, {
async provideSelectionRanges(document: TextDocument, position: Position): Promise<SelectionRange[]> {
async provideSelectionRanges(document: TextDocument, positions: Position[]): Promise<SelectionRange[][]> {
const textDocument = client.code2ProtocolConverter.asTextDocumentIdentifier(document);
const rawRanges = await client.sendRequest<Range[]>('$/textDocument/selectionRange', { textDocument, position });
if (Array.isArray(rawRanges)) {
return rawRanges.map(r => {
return {
range: client.protocol2CodeConverter.asRange(r),
kind: SelectionRangeKind.Declaration
};
const rawResult = await client.sendRequest<SelectionRange[][]>('$/textDocument/selectionRanges', { textDocument, positions: positions.map(client.code2ProtocolConverter.asPosition) });
if (Array.isArray(rawResult)) {
return rawResult.map(rawSelectionRanges => {
return rawSelectionRanges.map(selectionRange => {
return {
range: client.protocol2CodeConverter.asRange(selectionRange.range),
kind: selectionRange.kind
};
});
});
}
return [];
@@ -14,7 +14,7 @@
"dependencies": {
"jsonc-parser": "^2.0.2",
"request-light": "^0.2.4",
"vscode-json-languageservice": "^3.3.0-next.0",
"vscode-json-languageservice": "^3.3.0-next.2",
"vscode-languageserver": "^5.1.0",
"vscode-nls": "^4.0.0",
"vscode-uri": "^1.0.6"
@@ -427,12 +427,12 @@ connection.onFoldingRanges((params, token) => {
}, null, `Error while computing folding ranges for ${params.textDocument.uri}`, token);
});
connection.onRequest('$/textDocument/selectionRange', async (params, token) => {
connection.onRequest('$/textDocument/selectionRanges', async (params, token) => {
return runSafe(() => {
const document = documents.get(params.textDocument.uri);
if (document) {
const jsonDocument = getJSONDocument(document);
return languageService.getSelectionRanges(document, params.position, jsonDocument);
return languageService.getSelectionRanges(document, params.positions, jsonDocument);
}
return [];
}, [], `Error while computing selection ranges for ${params.textDocument.uri}`, token);
@@ -73,10 +73,10 @@ request-light@^0.2.4:
https-proxy-agent "^2.2.1"
vscode-nls "^4.0.0"
vscode-json-languageservice@^3.3.0-next.0:
version "3.3.0-next.0"
resolved "https://registry.yarnpkg.com/vscode-json-languageservice/-/vscode-json-languageservice-3.3.0-next.0.tgz#c17db95d0eacc24f80d3b3f120ab5e03943769a0"
integrity sha512-YZXL3yHzbr0/Ar5dGdeM/f5Y0l41z/Y4QSQTdL3Hl3ScuY76IPcDEnf7iuk9yx+QoPfEHFCBDv5Rg6XVcMl8Tg==
vscode-json-languageservice@^3.3.0-next.2:
version "3.3.0-next.2"
resolved "https://registry.yarnpkg.com/vscode-json-languageservice/-/vscode-json-languageservice-3.3.0-next.2.tgz#32ac8546a7b80d910b72b0f18ef591d917fa6938"
integrity sha512-ny4vye7kqJfzm31Gvt/zkrNoav2iyck6njmdtugjWslWx1i8ZPSCa1FyPRajnORJpTXu9VC+2oYl2Vmliuywog==
dependencies:
jsonc-parser "^2.0.2"
vscode-languageserver-types "^3.13.0"
+1
View File
@@ -24,6 +24,7 @@
".jshintrc",
".jscsrc",
".eslintrc",
".swcrc",
".webmanifest",
".js.map",
".css.map"
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/
export function onceDocumentLoaded(f: () => void) {
if (document.readyState === 'loading' || document.readyState === 'uninitialized') {
if (document.readyState === 'loading' || document.readyState as string === 'uninitialized') {
document.addEventListener('DOMContentLoaded', f);
} else {
f();
@@ -19,7 +19,7 @@ const settings = getSettings();
const vscode = acquireVsCodeApi();
// Set VS Code state
const state = getData('data-state');
let state = getData('data-state');
vscode.setState(state);
const messaging = createPosterForVsCode(vscode);
@@ -152,6 +152,8 @@ if (settings.scrollEditorWithPreview) {
const line = getEditorLineNumberForPageOffset(window.scrollY);
if (typeof line === 'number' && !isNaN(line)) {
messaging.postMessage('revealLine', { line });
state.line = line;
vscode.setState(state);
}
}
}, 50));
@@ -24,13 +24,13 @@ const getCodeLineElements = (() => {
let elements: CodeLineElement[];
return () => {
if (!elements) {
elements = ([{ element: document.body, line: 0 }]).concat(Array.prototype.map.call(
document.getElementsByClassName('code-line'),
(element: any) => {
const line = +element.getAttribute('data-line');
return { element, line };
})
.filter((x: any) => !isNaN(x.line)));
elements = [{ element: document.body, line: 0 }];
for (const element of document.getElementsByClassName('code-line')) {
const line = +element.getAttribute('data-line')!;
if (!isNaN(line)) {
elements.push({ element: element as HTMLElement, line });
}
}
}
return elements;
};
@@ -6,6 +6,7 @@
"jsx": "react",
"sourceMap": true,
"strict": true,
"strictBindCallApply": true,
"noImplicitAny": true,
"noUnusedLocals": true
}
@@ -38,7 +38,7 @@ suite('markdown.WorkspaceSymbolProvider', () => {
const fileNameCount = 10;
const files: vscode.TextDocument[] = [];
for (let i = 0; i < fileNameCount; ++i) {
const testFileName = vscode.Uri.parse(`test${i}.md`);
const testFileName = vscode.Uri.file(`test${i}.md`);
files.push(new InMemoryDocument(testFileName, `# common\nabc\n## header${i}`));
}
+1 -1
View File
@@ -6,7 +6,7 @@
"git": {
"name": "TypeScript-TmLanguage",
"repositoryUrl": "https://github.com/Microsoft/TypeScript-TmLanguage",
"commitHash": "a42e5cbe14945ccc0493f62b1e2d63eddcdaa6f6"
"commitHash": "06d49b5ea993412a21aad630a17c6e7e7081c30f"
}
},
"license": "MIT",
@@ -4,7 +4,7 @@
"If you want to provide a fix or improvement, please create a pull request against the original repository.",
"Once accepted there, we are happy to receive an update request."
],
"version": "https://github.com/Microsoft/TypeScript-TmLanguage/commit/a42e5cbe14945ccc0493f62b1e2d63eddcdaa6f6",
"version": "https://github.com/Microsoft/TypeScript-TmLanguage/commit/06d49b5ea993412a21aad630a17c6e7e7081c30f",
"name": "TypeScript",
"scopeName": "source.ts",
"patterns": [
@@ -4445,7 +4445,7 @@
"patterns": [
{
"name": "string.regexp.ts",
"begin": "(?<!\\+\\+|--|})(?<=[=(:,\\[?+!]|^return|[^\\._$[:alnum:]]return|^case|[^\\._$[:alnum:]]case|=>|&&|\\|\\||\\*\\/)\\s*(\\/)(?![\\/*])(?=(?:[^\\/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"begin": "(?<!\\+\\+|--|})(?<=[=(:,\\[?+!]|^return|[^\\._$[:alnum:]]return|^case|[^\\._$[:alnum:]]case|=>|&&|\\|\\||\\*\\/)\\s*(\\/)(?![\\/*])(?=(?:[^\\/\\\\\\[\\()]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\]|\\(([^\\)\\\\]|\\\\.)+\\))+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"beginCaptures": {
"1": {
"name": "punctuation.definition.string.begin.ts"
@@ -4468,7 +4468,7 @@
},
{
"name": "string.regexp.ts",
"begin": "(?<![_$[:alnum:])\\]]|\\+\\+|--|})\\/(?![\\/*])(?=(?:[^\\/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"begin": "(?<![_$[:alnum:])\\]]|\\+\\+|--|}|\\*\\/)\\/(?![\\/*])(?=(?:[^\\/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.ts"
@@ -4,7 +4,7 @@
"If you want to provide a fix or improvement, please create a pull request against the original repository.",
"Once accepted there, we are happy to receive an update request."
],
"version": "https://github.com/Microsoft/TypeScript-TmLanguage/commit/a42e5cbe14945ccc0493f62b1e2d63eddcdaa6f6",
"version": "https://github.com/Microsoft/TypeScript-TmLanguage/commit/06d49b5ea993412a21aad630a17c6e7e7081c30f",
"name": "TypeScriptReact",
"scopeName": "source.tsx",
"patterns": [
@@ -4396,7 +4396,7 @@
"patterns": [
{
"name": "string.regexp.tsx",
"begin": "(?<!\\+\\+|--|})(?<=[=(:,\\[?+!]|^return|[^\\._$[:alnum:]]return|^case|[^\\._$[:alnum:]]case|=>|&&|\\|\\||\\*\\/)\\s*(\\/)(?![\\/*])(?=(?:[^\\/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"begin": "(?<!\\+\\+|--|})(?<=[=(:,\\[?+!]|^return|[^\\._$[:alnum:]]return|^case|[^\\._$[:alnum:]]case|=>|&&|\\|\\||\\*\\/)\\s*(\\/)(?![\\/*])(?=(?:[^\\/\\\\\\[\\()]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\]|\\(([^\\)\\\\]|\\\\.)+\\))+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"beginCaptures": {
"1": {
"name": "punctuation.definition.string.begin.tsx"
@@ -4419,7 +4419,7 @@
},
{
"name": "string.regexp.tsx",
"begin": "(?<![_$[:alnum:])\\]]|\\+\\+|--|})\\/(?![\\/*])(?=(?:[^\\/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"begin": "(?<![_$[:alnum:])\\]]|\\+\\+|--|}|\\*\\/)\\/(?![\\/*])(?=(?:[^\\/\\\\\\[]|\\\\.|\\[([^\\]\\\\]|\\\\.)+\\])+\\/[gimsuy]*(?!\\s*[a-zA-Z0-9_$]))",
"beginCaptures": {
"0": {
"name": "punctuation.definition.string.begin.tsx"
@@ -358,13 +358,6 @@
"description": "%format.placeOpenBraceOnNewLineForControlBlocks%",
"scope": "resource"
},
"jsDocCompletion.enabled": {
"type": "boolean",
"default": true,
"description": "%jsDocCompletion.enabled%",
"deprecationMessage": "%jsDocCompletion.deprecationMessage%",
"scope": "resource"
},
"javascript.implicitProjectConfig.checkJs": {
"type": "boolean",
"default": false,
@@ -525,6 +518,18 @@
"description": "%typescript.preferences.importModuleSpecifier%",
"scope": "resource"
},
"javascript.preferences.renameShorthandProperties": {
"type": "boolean",
"default": true,
"description": "%typescript.preferences.renameShorthandProperties%",
"scope": "resource"
},
"typescript.preferences.renameShorthandProperties": {
"type": "boolean",
"default": true,
"description": "%typescript.preferences.renameShorthandProperties%",
"scope": "resource"
},
"typescript.updateImportsOnFileMove.enabled": {
"type": "string",
"enum": [
@@ -37,8 +37,6 @@
"typescript.restartTsServer": "Restart TS server.",
"typescript.selectTypeScriptVersion.title": "Select TypeScript Version.",
"typescript.reportStyleChecksAsWarnings": "Report style checks as warnings.",
"jsDocCompletion.enabled": "Enable/disable auto JSDoc comments.",
"jsDocCompletion.deprecationMessage": "This setting has renamed to `javascript.suggest.completeJSDocs` and `typescript.suggest.completeJSDocs` and will be removed.",
"javascript.implicitProjectConfig.checkJs": "Enable/disable semantic checking of JavaScript files. Existing jsconfig.json or tsconfig.json files override this setting. Requires using TypeScript 2.3.1 or newer in the workspace.",
"typescript.npm": "Specifies the path to the NPM executable used for Automatic Type Acquisition. Requires using TypeScript 2.3.4 or newer in the workspace.",
"typescript.check.npmIsInstalled": "Check if NPM is installed for Automatic Type Acquisition.",
@@ -69,5 +67,6 @@
"typescript.autoClosingTags": "Enable/disable automatic closing of JSX tags. Requires using TypeScript 3.0 or newer in the workspace.",
"typescript.suggest.enabled": "Enabled/disable autocomplete suggestions.",
"configuration.surveys.enabled": "Enabled/disable occasional surveys that help us improve VS Code's JavaScript and TypeScript support.",
"configuration.suggest.completeJSDocs": "Enable/disable suggestion to complete JSDoc comments."
"configuration.suggest.completeJSDocs": "Enable/disable suggestion to complete JSDoc comments.",
"typescript.preferences.renameShorthandProperties": "Enable/disable introducing aliases for object shorthand properties during renames. Requires using TypeScript 3.4 or newer in the workspace."
}
@@ -173,15 +173,15 @@ export default class FileConfigurationManager extends Disposable {
return {};
}
const preferences = vscode.workspace.getConfiguration(
const config = vscode.workspace.getConfiguration(
isTypeScriptDocument(document) ? 'typescript.preferences' : 'javascript.preferences',
document.uri);
return {
quotePreference: this.getQuoteStylePreference(preferences),
importModuleSpecifierPreference: getImportModuleSpecifierPreference(preferences),
quotePreference: this.getQuoteStylePreference(config),
importModuleSpecifierPreference: getImportModuleSpecifierPreference(config),
allowTextChangesInNewFiles: document.uri.scheme === 'file',
providePrefixAndSuffixTextForRename: true,
providePrefixAndSuffixTextForRename: config.get<boolean>('renameShorthandProperties', true),
allowRenameOfImportPath: true,
};
}
@@ -27,11 +27,57 @@ import { RequestItem, RequestQueue, RequestQueueingType } from './requestQueue';
class TypeScriptServerError extends Error {
public static create(
version: TypeScriptVersion,
response: Proto.Response,
): TypeScriptServerError {
const parsedResult = TypeScriptServerError.parseErrorText(version, response);
return new TypeScriptServerError(version, response,
parsedResult ? parsedResult.message : undefined,
parsedResult ? parsedResult.stack : undefined);
}
constructor(
version: TypeScriptVersion,
public readonly response: Proto.Response,
private readonly response: Proto.Response,
public readonly serverMessage: string | undefined,
public readonly serverStack: string | undefined,
) {
super(`TypeScript Server Error (${version.versionString})\n${TypeScriptServerError.normalizeMessageStack(version, response.message)}`);
super(`TypeScript Server Error (${version.versionString})\n${serverMessage}\n${serverStack}`);
}
public get serverErrorText() {
return this.response.message;
}
public get serverCommand() {
return this.response.command;
}
/**
* Given a `errorText` from a tsserver request indicating failure in handling a request,
* prepares a payload for telemetry-logging.
*/
private static parseErrorText(
version: TypeScriptVersion,
response: Proto.Response,
) {
const errorText = response.message;
if (errorText) {
const errorPrefix = 'Error processing request. ';
if (errorText.startsWith(errorPrefix)) {
const prefixFreeErrorText = errorText.substr(errorPrefix.length);
const newlineIndex = prefixFreeErrorText.indexOf('\n');
if (newlineIndex >= 0) {
// Newline expected between message and stack.
return {
message: prefixFreeErrorText.substring(0, newlineIndex),
stack: TypeScriptServerError.normalizeMessageStack(version, prefixFreeErrorText.substring(newlineIndex + 1))
};
}
}
}
return undefined;
}
/**
@@ -42,7 +88,7 @@ class TypeScriptServerError extends Error {
message: string | undefined,
) {
if (!message) {
return message;
return '';
}
return message.replace(new RegExp(`${escapeRegExp(version.path)}[/\\\\]tsserver.js:`, 'gi'), 'tsserver.js:');
}
@@ -317,7 +363,7 @@ export class TypeScriptServer extends Disposable {
// Special case where response itself is successful but there is not any data to return.
callback.onSuccess(ServerResponse.NoContent);
} else {
callback.onError(new TypeScriptServerError(this._version, response));
callback.onError(TypeScriptServerError.create(this._version, response));
}
}
@@ -344,7 +390,6 @@ export class TypeScriptServer extends Disposable {
}).catch((err: Error) => {
if (err instanceof TypeScriptServerError) {
if (!executeInfo.token || !executeInfo.token.isCancellationRequested) {
const properties = this.parseErrorText(err.response.message, err.response.command);
/* __GDPR__
"languageServiceErrorResponse" : {
"command" : { "classification": "SystemMetaData", "purpose": "FeatureInsight" },
@@ -356,7 +401,12 @@ export class TypeScriptServer extends Disposable {
]
}
*/
this._telemetryReporter.logTelemetry('languageServiceErrorResponse', properties);
this._telemetryReporter.logTelemetry('languageServiceErrorResponse', {
command: err.serverCommand,
message: err.serverMessage || '',
stack: err.serverStack || '',
errortext: err.serverErrorText || '',
});
}
}
@@ -370,30 +420,6 @@ export class TypeScriptServer extends Disposable {
return result;
}
/**
* Given a `errorText` from a tsserver request indicating failure in handling a request,
* prepares a payload for telemetry-logging.
*/
private parseErrorText(errorText: string | undefined, command: string) {
const properties: ObjectMap<string> = Object.create(null);
properties['command'] = command;
if (errorText) {
properties['errorText'] = errorText;
const errorPrefix = 'Error processing request. ';
if (errorText.startsWith(errorPrefix)) {
const prefixFreeErrorText = errorText.substr(errorPrefix.length);
const newlineIndex = prefixFreeErrorText.indexOf('\n');
if (newlineIndex >= 0) {
// Newline expected between message and stack.
properties['message'] = prefixFreeErrorText.substring(0, newlineIndex);
properties['stack'] = prefixFreeErrorText.substring(newlineIndex + 1);
}
}
}
return properties;
}
private sendNextRequests(): void {
while (this._pendingResponses.size === 0 && this._requestQueue.length > 0) {
const item = this._requestQueue.dequeue();
@@ -166,6 +166,10 @@ export default class TypeScriptServiceClient extends Disposable implements IType
this._register(this.pluginManager.onDidUpdateConfig(update => {
this.configurePlugin(update.pluginId, update.config);
}));
this._register(this.pluginManager.onDidChangePlugins(() => {
this.restartTsServer();
}));
}
public get configuration() {
@@ -4,8 +4,8 @@
*--------------------------------------------------------------------------------------------*/
import * as vscode from 'vscode';
import * as arrays from './arrays';
import { Disposable } from './dispose';
import { memoize } from './memoize';
export interface TypeScriptServerPlugin {
readonly path: string;
@@ -14,28 +14,45 @@ export interface TypeScriptServerPlugin {
readonly languages: ReadonlyArray<string>;
}
namespace TypeScriptServerPlugin {
export function equals(a: TypeScriptServerPlugin, b: TypeScriptServerPlugin): boolean {
return a.path === b.path
&& a.name === b.name
&& a.enableForWorkspaceTypeScriptVersions === b.enableForWorkspaceTypeScriptVersions
&& arrays.equals(a.languages, b.languages);
}
}
export class PluginManager extends Disposable {
private readonly _pluginConfigurations = new Map<string, {}>();
@memoize
public get plugins(): ReadonlyArray<TypeScriptServerPlugin> {
const plugins: TypeScriptServerPlugin[] = [];
for (const extension of vscode.extensions.all) {
const pack = extension.packageJSON;
if (pack.contributes && Array.isArray(pack.contributes.typescriptServerPlugins)) {
for (const plugin of pack.contributes.typescriptServerPlugins) {
plugins.push({
name: plugin.name,
enableForWorkspaceTypeScriptVersions: !!plugin.enableForWorkspaceTypeScriptVersions,
path: extension.extensionPath,
languages: Array.isArray(plugin.languages) ? plugin.languages : [],
});
}
private _plugins: Map<string, ReadonlyArray<TypeScriptServerPlugin>> | undefined;
constructor() {
super();
vscode.extensions.onDidChange(() => {
if (!this._plugins) {
return;
}
}
return plugins;
const newPlugins = this.readPlugins();
if (!arrays.equals(arrays.flatten(Array.from(this._plugins.values())), arrays.flatten(Array.from(newPlugins.values())), TypeScriptServerPlugin.equals)) {
this._plugins = newPlugins;
this._onDidUpdatePlugins.fire(this);
}
}, undefined, this._disposables);
}
public get plugins(): ReadonlyArray<TypeScriptServerPlugin> {
if (!this._plugins) {
this._plugins = this.readPlugins();
}
return arrays.flatten(Array.from(this._plugins.values()));
}
private readonly _onDidUpdatePlugins = this._register(new vscode.EventEmitter<this>());
public readonly onDidChangePlugins = this._onDidUpdatePlugins.event;
private readonly _onDidUpdateConfig = this._register(new vscode.EventEmitter<{ pluginId: string, config: {} }>());
public readonly onDidUpdateConfig = this._onDidUpdateConfig.event;
@@ -47,4 +64,26 @@ export class PluginManager extends Disposable {
public configurations(): IterableIterator<[string, {}]> {
return this._pluginConfigurations.entries();
}
private readPlugins() {
const pluginMap = new Map<string, ReadonlyArray<TypeScriptServerPlugin>>();
for (const extension of vscode.extensions.all) {
const pack = extension.packageJSON;
if (pack.contributes && Array.isArray(pack.contributes.typescriptServerPlugins)) {
const plugins: TypeScriptServerPlugin[] = [];
for (const plugin of pack.contributes.typescriptServerPlugins) {
plugins.push({
name: plugin.name,
enableForWorkspaceTypeScriptVersions: !!plugin.enableForWorkspaceTypeScriptVersions,
path: extension.extensionPath,
languages: Array.isArray(plugin.languages) ? plugin.languages : [],
});
}
if (plugins.length) {
pluginMap.set(extension.id, plugins);
}
}
}
return pluginMap;
}
}
@@ -10,6 +10,18 @@ import { createRandomFile } from '../utils';
suite('languages namespace tests', () => {
function positionToString(p: vscode.Position) {
return `[${p.character}/${p.line}]`;
}
function rangeToString(r: vscode.Range) {
return `[${positionToString(r.start)}/${positionToString(r.end)}]`;
}
function assertEqualRange(actual: vscode.Range, expected: vscode.Range, message?: string) {
assert.equal(rangeToString(actual), rangeToString(expected), message);
}
test('setTextDocumentLanguage -> close/open event', async function () {
const file = await createRandomFile('foo\nbar\nbar');
const doc = await vscode.workspace.openTextDocument(file);
@@ -77,6 +89,31 @@ suite('languages namespace tests', () => {
assert.ok(found);
});
test('link detector', async function () {
const uri = await createRandomFile('class A { // http://a.com }', undefined, '.java');
const doc = await vscode.workspace.openTextDocument(uri);
const target = vscode.Uri.parse('file://foo/bar');
const range = new vscode.Range(new vscode.Position(0, 0), new vscode.Position(0, 5));
const linkProvider: vscode.DocumentLinkProvider = {
provideDocumentLinks: _doc => {
return [new vscode.DocumentLink(range, target)];
}
};
vscode.languages.registerDocumentLinkProvider({ language: 'java', scheme: 'file' }, linkProvider);
const links = await vscode.commands.executeCommand<vscode.DocumentLink[]>('vscode.executeLinkProvider', doc.uri);
assert.equal(2, links && links.length);
let [link1, link2] = links!.sort((l1, l2) => l1.range.start.compareTo(l2.range.start));
assert.equal(target.toString(), link1.target && link1.target.toString());
assertEqualRange(range, link1.range);
assert.equal('http://a.com/', link2.target && link2.target.toString());
assertEqualRange(new vscode.Range(new vscode.Position(0, 13), new vscode.Position(0, 25)), link2.range);
});
test('diagnostics & CodeActionProvider', async function () {
class D2 extends vscode.Diagnostic {
@@ -144,4 +181,5 @@ suite('languages namespace tests', () => {
assert.ok(ran);
assert.equal(result!.items[0].label, 'foo');
});
});
@@ -0,0 +1,30 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import 'mocha';
import * as assert from 'assert';
import * as vscode from 'vscode';
suite('types', () => {
test('static properties, es5 compat class', function () {
assert.ok(vscode.ThemeIcon.File instanceof vscode.ThemeIcon);
assert.ok(vscode.ThemeIcon.Folder instanceof vscode.ThemeIcon);
assert.ok(vscode.CodeActionKind.Empty instanceof vscode.CodeActionKind);
assert.ok(vscode.CodeActionKind.QuickFix instanceof vscode.CodeActionKind);
assert.ok(vscode.CodeActionKind.Refactor instanceof vscode.CodeActionKind);
assert.ok(vscode.CodeActionKind.RefactorExtract instanceof vscode.CodeActionKind);
assert.ok(vscode.CodeActionKind.RefactorInline instanceof vscode.CodeActionKind);
assert.ok(vscode.CodeActionKind.RefactorRewrite instanceof vscode.CodeActionKind);
assert.ok(vscode.CodeActionKind.Source instanceof vscode.CodeActionKind);
assert.ok(vscode.CodeActionKind.SourceOrganizeImports instanceof vscode.CodeActionKind);
assert.ok(vscode.CodeActionKind.SourceFixAll instanceof vscode.CodeActionKind);
// assert.ok(vscode.QuickInputButtons.Back instanceof vscode.QuickInputButtons); never was an instance
});
});
@@ -568,7 +568,7 @@ suite('workspace-namespace', () => {
test('applyEdit should fail when editing renamed from resource', async () => {
const resource = await createRandomFile();
const newResource = vscode.Uri.parse(resource.fsPath + '.1');
const newResource = vscode.Uri.file(resource.fsPath + '.1');
const edit = new vscode.WorkspaceEdit();
edit.renameFile(resource, newResource);
edit.insert(resource, new vscode.Position(0, 0), '');
+2 -2
View File
@@ -12,9 +12,9 @@ export function rndName() {
return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 10);
}
export function createRandomFile(contents = '', dir: string = os.tmpdir()): Thenable<vscode.Uri> {
export function createRandomFile(contents = '', dir: string = os.tmpdir(), ext = ''): Thenable<vscode.Uri> {
return new Promise((resolve, reject) => {
const tmpFile = join(dir, rndName());
const tmpFile = join(dir, rndName() + ext);
fs.writeFile(tmpFile, contents, (error) => {
if (error) {
return reject(error);
+8 -10
View File
@@ -10,26 +10,24 @@ require('events').EventEmitter.defaultMaxListeners = 100;
const gulp = require('gulp');
const util = require('./build/lib/util');
const task = require('./build/lib/task');
const path = require('path');
const compilation = require('./build/lib/compilation');
const { monacoTypecheckTask/* , monacoTypecheckWatchTask */ } = require('./build/gulpfile.editor');
const { compileExtensionsTask, watchExtensionsTask } = require('./build/gulpfile.extensions');
// Fast compile for development time
const compileClientTask = util.task.series(util.rimraf('out'), compilation.compileTask('src', 'out', false));
compileClientTask.displayName = 'compile-client';
gulp.task(compileClientTask.displayName, compileClientTask);
const compileClientTask = task.define('compile-client', task.series(util.rimraf('out'), compilation.compileTask('src', 'out', false)));
gulp.task(compileClientTask);
const watchClientTask = util.task.series(util.rimraf('out'), compilation.watchTask('out', false));
watchClientTask.displayName = 'watch-client';
gulp.task(watchClientTask.displayName, watchClientTask);
const watchClientTask = task.define('watch-client', task.series(util.rimraf('out'), compilation.watchTask('out', false)));
gulp.task(watchClientTask);
// All
const compileTask = util.task.parallel(monacoTypecheckTask, compileClientTask, compileExtensionsTask);
compileTask.displayName = 'compile';
gulp.task(compileTask.displayName, compileTask);
const compileTask = task.define('compile', task.parallel(monacoTypecheckTask, compileClientTask, compileExtensionsTask));
gulp.task(compileTask);
gulp.task('watch', util.task.parallel(/* monacoTypecheckWatchTask, */ watchClientTask, watchExtensionsTask));
gulp.task(task.define('watch', task.parallel(/* monacoTypecheckWatchTask, */ watchClientTask, watchExtensionsTask)));
// Default
gulp.task('default', compileTask);
+5 -5
View File
@@ -1,7 +1,7 @@
{
"name": "code-oss-dev",
"version": "1.32.0",
"distro": "7b752ca3a77088fd367b62bfcce2e437c99030b7",
"distro": "6f5d9db8821add003be71e726b4ef49df83a51b4",
"author": {
"name": "Microsoft Corporation"
},
@@ -28,7 +28,6 @@
},
"dependencies": {
"applicationinsights": "1.0.8",
"fast-plist": "0.1.2",
"gc-signals": "^0.0.1",
"getmac": "1.4.1",
"graceful-fs": "4.1.11",
@@ -47,13 +46,13 @@
"sudo-prompt": "8.2.0",
"v8-inspect-profiler": "^0.0.20",
"vscode-chokidar": "1.6.5",
"vscode-debugprotocol": "1.33.0",
"vscode-debugprotocol": "^1.34.0-pre.0",
"vscode-nsfw": "1.1.1",
"vscode-proxy-agent": "0.3.0",
"vscode-ripgrep": "^1.2.5",
"vscode-sqlite3": "4.0.7",
"vscode-textmate": "^4.0.1",
"vscode-xterm": "3.12.0-beta2",
"vscode-xterm": "3.12.0-beta4",
"winreg": "^1.2.4",
"yauzl": "^2.9.1",
"yazl": "^2.4.3"
@@ -82,6 +81,7 @@
"event-stream": "3.3.4",
"express": "^4.13.1",
"fancy-log": "^1.3.3",
"fast-plist": "0.1.2",
"glob": "^5.0.13",
"gulp": "^4.0.0",
"gulp-atom-electron": "^1.20.0",
@@ -133,7 +133,7 @@
"vinyl": "^2.0.0",
"vinyl-fs": "^3.0.0",
"vsce": "1.48.0",
"vscode-nls-dev": "3.2.4",
"vscode-nls-dev": "3.2.5",
"webpack": "^4.16.5",
"webpack-cli": "^3.1.0",
"webpack-stream": "^5.1.1"
+4 -4
View File
@@ -10,11 +10,11 @@ call .\scripts\test.bat --runGlob **\*.integrationTest.js %*
if %errorlevel% neq 0 exit /b %errorlevel%
:: Tests in the extension host
REM call .\scripts\code.bat %~dp0\..\extensions\vscode-api-tests\testWorkspace --extensionDevelopmentPath=%~dp0\..\extensions\vscode-api-tests --extensionTestsPath=%~dp0\..\extensions\vscode-api-tests\out\singlefolder-tests --disableExtensions --user-data-dir=%VSCODEUSERDATADIR%
REM if %errorlevel% neq 0 exit /b %errorlevel%
call .\scripts\code.bat %~dp0\..\extensions\vscode-api-tests\testWorkspace --extensionDevelopmentPath=%~dp0\..\extensions\vscode-api-tests --extensionTestsPath=%~dp0\..\extensions\vscode-api-tests\out\singlefolder-tests --disableExtensions --user-data-dir=%VSCODEUSERDATADIR%
if %errorlevel% neq 0 exit /b %errorlevel%
REM call .\scripts\code.bat %~dp0\..\extensions\vscode-api-tests\testworkspace.code-workspace --extensionDevelopmentPath=%~dp0\..\extensions\vscode-api-tests --extensionTestsPath=%~dp0\..\extensions\vscode-api-tests\out\workspace-tests --disableExtensions --user-data-dir=%VSCODEUSERDATADIR%
REM if %errorlevel% neq 0 exit /b %errorlevel%
call .\scripts\code.bat %~dp0\..\extensions\vscode-api-tests\testworkspace.code-workspace --extensionDevelopmentPath=%~dp0\..\extensions\vscode-api-tests --extensionTestsPath=%~dp0\..\extensions\vscode-api-tests\out\workspace-tests --disableExtensions --user-data-dir=%VSCODEUSERDATADIR%
if %errorlevel% neq 0 exit /b %errorlevel%
call .\scripts\code.bat %~dp0\..\extensions\vscode-colorize-tests\test --extensionDevelopmentPath=%~dp0\..\extensions\vscode-colorize-tests --extensionTestsPath=%~dp0\..\extensions\vscode-colorize-tests\out --disableExtensions --user-data-dir=%VSCODEUSERDATADIR%
if %errorlevel% neq 0 exit /b %errorlevel%
+6 -6
View File
@@ -32,6 +32,12 @@ exports.load = function (modulePaths, resultCallback, options) {
const args = parseURLQueryArgs();
const configuration = JSON.parse(args['config'] || '{}') || {};
// Apply zoom level early to avoid glitches
const zoomLevel = configuration.zoomLevel;
if (typeof zoomLevel === 'number' && zoomLevel !== 0) {
webFrame.setZoomLevel(zoomLevel);
}
// Error handler
// @ts-ignore
process.on('uncaughtException', function (error) {
@@ -51,12 +57,6 @@ exports.load = function (modulePaths, resultCallback, options) {
// Enable ASAR support
bootstrap.enableASARSupport(path.join(configuration.appRoot, 'node_modules'));
// Apply zoom level early to avoid glitches
const zoomLevel = configuration.zoomLevel;
if (typeof zoomLevel === 'number' && zoomLevel !== 0) {
webFrame.setZoomLevel(zoomLevel);
}
if (options && typeof options.canModifyDOM === 'function') {
options.canModifyDOM(configuration);
}
+9 -9
View File
@@ -57,7 +57,7 @@ registerListeners();
*/
let nlsConfiguration = undefined;
const userDefinedLocale = getUserDefinedLocale();
userDefinedLocale.then((locale) => {
userDefinedLocale.then(locale => {
if (locale && !nlsConfiguration) {
nlsConfiguration = getNLSConfiguration(locale);
}
@@ -98,7 +98,7 @@ function onReady() {
// First, we need to test a user defined locale. If it fails we try the app locale.
// If that fails we fall back to English.
nlsConfiguration.then((nlsConfig) => {
nlsConfiguration.then(nlsConfig => {
const startup = nlsConfig => {
nlsConfig._languagePackSupport = true;
@@ -129,7 +129,7 @@ function onReady() {
// See above the comment about the loader and case sensitiviness
appLocale = appLocale.toLowerCase();
getNLSConfiguration(appLocale).then((nlsConfig) => {
getNLSConfiguration(appLocale).then(nlsConfig => {
if (!nlsConfig) {
nlsConfig = { locale: appLocale, availableLanguages: {} };
}
@@ -437,7 +437,7 @@ function getUserDefinedLocale() {
}
const localeConfig = path.join(userDataPath, 'User', 'locale.json');
return bootstrap.readFile(localeConfig).then((content) => {
return bootstrap.readFile(localeConfig).then(content => {
content = stripComments(content);
try {
const value = JSON.parse(content).locale;
@@ -535,7 +535,7 @@ function getNLSConfiguration(locale) {
if (!packConfig || typeof packConfig.hash !== 'string' || !packConfig.translations || typeof (mainPack = packConfig.translations['vscode']) !== 'string') {
return defaultResult(initialLocale);
}
return exists(mainPack).then((fileExists) => {
return exists(mainPack).then(fileExists => {
if (!fileExists) {
return defaultResult(initialLocale);
}
@@ -553,7 +553,7 @@ function getNLSConfiguration(locale) {
_resolvedLanguagePackCoreLocation: coreLocation,
_corruptedFile: corruptedFile
};
return exists(corruptedFile).then((corrupted) => {
return exists(corruptedFile).then(corrupted => {
// The nls cache directory is corrupted.
let toDelete;
if (corrupted) {
@@ -562,7 +562,7 @@ function getNLSConfiguration(locale) {
toDelete = Promise.resolve(undefined);
}
return toDelete.then(() => {
return exists(coreLocation).then((fileExists) => {
return exists(coreLocation).then(fileExists => {
if (fileExists) {
// We don't wait for this. No big harm if we can't touch
touch(coreLocation).catch(() => { });
@@ -571,7 +571,7 @@ function getNLSConfiguration(locale) {
}
return mkdirp(coreLocation).then(() => {
return Promise.all([bootstrap.readFile(path.join(__dirname, 'nls.metadata.json')), bootstrap.readFile(mainPack)]);
}).then((values) => {
}).then(values => {
const metadata = JSON.parse(values[0]);
const packData = JSON.parse(values[1]).contents;
const bundles = Object.keys(metadata.bundles);
@@ -607,7 +607,7 @@ function getNLSConfiguration(locale) {
}).then(() => {
perf.mark('nlsGeneration:end');
return result;
}).catch((err) => {
}).catch(err => {
console.error('Generating translation files failed.', err);
return defaultResult(locale);
});
+7 -1
View File
@@ -4,7 +4,13 @@
"removeComments": false,
"preserveConstEnums": true,
"sourceMap": false,
"outDir": "../out"
"outDir": "../out",
"target": "es6",
"lib": [
"dom",
"es5",
"es2015.iterable"
]
},
"include": [
"./typings",
+33 -19
View File
@@ -213,7 +213,7 @@
"./vs/platform/actions/test/common/menuService.test.ts",
"./vs/platform/backup/common/backup.ts",
"./vs/platform/backup/electron-main/backupMainService.ts",
"./vs/platform/broadcast/electron-browser/broadcastService.ts",
"./vs/platform/browser/contextScopedHistoryWidget.ts",
"./vs/platform/clipboard/common/clipboardService.ts",
"./vs/platform/clipboard/electron-browser/clipboardService.ts",
"./vs/platform/commands/common/commands.ts",
@@ -235,7 +235,6 @@
"./vs/platform/contextview/browser/contextMenuService.ts",
"./vs/platform/contextview/browser/contextView.ts",
"./vs/platform/contextview/browser/contextViewService.ts",
"./vs/platform/credentials/test/node/keytar.test.ts",
"./vs/platform/diagnostics/electron-main/diagnosticsService.ts",
"./vs/platform/dialogs/common/dialogs.ts",
"./vs/platform/dialogs/node/dialogIpc.ts",
@@ -284,8 +283,6 @@
"./vs/platform/instantiation/test/common/graph.test.ts",
"./vs/platform/instantiation/test/common/instantiationService.test.ts",
"./vs/platform/instantiation/test/common/instantiationServiceMock.ts",
"./vs/platform/integrity/common/integrity.ts",
"./vs/platform/integrity/node/integrityServiceImpl.ts",
"./vs/platform/issue/common/issue.ts",
"./vs/platform/issue/electron-main/issueService.ts",
"./vs/platform/issue/node/issueIpc.ts",
@@ -320,15 +317,11 @@
"./vs/platform/menubar/electron-main/menubar.ts",
"./vs/platform/menubar/electron-main/menubarService.ts",
"./vs/platform/menubar/node/menubarIpc.ts",
"./vs/platform/node/minimalTranslations.ts",
"./vs/platform/node/package.ts",
"./vs/platform/node/product.ts",
"./vs/platform/node/test/zip.test.ts",
"./vs/platform/node/zip.ts",
"./vs/platform/notification/common/notification.ts",
"./vs/platform/notification/test/common/testNotificationService.ts",
"./vs/platform/opener/common/opener.ts",
"./vs/platform/output/node/outputAppender.ts",
"./vs/platform/progress/common/progress.ts",
"./vs/platform/quickOpen/common/quickOpen.ts",
"./vs/platform/quickinput/common/quickInput.ts",
@@ -343,10 +336,6 @@
"./vs/platform/request/electron-main/requestService.ts",
"./vs/platform/request/node/request.ts",
"./vs/platform/request/node/requestService.ts",
"./vs/platform/search/common/replace.ts",
"./vs/platform/search/common/search.ts",
"./vs/platform/search/test/common/replace.test.ts",
"./vs/platform/search/test/common/search.test.ts",
"./vs/platform/state/common/state.ts",
"./vs/platform/state/node/stateService.ts",
"./vs/platform/statusbar/common/statusbar.ts",
@@ -381,7 +370,6 @@
"./vs/platform/url/common/urlService.ts",
"./vs/platform/url/electron-main/electronUrlListener.ts",
"./vs/platform/url/node/urlIpc.ts",
"./vs/platform/browser/contextScopedHistoryWidget.ts",
"./vs/platform/windows/common/windows.ts",
"./vs/platform/windows/electron-browser/windowService.ts",
"./vs/platform/windows/electron-main/windows.ts",
@@ -392,18 +380,19 @@
"./vs/platform/workspace/test/common/workspace.test.ts",
"./vs/platform/workspaces/common/workspaces.ts",
"./vs/platform/workspaces/electron-main/workspacesMainService.ts",
"./vs/platform/workspaces/node/workspaces.ts",
"./vs/platform/workspaces/node/workspacesIpc.ts",
"./vs/vscode.d.ts",
"./vs/vscode.proposed.d.ts",
"./vs/workbench/api/common/configurationExtensionPoint.ts",
"./vs/workbench/api/common/menusExtensionPoint.ts",
"./vs/workbench/api/common/jsonValidationExtensionPoint.ts",
"./vs/workbench/api/common/menusExtensionPoint.ts",
"./vs/workbench/api/electron-browser/extHostCustomers.ts",
"./vs/workbench/api/electron-browser/mainThreadClipboard.ts",
"./vs/workbench/api/electron-browser/mainThreadCommands.ts",
"./vs/workbench/api/electron-browser/mainThreadConfiguration.ts",
"./vs/workbench/api/electron-browser/mainThreadConsole.ts",
"./vs/workbench/api/electron-browser/mainThreadDebugService.ts",
"./vs/workbench/api/electron-browser/mainThreadDecorations.ts",
"./vs/workbench/api/electron-browser/mainThreadDiagnostics.ts",
"./vs/workbench/api/electron-browser/mainThreadDialogs.ts",
"./vs/workbench/api/electron-browser/mainThreadDocumentContentProviders.ts",
@@ -414,6 +403,7 @@
"./vs/workbench/api/electron-browser/mainThreadLanguages.ts",
"./vs/workbench/api/electron-browser/mainThreadLogService.ts",
"./vs/workbench/api/electron-browser/mainThreadMessageService.ts",
"./vs/workbench/api/electron-browser/mainThreadOutputService.ts",
"./vs/workbench/api/electron-browser/mainThreadProgress.ts",
"./vs/workbench/api/electron-browser/mainThreadQuickOpen.ts",
"./vs/workbench/api/electron-browser/mainThreadSCM.ts",
@@ -421,6 +411,8 @@
"./vs/workbench/api/electron-browser/mainThreadStatusBar.ts",
"./vs/workbench/api/electron-browser/mainThreadStorage.ts",
"./vs/workbench/api/electron-browser/mainThreadTelemetry.ts",
"./vs/workbench/api/electron-browser/mainThreadTerminalService.ts",
"./vs/workbench/api/electron-browser/mainThreadTreeViews.ts",
"./vs/workbench/api/electron-browser/mainThreadUrls.ts",
"./vs/workbench/api/electron-browser/mainThreadWindow.ts",
"./vs/workbench/api/electron-browser/mainThreadWorkspace.ts",
@@ -435,10 +427,12 @@
"./vs/workbench/api/node/extHostMessageService.ts",
"./vs/workbench/api/node/extHostOutputService.ts",
"./vs/workbench/api/node/extHostSearch.fileIndex.ts",
"./vs/workbench/api/node/extHostSearch.ts",
"./vs/workbench/api/node/extHostStorage.ts",
"./vs/workbench/api/node/extHostTypes.ts",
"./vs/workbench/api/node/extHostUrls.ts",
"./vs/workbench/api/node/extHostWindow.ts",
"./vs/workbench/api/node/extHostWorkspace.ts",
"./vs/workbench/api/shared/editor.ts",
"./vs/workbench/api/shared/tasks.ts",
"./vs/workbench/browser/actions.ts",
@@ -467,6 +461,8 @@
"./vs/workbench/browser/parts/quickinput/quickInputBox.ts",
"./vs/workbench/browser/parts/quickinput/quickInputList.ts",
"./vs/workbench/browser/parts/quickinput/quickInputUtils.ts",
"./vs/workbench/browser/parts/quickopen/quickOpenActions.ts",
"./vs/workbench/browser/parts/quickopen/quickOpenController.ts",
"./vs/workbench/browser/parts/quickopen/quickopen.ts",
"./vs/workbench/browser/parts/sidebar/sidebarPart.ts",
"./vs/workbench/browser/parts/statusbar/statusbar.ts",
@@ -475,6 +471,7 @@
"./vs/workbench/browser/parts/views/views.ts",
"./vs/workbench/browser/parts/views/viewsViewlet.ts",
"./vs/workbench/browser/quickopen.ts",
"./vs/workbench/browser/style.ts",
"./vs/workbench/browser/viewlet.ts",
"./vs/workbench/browser/workbench.contribution.ts",
"./vs/workbench/common/actions.ts",
@@ -496,12 +493,12 @@
"./vs/workbench/common/views.ts",
"./vs/workbench/contrib/backup/common/backupRestorer.ts",
"./vs/workbench/contrib/cli/electron-browser/cli.contribution.ts",
"./vs/workbench/contrib/codeEditor/browser/largeFileOptimizations.ts",
"./vs/workbench/contrib/codeEditor/browser/menuPreventer.ts",
"./vs/workbench/contrib/codeEditor/browser/simpleEditorOptions.ts",
"./vs/workbench/contrib/codeEditor/electron-browser/accessibility.ts",
"./vs/workbench/contrib/codeEditor/electron-browser/inspectKeybindings.ts",
"./vs/workbench/contrib/codeEditor/electron-browser/languageConfiguration/languageConfigurationExtensionPoint.ts",
"./vs/workbench/contrib/codeEditor/electron-browser/largeFileOptimizations.ts",
"./vs/workbench/contrib/codeEditor/electron-browser/selectionClipboard.ts",
"./vs/workbench/contrib/codeEditor/electron-browser/simpleEditorOptions.ts",
"./vs/workbench/contrib/codeEditor/electron-browser/sleepResumeRepaintMinimap.ts",
@@ -512,9 +509,11 @@
"./vs/workbench/contrib/codeEditor/electron-browser/toggleRenderControlCharacter.ts",
"./vs/workbench/contrib/codeEditor/electron-browser/toggleRenderWhitespace.ts",
"./vs/workbench/contrib/codeEditor/electron-browser/toggleWordWrap.ts",
"./vs/workbench/contrib/codeinset/common/codeInset.ts",
"./vs/workbench/contrib/comments/common/commentModel.ts",
"./vs/workbench/contrib/comments/electron-browser/commentGlyphWidget.ts",
"./vs/workbench/contrib/comments/electron-browser/commentService.ts",
"./vs/workbench/contrib/comments/electron-browser/reactionsAction.ts",
"./vs/workbench/contrib/comments/electron-browser/simpleCommentEditor.ts",
"./vs/workbench/contrib/debug/browser/debugANSIHandling.ts",
"./vs/workbench/contrib/debug/browser/debugActionItems.ts",
@@ -547,7 +546,9 @@
"./vs/workbench/contrib/extensions/electron-browser/extensionTipsService.ts",
"./vs/workbench/contrib/extensions/electron-browser/extensionsActions.ts",
"./vs/workbench/contrib/extensions/electron-browser/extensionsActivationProgress.ts",
"./vs/workbench/contrib/extensions/electron-browser/extensionsList.ts",
"./vs/workbench/contrib/extensions/electron-browser/extensionsUtils.ts",
"./vs/workbench/contrib/extensions/electron-browser/extensionsWidgets.ts",
"./vs/workbench/contrib/extensions/node/extensionsWorkbenchService.ts",
"./vs/workbench/contrib/extensions/test/common/extensionQuery.test.ts",
"./vs/workbench/contrib/feedback/electron-browser/feedback.contribution.ts",
@@ -558,8 +559,10 @@
"./vs/workbench/contrib/files/common/files.ts",
"./vs/workbench/contrib/files/electron-browser/explorerService.ts",
"./vs/workbench/contrib/files/electron-browser/views/explorerDecorationsProvider.ts",
"./vs/workbench/contrib/format/browser/format.contribution.ts",
"./vs/workbench/contrib/localizations/electron-browser/localizations.contribution.ts",
"./vs/workbench/contrib/localizations/electron-browser/localizationsActions.ts",
"./vs/workbench/contrib/localizations/electron-browser/minimalTranslations.ts",
"./vs/workbench/contrib/logs/common/logConstants.ts",
"./vs/workbench/contrib/logs/electron-browser/logs.contribution.ts",
"./vs/workbench/contrib/logs/electron-browser/logsActions.ts",
@@ -574,6 +577,7 @@
"./vs/workbench/contrib/output/common/output.ts",
"./vs/workbench/contrib/output/common/outputLinkComputer.ts",
"./vs/workbench/contrib/output/common/outputLinkProvider.ts",
"./vs/workbench/contrib/output/node/outputAppender.ts",
"./vs/workbench/contrib/performance/electron-browser/startupTimings.ts",
"./vs/workbench/contrib/preferences/browser/settingsWidgets.ts",
"./vs/workbench/contrib/preferences/common/smartSnippetInserter.ts",
@@ -641,6 +645,7 @@
"./vs/workbench/contrib/terminal/common/terminalCommands.ts",
"./vs/workbench/contrib/terminal/common/terminalMenu.ts",
"./vs/workbench/contrib/terminal/common/terminalService.ts",
"./vs/workbench/contrib/terminal/electron-browser/terminalActions.ts",
"./vs/workbench/contrib/terminal/electron-browser/terminalConfigHelper.ts",
"./vs/workbench/contrib/terminal/electron-browser/terminalInstance.ts",
"./vs/workbench/contrib/terminal/electron-browser/terminalLinkHandler.ts",
@@ -657,13 +662,14 @@
"./vs/workbench/contrib/terminal/test/node/terminalCommandTracker.test.ts",
"./vs/workbench/contrib/terminal/test/node/terminalEnvironment.test.ts",
"./vs/workbench/contrib/themes/electron-browser/themes.contribution.ts",
"./vs/workbench/contrib/themes/test/electron-browser/themes.test.contribution.ts",
"./vs/workbench/contrib/url/electron-browser/url.contribution.ts",
"./vs/workbench/contrib/webview/electron-browser/webviewProtocols.ts",
"./vs/workbench/electron-browser/resources.ts",
"./vs/workbench/electron-browser/window.ts",
"./vs/workbench/services/activity/common/activity.ts",
"./vs/workbench/services/backup/common/backup.ts",
"./vs/workbench/services/backup/node/backupFileService.ts",
"./vs/workbench/services/broadcast/electron-browser/broadcastService.ts",
"./vs/workbench/services/bulkEdit/electron-browser/bulkEditService.ts",
"./vs/workbench/services/configuration/common/configuration.ts",
"./vs/workbench/services/configuration/common/configurationModels.ts",
@@ -702,8 +708,10 @@
"./vs/workbench/services/files/test/electron-browser/watcher.test.ts",
"./vs/workbench/services/hash/common/hashService.ts",
"./vs/workbench/services/hash/node/hashService.ts",
"./vs/workbench/services/history/browser/history.ts",
"./vs/workbench/services/history/common/history.ts",
"./vs/workbench/services/history/electron-browser/history.ts",
"./vs/workbench/services/integrity/common/integrity.ts",
"./vs/workbench/services/integrity/node/integrityServiceImpl.ts",
"./vs/workbench/services/keybinding/common/keybindingIO.ts",
"./vs/workbench/services/keybinding/common/keyboardMapper.ts",
"./vs/workbench/services/keybinding/common/macLinuxFallbackKeyboardMapper.ts",
@@ -727,7 +735,10 @@
"./vs/workbench/services/remote/electron-browser/remoteAgentServiceImpl.ts",
"./vs/workbench/services/remote/node/remoteAgentEnvironmentChannel.ts",
"./vs/workbench/services/remote/node/remoteAgentService.ts",
"./vs/workbench/services/search/common/replace.ts",
"./vs/workbench/services/search/common/search.ts",
"./vs/workbench/services/search/common/searchHelpers.ts",
"./vs/workbench/services/search/common/searchHistoryService.ts",
"./vs/workbench/services/search/node/fileSearch.ts",
"./vs/workbench/services/search/node/fileSearchManager.ts",
"./vs/workbench/services/search/node/rawSearchService.ts",
@@ -737,10 +748,11 @@
"./vs/workbench/services/search/node/ripgrepTextSearchEngine.ts",
"./vs/workbench/services/search/node/search.ts",
"./vs/workbench/services/search/node/searchApp.ts",
"./vs/workbench/services/search/node/searchHistoryService.ts",
"./vs/workbench/services/search/node/searchIpc.ts",
"./vs/workbench/services/search/node/textSearchAdapter.ts",
"./vs/workbench/services/search/node/textSearchManager.ts",
"./vs/workbench/services/search/test/common/replace.test.ts",
"./vs/workbench/services/search/test/common/search.test.ts",
"./vs/workbench/services/search/test/common/searchHelpers.test.ts",
"./vs/workbench/services/search/test/node/ripgrepFileSearch.test.ts",
"./vs/workbench/services/search/test/node/ripgrepTextSearchEngine.test.ts",
@@ -761,9 +773,11 @@
"./vs/workbench/test/browser/viewlet.test.ts",
"./vs/workbench/test/common/editor/editorOptions.test.ts",
"./vs/workbench/test/common/notifications.test.ts",
"./vs/workbench/test/electron-browser/api/extHost.api.impl.test.ts",
"./vs/workbench/test/electron-browser/api/extHostDocumentData.test.ts",
"./vs/workbench/test/electron-browser/api/extHostMessagerService.test.ts",
"./vs/workbench/test/electron-browser/api/extHostTypes.test.ts",
"./vs/workbench/test/electron-browser/api/extHostWorkspace.test.ts",
"./vs/workbench/test/electron-browser/api/mainThreadCommands.test.ts",
"./vs/workbench/test/electron-browser/api/mainThreadDiagnostics.test.ts",
"./vs/workbench/test/electron-browser/api/mainThreadDocumentContentProviders.test.ts",
-7
View File
@@ -1,7 +0,0 @@
declare module "fast-plist" {
/**
* A very fast plist parser
*/
export function parse(content: string): any;
}
+3 -3
View File
@@ -59,7 +59,7 @@ interface SetConstructor {
declare var Set: SetConstructor;
interface WeakMap<K, V> {
interface WeakMap<K extends object, V> {
delete(key: K): boolean;
get(key: K): V | undefined;
has(key: K): boolean;
@@ -70,9 +70,9 @@ interface WeakMap<K, V> {
interface WeakMapConstructor {
new(): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
new <K extends object, V>(): WeakMap<K, V>;
// new <K, V>(entries?: [K, V][]): WeakMap<K, V>;
readonly prototype: WeakMap<any, any>;
readonly prototype: WeakMap<object, any>;
}
declare var WeakMap: WeakMapConstructor;
+23
View File
@@ -0,0 +1,23 @@
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/////////////////////////////
/// WorkerGlobalScope APIs
/////////////////////////////
// These are only available in a Web Worker
declare function importScripts(...urls: string[]): void;
+1 -1
View File
@@ -71,7 +71,7 @@ export const DataTransfers = {
TEXT: 'text/plain'
};
export function applyDragImage(event: DragEvent, label: string, clazz: string): void {
export function applyDragImage(event: DragEvent, label: string | null, clazz: string): void {
const dragImage = document.createElement('div');
dragImage.className = clazz;
dragImage.textContent = label;
@@ -200,8 +200,8 @@ export class BreadcrumbsWidget {
return this._items[this._focusedItemIdx];
}
setFocused(item: BreadcrumbsItem, payload?: any): void {
this._focus(this._items.indexOf(item), payload);
setFocused(item: BreadcrumbsItem | undefined, payload?: any): void {
this._focus(this._items.indexOf(item!), payload);
}
focusPrev(payload?: any): any {
@@ -256,8 +256,8 @@ export class BreadcrumbsWidget {
return this._items[this._selectedItemIdx];
}
setSelection(item: BreadcrumbsItem, payload?: any): void {
this._select(this._items.indexOf(item), payload);
setSelection(item: BreadcrumbsItem | undefined, payload?: any): void {
this._select(this._items.indexOf(item!), payload);
}
private _select(nth: number, payload: any): void {
@@ -358,6 +358,10 @@ export class FindInput extends Widget {
this._onCaseSensitiveKeyDown.fire(e);
}));
if (this._showOptionButtons) {
this.inputBox.inputElement.style.paddingRight = (this.caseSensitive.width() + this.wholeWords.width() + this.regex.width()) + 'px';
}
// Arrow-Key support to navigate between options
let indexes = [this.caseSensitive.domNode, this.wholeWords.domNode, this.regex.domNode];
this.onkeydown(this.domNode, (event: IKeyboardEvent) => {
@@ -33,7 +33,7 @@ export interface KeybindingLabelOptions {
export class KeybindingLabel {
private domNode: HTMLElement;
private keybinding: ResolvedKeybinding;
private keybinding: ResolvedKeybinding | undefined;
private matches: Matches | undefined;
private didEverRender: boolean;
@@ -47,7 +47,7 @@ export class KeybindingLabel {
return this.domNode;
}
set(keybinding: ResolvedKeybinding, matches?: Matches) {
set(keybinding: ResolvedKeybinding | undefined, matches?: Matches) {
if (this.didEverRender && this.keybinding === keybinding && KeybindingLabel.areSame(this.matches, matches)) {
return;
}
+25 -11
View File
@@ -41,6 +41,11 @@ export interface IListViewDragAndDrop<T> extends IListDragAndDrop<T> {
getDragElements(element: T): T[];
}
export interface IAriaSetProvider<T> {
getSetSize(element: T, index: number, listLength: number): number;
getPosInSet(element: T, index: number): number;
}
export interface IListViewOptions<T> {
readonly dnd?: IListViewDragAndDrop<T>;
readonly useShadows?: boolean;
@@ -49,7 +54,7 @@ export interface IListViewOptions<T> {
readonly supportDynamicHeights?: boolean;
readonly mouseSupport?: boolean;
readonly horizontalScrolling?: boolean;
readonly disableAriaRoles?: boolean;
readonly ariaSetProvider?: IAriaSetProvider<T>;
}
const DefaultOptions = {
@@ -64,8 +69,7 @@ const DefaultOptions = {
onDragOver() { return false; },
drop() { }
},
horizontalScrolling: false,
disableAriaRoles: false
horizontalScrolling: false
};
export class ElementsDragAndDropData<T> implements IDragAndDropData {
@@ -144,6 +148,9 @@ function equalsDragFeedback(f1: number[] | undefined, f2: number[] | undefined):
export class ListView<T> implements ISpliceable<T>, IDisposable {
private static InstanceCount = 0;
readonly domId = `list_id_${++ListView.InstanceCount}`;
readonly domNode: HTMLElement;
private items: IItem<T>[];
@@ -167,7 +174,7 @@ export class ListView<T> implements ISpliceable<T>, IDisposable {
private setRowLineHeight: boolean;
private supportDynamicHeights: boolean;
private horizontalScrolling: boolean;
private disableAriaRoles: boolean;
private ariaSetProvider: IAriaSetProvider<T>;
private scrollWidth: number | undefined;
private canUseTranslate3d: boolean | undefined = undefined;
@@ -198,7 +205,7 @@ export class ListView<T> implements ISpliceable<T>, IDisposable {
container: HTMLElement,
private virtualDelegate: IListVirtualDelegate<T>,
renderers: IListRenderer<any /* TODO@joao */, any>[],
options: IListViewOptions<T> = DefaultOptions
options: IListViewOptions<T> = DefaultOptions as IListViewOptions<T>
) {
if (options.horizontalScrolling && options.supportDynamicHeights) {
throw new Error('Horizontal scrolling and dynamic heights not supported simultaneously');
@@ -219,12 +226,16 @@ export class ListView<T> implements ISpliceable<T>, IDisposable {
this.domNode = document.createElement('div');
this.domNode.className = 'monaco-list';
DOM.addClass(this.domNode, this.domId);
this.domNode.tabIndex = 0;
DOM.toggleClass(this.domNode, 'mouse-support', typeof options.mouseSupport === 'boolean' ? options.mouseSupport : true);
this.horizontalScrolling = getOrDefault(options, o => o.horizontalScrolling, DefaultOptions.horizontalScrolling);
DOM.toggleClass(this.domNode, 'horizontal-scrolling', this.horizontalScrolling);
this.disableAriaRoles = getOrDefault(options, o => o.disableAriaRoles, DefaultOptions.disableAriaRoles);
this.ariaSetProvider = options.ariaSetProvider || { getSetSize: (e, i, length) => length, getPosInSet: (_, index) => index + 1 };
this.rowsContainer = document.createElement('div');
this.rowsContainer.className = 'monaco-list-rows';
@@ -533,6 +544,7 @@ export class ListView<T> implements ISpliceable<T>, IDisposable {
if (!item.row) {
item.row = this.cache.alloc(item.templateId);
item.row!.domNode!.setAttribute('role', 'treeitem');
}
if (!item.row.domNode!.parentElement) {
@@ -600,11 +612,9 @@ export class ListView<T> implements ISpliceable<T>, IDisposable {
item.row!.domNode!.setAttribute('data-index', `${index}`);
item.row!.domNode!.setAttribute('data-last-element', index === this.length - 1 ? 'true' : 'false');
if (!this.disableAriaRoles) {
item.row!.domNode!.setAttribute('aria-setsize', `${this.length}`);
item.row!.domNode!.setAttribute('aria-posinset', `${index + 1}`);
}
item.row!.domNode!.setAttribute('aria-setsize', String(this.ariaSetProvider.getSetSize(item.element, index, this.length)));
item.row!.domNode!.setAttribute('aria-posinset', String(this.ariaSetProvider.getPosInSet(item.element, index)));
item.row!.domNode!.setAttribute('id', this.getElementDomId(index));
DOM.toggleClass(item.row!.domNode!, 'drop-target', item.dropTarget);
}
@@ -1083,6 +1093,10 @@ export class ListView<T> implements ISpliceable<T>, IDisposable {
return nextToLastItem.row.domNode;
}
getElementDomId(index: number): string {
return `${this.domId}_${index}`;
}
// Dispose
dispose() {
+6 -20
View File
@@ -17,7 +17,7 @@ import { StandardKeyboardEvent, IKeyboardEvent } from 'vs/base/browser/keyboardE
import { Event, Emitter, EventBufferer } from 'vs/base/common/event';
import { domEvent } from 'vs/base/browser/event';
import { IListVirtualDelegate, IListRenderer, IListEvent, IListContextMenuEvent, IListMouseEvent, IListTouchEvent, IListGestureEvent, IIdentityProvider, IKeyboardNavigationLabelProvider, IListDragAndDrop, IListDragOverReaction, ListAriaRootRole } from './list';
import { ListView, IListViewOptions, IListViewDragAndDrop } from './listView';
import { ListView, IListViewOptions, IListViewDragAndDrop, IAriaSetProvider } from './listView';
import { Color } from 'vs/base/common/color';
import { mixin } from 'vs/base/common/objects';
import { ScrollbarVisibility } from 'vs/base/common/scrollable';
@@ -179,16 +179,12 @@ class Trait<T> implements ISpliceable<boolean>, IDisposable {
class FocusTrait<T> extends Trait<T> {
constructor(
private getDomId: (index: number) => string
) {
constructor() {
super('focused');
}
renderIndex(index: number, container: HTMLElement): void {
super.renderIndex(index, container);
container.setAttribute('role', 'treeitem');
container.setAttribute('id', this.getDomId(index));
if (this.contains(index)) {
container.setAttribute('aria-selected', 'true');
@@ -818,7 +814,7 @@ export interface IListOptions<T> extends IListStyles {
readonly supportDynamicHeights?: boolean;
readonly mouseSupport?: boolean;
readonly horizontalScrolling?: boolean;
readonly disableAriaRoles?: boolean;
readonly ariaSetProvider?: IAriaSetProvider<T>;
}
export interface IListStyles {
@@ -1069,9 +1065,6 @@ export interface IListOptionsUpdate {
export class List<T> implements ISpliceable<T>, IDisposable {
private static InstanceCount = 0;
private idPrefix = `list_id_${++List.InstanceCount}`;
private focus: Trait<T>;
private selection: Trait<T>;
private eventBufferer = new EventBufferer();
@@ -1167,7 +1160,7 @@ export class List<T> implements ISpliceable<T>, IDisposable {
renderers: IListRenderer<any /* TODO@joao */, any>[],
private _options: IListOptions<T> = DefaultOptions
) {
this.focus = new FocusTrait(i => this.getElementDomId(i));
this.focus = new FocusTrait();
this.selection = new Trait('selected');
mixin(_options, defaultStyles, false);
@@ -1193,12 +1186,9 @@ export class List<T> implements ISpliceable<T>, IDisposable {
this.view.domNode.setAttribute('role', _options.ariaRole);
}
DOM.addClass(this.view.domNode, this.idPrefix);
this.view.domNode.tabIndex = 0;
this.styleElement = DOM.createStyleSheet(this.view.domNode);
this.styleController = _options.styleController || new DefaultStyleController(this.styleElement, this.idPrefix);
this.styleController = _options.styleController || new DefaultStyleController(this.styleElement, this.view.domId);
this.spliceable = new CombinedSpliceable([
new TraitSpliceable(this.focus, this.view, _options.identityProvider),
@@ -1528,10 +1518,6 @@ export class List<T> implements ISpliceable<T>, IDisposable {
return Math.abs((scrollTop - elementTop) / m);
}
private getElementDomId(index: number): string {
return `${this.idPrefix}_${index}`;
}
isDOMFocused(): boolean {
return this.view.domNode === document.activeElement;
}
@@ -1572,7 +1558,7 @@ export class List<T> implements ISpliceable<T>, IDisposable {
const focus = this.focus.get();
if (focus.length > 0) {
this.view.domNode.setAttribute('aria-activedescendant', this.getElementDomId(focus[0]));
this.view.domNode.setAttribute('aria-activedescendant', this.view.getElementDomId(focus[0]));
} else {
this.view.domNode.removeAttribute('aria-activedescendant');
}
+3 -5
View File
@@ -150,11 +150,9 @@ export class MenuBar extends Disposable {
this._register(DOM.addDisposableListener(this.container, DOM.EventType.FOCUS_OUT, (e) => {
let event = e as FocusEvent;
if (event.relatedTarget) {
if (!this.container.contains(event.relatedTarget as HTMLElement)) {
this.focusToReturn = undefined;
this.setUnfocusedState();
}
if (!event.relatedTarget || !this.container.contains(event.relatedTarget as HTMLElement)) {
this.focusToReturn = undefined;
this.setUnfocusedState();
}
}));
@@ -428,8 +428,6 @@ export class SelectBoxList implements ISelectBoxDelegate, IListVirtualDelegate<I
this.createSelectList(this.selectDropDownContainer);
this.setOptionsList();
this.cloneElementFont(this.selectElement, this.selectDropDownContainer);
// This allows us to flip the position based on measurement
// Set drop-down position above/below from required height and margins
// If pre-layout cannot fit at least one option do not show drop-down
@@ -709,13 +707,6 @@ export class SelectBoxList implements ISelectBoxDelegate, IListVirtualDelegate<I
return elementWidth;
}
private cloneElementFont(source: HTMLElement, target: HTMLElement) {
const fontSize = window.getComputedStyle(source, null).getPropertyValue('font-size');
const fontFamily = window.getComputedStyle(source, null).getPropertyValue('font-family');
target.style.fontFamily = fontFamily;
target.style.fontSize = fontSize;
}
private createSelectList(parent: HTMLElement): void {
// If we have already constructive list on open, skip
+12 -5
View File
@@ -151,7 +151,14 @@ function asListOptions<T, TFilterData, TRef>(modelProvider: () => ITreeModel<T,
}
},
enableKeyboardNavigation: options.simpleKeyboardNavigation,
disableAriaRoles: true
ariaSetProvider: {
getSetSize(node) {
return node.parent!.visibleChildrenCount;
},
getPosInSet(node) {
return node.visibleChildIndex + 1;
}
}
};
}
@@ -189,7 +196,7 @@ class TreeRenderer<T, TFilterData, TTemplateData> implements IListRenderer<ITree
readonly templateId: string;
private renderedElements = new Map<T, ITreeNode<T, TFilterData>>();
private renderedNodes = new Map<ITreeNode<T, TFilterData>, ITreeListTemplateData<TTemplateData>>();
private indent: number;
private indent: number = TreeRenderer.DefaultIndent;
private disposables: IDisposable[] = [];
constructor(
@@ -208,7 +215,9 @@ class TreeRenderer<T, TFilterData, TTemplateData> implements IListRenderer<ITree
}
updateOptions(options: ITreeRendererOptions = {}): void {
this.indent = typeof options.indent === 'number' ? clamp(options.indent, 0, 20) : TreeRenderer.DefaultIndent;
if (typeof options.indent !== 'undefined') {
this.indent = clamp(options.indent, 0, 40);
}
this.renderedNodes.forEach((templateData, node) => {
templateData.twistie.style.marginLeft = `${node.depth * this.indent}px`;
@@ -230,8 +239,6 @@ class TreeRenderer<T, TFilterData, TTemplateData> implements IListRenderer<ITree
const indent = TreeRenderer.DefaultIndent + (node.depth - 1) * this.indent;
templateData.twistie.style.marginLeft = `${indent}px`;
templateData.container.setAttribute('aria-posinset', String(node.visibleChildIndex + 1));
templateData.container.setAttribute('aria-setsize', String(node.parent!.visibleChildrenCount));
this.update(node, templateData);
this.renderer.renderElement(node, index, templateData.templateData);
+2 -1
View File
@@ -222,7 +222,8 @@ function asObjectTreeOptions<TInput, T, TFilterData>(options?: IAsyncDataTreeOpt
typeof options.expandOnlyOnTwistieClick !== 'function' ? options.expandOnlyOnTwistieClick : (
e => (options.expandOnlyOnTwistieClick as ((e: T) => boolean))(e.element as T)
)
)
),
ariaSetProvider: undefined
};
}
+3 -3
View File
@@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/
import * as strings from 'vs/base/common/strings';
import * as paths from 'vs/base/common/paths';
import { sep } from 'vs/base/common/path';
import { IdleValue } from 'vs/base/common/async';
let intlFileNameCollator: IdleValue<{ collator: Intl.Collator, collatorIsNumeric: boolean }>;
@@ -116,8 +116,8 @@ function comparePathComponents(one: string, other: string, caseSensitive = false
}
export function comparePaths(one: string, other: string, caseSensitive = false): number {
const oneParts = one.split(paths.nativeSep);
const otherParts = other.split(paths.nativeSep);
const oneParts = one.split(sep);
const otherParts = other.split(sep);
const lastOne = oneParts.length - 1;
const lastOther = otherParts.length - 1;
+2 -2
View File
@@ -27,8 +27,8 @@ export namespace Event {
return (listener, thisArgs = null, disposables?) => {
// we need this, in case the event fires during the listener call
let didFire = false;
const result = event(e => {
let result: IDisposable;
result = event(e => {
if (didFire) {
return;
} else if (result) {
@@ -6,81 +6,12 @@
import { isWindows } from 'vs/base/common/platform';
import { startsWithIgnoreCase, equalsIgnoreCase } from 'vs/base/common/strings';
import { CharCode } from 'vs/base/common/charCode';
/**
* The forward slash path separator.
*/
export const sep = '/';
/**
* The native path separator depending on the OS.
*/
export const nativeSep = isWindows ? '\\' : '/';
import { sep, posix } from 'vs/base/common/path';
function isPathSeparator(code: number) {
return code === CharCode.Slash || code === CharCode.Backslash;
}
/**
* @param path the path to get the dirname from
* @param separator the separator to use
* @returns the directory name of a path.
* '.' is returned for empty paths or single segment relative paths (as done by NodeJS)
* For paths consisting only of a root, the input path is returned
*/
export function dirname(path: string, separator = nativeSep): string {
const len = path.length;
if (len === 0) {
return '.';
} else if (len === 1) {
return isPathSeparator(path.charCodeAt(0)) ? path : '.';
}
const root = getRoot(path, separator);
let rootLength = root.length;
if (rootLength >= len) {
return path; // matched the root
}
if (rootLength === 0 && isPathSeparator(path.charCodeAt(0))) {
rootLength = 1; // absolute paths stay absolute paths.
}
let i = len - 1;
if (i > rootLength) {
i--; // no need to look at the last character. If it's a trailing slash, we ignore it.
while (i > rootLength && !isPathSeparator(path.charCodeAt(i))) {
i--;
}
}
if (i === 0) {
return '.'; // it was a relative path with a single segment, no root. Nodejs returns '.' here.
}
return path.substr(0, i);
}
/**
* @returns the base name of a path.
*/
export function basename(path: string): string {
const idx = ~path.lastIndexOf('/') || ~path.lastIndexOf('\\');
if (idx === 0) {
return path;
} else if (~idx === path.length - 1) {
return basename(path.substring(0, path.length - 1));
} else {
return path.substr(~idx + 1);
}
}
/**
* @returns `.far` from `boo.far` or the empty string.
*/
export function extname(path: string): string {
path = basename(path);
const idx = ~path.lastIndexOf('.');
return idx ? path.substring(~idx) : '';
}
const _posixBadPath = /(\/\.\.?\/)|(\/\.\.?)$|^(\.\.?\/)|(\/\/+)|(\\)/;
const _winBadPath = /(\\\.\.?\\)|(\\\.\.?)$|^(\.\.?\\)|(\\\\+)|(\/)/;
@@ -90,10 +21,19 @@ function _isNormal(path: string, win: boolean): boolean {
: !_posixBadPath.test(path);
}
export function normalize(path: undefined, toOSPath?: boolean): undefined;
export function normalize(path: null, toOSPath?: boolean): null;
export function normalize(path: string, toOSPath?: boolean): string;
export function normalize(path: string | null | undefined, toOSPath?: boolean): string | null | undefined {
/**
* Takes a Windows OS path and changes backward slashes to forward slashes.
* This should only be done for OS paths from Windows (or user provided paths potentially from Windows).
* Using it on a Linux or MaxOS path might change it.
*/
export function toSlashes(osPath: string) {
return osPath.replace(/[\\/]/g, '/');
}
export function normalizeWithSlashes(path: undefined): undefined;
export function normalizeWithSlashes(path: null): null;
export function normalizeWithSlashes(path: string): string;
export function normalizeWithSlashes(path: string | null | undefined): string | null | undefined {
if (path === null || path === undefined) {
return path;
@@ -104,12 +44,11 @@ export function normalize(path: string | null | undefined, toOSPath?: boolean):
return '.';
}
const wantsBackslash = !!(isWindows && toOSPath);
if (_isNormal(path, wantsBackslash)) {
if (_isNormal(path, false)) {
return path;
}
const sep = wantsBackslash ? '\\' : '/';
const sep = '/';
const root = getRoot(path, sep);
// skip the root-portion of the path
@@ -154,6 +93,30 @@ function streql(value: string, start: number, end: number, other: string): boole
return start + other.length === end && value.indexOf(other, start) === start;
}
export function joinWithSlashes(...parts: string[]): string {
let value = '';
for (let i = 0; i < parts.length; i++) {
let part = parts[i];
if (i > 0) {
// add the separater between two parts unless
// there already is one
let last = value.charCodeAt(value.length - 1);
if (!isPathSeparator(last)) {
let next = part.charCodeAt(0);
if (!isPathSeparator(next)) {
value += posix.sep;
}
}
}
value += part;
}
return normalizeWithSlashes(value);
}
// #region extpath
/**
* Computes the _root_ this path, like `getRoot('c:\files') === c:\`,
* `getRoot('files:///files/path') === files:///`,
@@ -227,33 +190,6 @@ export function getRoot(path: string, sep: string = '/'): string {
return '';
}
export const join: (...parts: string[]) => string = function () {
// Not using a function with var-args because of how TS compiles
// them to JS - it would result in 2*n runtime cost instead
// of 1*n, where n is parts.length.
let value = '';
for (let i = 0; i < arguments.length; i++) {
let part = arguments[i];
if (i > 0) {
// add the separater between two parts unless
// there already is one
let last = value.charCodeAt(value.length - 1);
if (!isPathSeparator(last)) {
let next = part.charCodeAt(0);
if (!isPathSeparator(next)) {
value += sep;
}
}
}
value += part;
}
return normalize(value);
};
/**
* Check if the path follows this pattern: `\\hostname\sharename`.
*
@@ -343,7 +279,7 @@ export function isEqual(pathA: string, pathB: string, ignoreCase?: boolean): boo
return equalsIgnoreCase(pathA, pathB);
}
export function isEqualOrParent(path: string, candidate: string, ignoreCase?: boolean, separator = nativeSep): boolean {
export function isEqualOrParent(path: string, candidate: string, ignoreCase?: boolean, separator = sep): boolean {
if (path === candidate) {
return true;
}
@@ -381,39 +317,8 @@ export function isEqualOrParent(path: string, candidate: string, ignoreCase?: bo
return path.indexOf(candidate) === 0;
}
/**
* Adapted from Node's path.isAbsolute functions
*/
export function isAbsolute(path: string): boolean {
return isWindows ?
isAbsolute_win32(path) :
isAbsolute_posix(path);
}
export function isAbsolute_win32(path: string): boolean {
if (!path) {
return false;
}
const char0 = path.charCodeAt(0);
if (isPathSeparator(char0)) {
return true;
} else if (isWindowsDriveLetter(char0)) {
if (path.length > 2 && path.charCodeAt(1) === CharCode.Colon) {
const char2 = path.charCodeAt(2);
if (isPathSeparator(char2)) {
return true;
}
}
}
return false;
}
export function isAbsolute_posix(path: string): boolean {
return !!(path && path.charCodeAt(0) === CharCode.Slash);
}
export function isWindowsDriveLetter(char0: number): boolean {
return char0 >= CharCode.A && char0 <= CharCode.Z || char0 >= CharCode.a && char0 <= CharCode.z;
}
// #endregion
+7 -7
View File
@@ -5,7 +5,8 @@
import * as arrays from 'vs/base/common/arrays';
import * as strings from 'vs/base/common/strings';
import * as paths from 'vs/base/common/paths';
import * as extpath from 'vs/base/common/extpath';
import * as paths from 'vs/base/common/path';
import { LRUCache } from 'vs/base/common/map';
import { CharCode } from 'vs/base/common/charCode';
import { isThenable } from 'vs/base/common/async';
@@ -17,7 +18,6 @@ export interface IExpression {
export interface IRelativePattern {
base: string;
pattern: string;
pathToRelative(from: string, to: string): string;
}
export function getEmptyExpression(): IExpression {
@@ -331,11 +331,11 @@ function wrapRelativePattern(parsedPattern: ParsedStringPattern, arg2: string |
}
return function (path, basename) {
if (!paths.isEqualOrParent(path, arg2.base)) {
if (!extpath.isEqualOrParent(path, arg2.base)) {
return null;
}
return parsedPattern(arg2.pathToRelative(arg2.base, path), basename);
return parsedPattern(paths.relative(arg2.base, path), basename);
};
}
@@ -396,8 +396,8 @@ function trivia3(pattern: string, options: IGlobOptions): ParsedStringPattern {
// common patterns: **/something/else just need endsWith check, something/else just needs and equals check
function trivia4and5(path: string, pattern: string, matchPathEnds: boolean): ParsedStringPattern {
const nativePath = paths.nativeSep !== paths.sep ? path.replace(ALL_FORWARD_SLASHES, paths.nativeSep) : path;
const nativePathEnd = paths.nativeSep + nativePath;
const nativePath = paths.sep !== paths.posix.sep ? path.replace(ALL_FORWARD_SLASHES, paths.sep) : path;
const nativePathEnd = paths.sep + nativePath;
const parsedPattern: ParsedStringPattern = matchPathEnds ? function (path, basename) {
return typeof path === 'string' && (path === nativePath || strings.endsWith(path, nativePathEnd)) ? pattern : null;
} : function (path, basename) {
@@ -515,7 +515,7 @@ function listToMap(list: string[]) {
export function isRelativePattern(obj: any): obj is IRelativePattern {
const rp = obj as IRelativePattern;
return rp && typeof rp.base === 'string' && typeof rp.pattern === 'string' && typeof rp.pathToRelative === 'function';
return rp && typeof rp.base === 'string' && typeof rp.pattern === 'string';
}
/**
+46 -29
View File
@@ -4,6 +4,7 @@
*--------------------------------------------------------------------------------------------*/
import { OperatingSystem } from 'vs/base/common/platform';
import { illegalArgument } from 'vs/base/common/errors';
/**
* Virtual Key Codes, the value does not hold any inherent meaning.
@@ -417,12 +418,12 @@ export function createKeybinding(keybinding: number, OS: OperatingSystem): Keybi
const firstPart = (keybinding & 0x0000FFFF) >>> 0;
const chordPart = (keybinding & 0xFFFF0000) >>> 16;
if (chordPart !== 0) {
return new ChordKeybinding(
return new ChordKeybinding([
createSimpleKeybinding(firstPart, OS),
createSimpleKeybinding(chordPart, OS),
);
createSimpleKeybinding(chordPart, OS)
]);
}
return createSimpleKeybinding(firstPart, OS);
return new ChordKeybinding([createSimpleKeybinding(firstPart, OS)]);
}
export function createSimpleKeybinding(keybinding: number, OS: OperatingSystem): SimpleKeybinding {
@@ -439,14 +440,7 @@ export function createSimpleKeybinding(keybinding: number, OS: OperatingSystem):
return new SimpleKeybinding(ctrlKey, shiftKey, altKey, metaKey, keyCode);
}
export const enum KeybindingType {
Simple = 1,
Chord = 2
}
export class SimpleKeybinding {
public readonly type = KeybindingType.Simple;
public readonly ctrlKey: boolean;
public readonly shiftKey: boolean;
public readonly altKey: boolean;
@@ -461,10 +455,7 @@ export class SimpleKeybinding {
this.keyCode = keyCode;
}
public equals(other: Keybinding): boolean {
if (other.type !== KeybindingType.Simple) {
return false;
}
public equals(other: SimpleKeybinding): boolean {
return (
this.ctrlKey === other.ctrlKey
&& this.shiftKey === other.shiftKey
@@ -492,6 +483,10 @@ export class SimpleKeybinding {
);
}
public toChord(): ChordKeybinding {
return new ChordKeybinding([this]);
}
/**
* Does this keybinding refer to the key code of a modifier and it also has the modifier flag?
*/
@@ -506,22 +501,43 @@ export class SimpleKeybinding {
}
export class ChordKeybinding {
public readonly type = KeybindingType.Chord;
public readonly parts: SimpleKeybinding[];
public readonly firstPart: SimpleKeybinding;
public readonly chordPart: SimpleKeybinding;
constructor(firstPart: SimpleKeybinding, chordPart: SimpleKeybinding) {
this.firstPart = firstPart;
this.chordPart = chordPart;
constructor(parts: SimpleKeybinding[]) {
if (parts.length === 0) {
throw illegalArgument(`parts`);
}
this.parts = parts;
}
public getHashCode(): string {
return `${this.firstPart.getHashCode()};${this.chordPart.getHashCode()}`;
let result = '';
for (let i = 0, len = this.parts.length; i < len; i++) {
if (i !== 0) {
result += ';';
}
result += this.parts[i].getHashCode();
}
return result;
}
public equals(other: ChordKeybinding | null): boolean {
if (other === null) {
return false;
}
if (this.parts.length !== other.parts.length) {
return false;
}
for (let i = 0; i < this.parts.length; i++) {
if (!this.parts[i].equals(other.parts[i])) {
return false;
}
}
return true;
}
}
export type Keybinding = SimpleKeybinding | ChordKeybinding;
export type Keybinding = ChordKeybinding;
export class ResolvedKeybindingPart {
readonly ctrlKey: boolean;
@@ -574,12 +590,13 @@ export abstract class ResolvedKeybinding {
public abstract isChord(): boolean;
/**
* Returns the firstPart, chordPart that should be used for dispatching.
* Returns the parts that comprise of the keybinding.
* Simple keybindings return one element.
*/
public abstract getDispatchParts(): [string | null, string | null];
public abstract getParts(): ResolvedKeybindingPart[];
/**
* Returns the firstPart, chordPart of the keybinding.
* For simple keybindings, the second element will be null.
* Returns the parts that should be used for dispatching.
*/
public abstract getParts(): [ResolvedKeybindingPart, ResolvedKeybindingPart | null];
public abstract getDispatchParts(): (string | null)[];
}
+18 -14
View File
@@ -21,6 +21,10 @@ export interface Modifiers {
readonly metaKey: boolean;
}
export interface KeyLabelProvider<T extends Modifiers> {
(keybinding: T): string | null;
}
export class ModifierLabelProvider {
public readonly modifierLabels: ModifierLabels[];
@@ -32,11 +36,22 @@ export class ModifierLabelProvider {
this.modifierLabels[OperatingSystem.Linux] = linux;
}
public toLabel(firstPartMod: Modifiers | null, firstPartKey: string | null, chordPartMod: Modifiers | null, chordPartKey: string | null, OS: OperatingSystem): string | null {
if (firstPartMod === null || firstPartKey === null) {
public toLabel<T extends Modifiers>(OS: OperatingSystem, parts: T[], keyLabelProvider: KeyLabelProvider<T>): string | null {
if (parts.length === 0) {
return null;
}
return _asString(firstPartMod, firstPartKey, chordPartMod, chordPartKey, this.modifierLabels[OS]);
let result: string[] = [];
for (let i = 0, len = parts.length; i < len; i++) {
const part = parts[i];
const keyLabel = keyLabelProvider(part);
if (keyLabel === null) {
// this keybinding cannot be expressed...
return null;
}
result[i] = _simpleAsString(part, keyLabel, this.modifierLabels[OS]);
}
return result.join(' ');
}
}
@@ -171,14 +186,3 @@ function _simpleAsString(modifiers: Modifiers, key: string, labels: ModifierLabe
return result.join(labels.separator);
}
function _asString(firstPartMod: Modifiers, firstPartKey: string, chordPartMod: Modifiers | null, chordPartKey: string | null, labels: ModifierLabels): string {
let result = _simpleAsString(firstPartMod, firstPartKey, labels);
if (chordPartMod !== null && chordPartKey !== null) {
result += ' ';
result += _simpleAsString(chordPartMod, chordPartKey, labels);
}
return result;
}
+8 -9
View File
@@ -85,16 +85,14 @@ export class KeybindingParser {
return null;
}
let [firstPart, remains] = this.parseSimpleKeybinding(input);
let chordPart: SimpleKeybinding | null = null;
if (remains.length > 0) {
[chordPart] = this.parseSimpleKeybinding(remains);
}
let parts: SimpleKeybinding[] = [];
let part: SimpleKeybinding;
if (chordPart) {
return new ChordKeybinding(firstPart, chordPart);
}
return firstPart;
do {
[part, input] = this.parseSimpleKeybinding(input);
parts.push(part);
} while (input.length > 0);
return new ChordKeybinding(parts);
}
private static parseSimpleUserBinding(input: string): [SimpleKeybinding | ScanCodeBinding, string] {
@@ -110,6 +108,7 @@ export class KeybindingParser {
}
static parseUserBinding(input: string): [SimpleKeybinding | ScanCodeBinding | null, SimpleKeybinding | ScanCodeBinding | null] {
// TODO@chords: allow users to define N chords
if (!input) {
return [null, null];
}
+20 -19
View File
@@ -4,11 +4,11 @@
*--------------------------------------------------------------------------------------------*/
import { URI } from 'vs/base/common/uri';
import { nativeSep, normalize, basename as pathsBasename, sep } from 'vs/base/common/paths';
import { sep, posix, normalize } from 'vs/base/common/path';
import { endsWith, ltrim, startsWithIgnoreCase, rtrim, startsWith } from 'vs/base/common/strings';
import { Schemas } from 'vs/base/common/network';
import { isLinux, isWindows, isMacintosh } from 'vs/base/common/platform';
import { isEqual } from 'vs/base/common/resources';
import { isEqual, basename } from 'vs/base/common/resources';
export interface IWorkspaceFolderProvider {
getWorkspaceFolder(resource: URI): { uri: URI, name?: string } | null;
@@ -39,11 +39,12 @@ export function getPathLabel(resource: URI | string, userHomeProvider?: IUserHom
if (isEqual(baseResource.uri, resource, !isLinux)) {
pathLabel = ''; // no label if paths are identical
} else {
pathLabel = normalize(ltrim(resource.path.substr(baseResource.uri.path.length), sep)!, true);
// TODO: isidor use resources.relative
pathLabel = normalize(ltrim(resource.path.substr(baseResource.uri.path.length), posix.sep)!);
}
if (hasMultipleRoots) {
const rootName = (baseResource && baseResource.name) ? baseResource.name : pathsBasename(baseResource.uri.fsPath);
const rootName = (baseResource && baseResource.name) ? baseResource.name : basename(baseResource.uri);
pathLabel = pathLabel ? (rootName + ' • ' + pathLabel) : rootName; // always show root basename if there are multiple
}
@@ -58,11 +59,11 @@ export function getPathLabel(resource: URI | string, userHomeProvider?: IUserHom
// convert c:\something => C:\something
if (hasDriveLetter(resource.fsPath)) {
return normalize(normalizeDriveLetter(resource.fsPath), true);
return normalize(normalizeDriveLetter(resource.fsPath));
}
// normalize and tildify (macOS, Linux only)
let res = normalize(resource.fsPath, true);
let res = normalize(resource.fsPath);
if (!isWindows && userHomeProvider) {
res = tildify(res, userHomeProvider.userHome);
}
@@ -81,7 +82,7 @@ export function getBaseLabel(resource: URI | string | undefined): string | undef
resource = URI.file(resource);
}
const base = pathsBasename(resource.path) || (resource.scheme === Schemas.file ? resource.fsPath : resource.path) /* can be empty string if '/' is passed in */;
const base = basename(resource) || (resource.scheme === Schemas.file ? resource.fsPath : resource.path) /* can be empty string if '/' is passed in */;
// convert c: => C:
if (hasDriveLetter(base)) {
@@ -112,7 +113,7 @@ export function tildify(path: string, userHome: string): string {
// Keep a normalized user home path as cache to prevent accumulated string creation
let normalizedUserHome = normalizedUserHomeCached.original === userHome ? normalizedUserHomeCached.normalized : undefined;
if (!normalizedUserHome) {
normalizedUserHome = `${rtrim(userHome, sep)}${sep}`;
normalizedUserHome = `${rtrim(userHome, posix.sep)}${posix.sep}`;
normalizedUserHomeCached = { original: userHome, normalized: normalizedUserHome };
}
@@ -169,7 +170,7 @@ export function shorten(paths: string[]): string[] {
let path = paths[pathIndex];
if (path === '') {
shortenedPaths[pathIndex] = `.${nativeSep}`;
shortenedPaths[pathIndex] = `.${sep}`;
continue;
}
@@ -185,20 +186,20 @@ export function shorten(paths: string[]): string[] {
if (path.indexOf(unc) === 0) {
prefix = path.substr(0, path.indexOf(unc) + unc.length);
path = path.substr(path.indexOf(unc) + unc.length);
} else if (path.indexOf(nativeSep) === 0) {
prefix = path.substr(0, path.indexOf(nativeSep) + nativeSep.length);
path = path.substr(path.indexOf(nativeSep) + nativeSep.length);
} else if (path.indexOf(sep) === 0) {
prefix = path.substr(0, path.indexOf(sep) + sep.length);
path = path.substr(path.indexOf(sep) + sep.length);
} else if (path.indexOf(home) === 0) {
prefix = path.substr(0, path.indexOf(home) + home.length);
path = path.substr(path.indexOf(home) + home.length);
}
// pick the first shortest subpath found
const segments: string[] = path.split(nativeSep);
const segments: string[] = path.split(sep);
for (let subpathLength = 1; match && subpathLength <= segments.length; subpathLength++) {
for (let start = segments.length - subpathLength; match && start >= 0; start--) {
match = false;
let subpath = segments.slice(start, start + subpathLength).join(nativeSep);
let subpath = segments.slice(start, start + subpathLength).join(sep);
// that is unique to any other path
for (let otherPathIndex = 0; !match && otherPathIndex < paths.length; otherPathIndex++) {
@@ -209,7 +210,7 @@ export function shorten(paths: string[]): string[] {
// Adding separator as prefix for subpath, such that 'endsWith(src, trgt)' considers subpath as directory name instead of plain string.
// prefix is not added when either subpath is root directory or path[otherPathIndex] does not have multiple directories.
const subpathWithSep: string = (start > 0 && paths[otherPathIndex].indexOf(nativeSep) > -1) ? nativeSep + subpath : subpath;
const subpathWithSep: string = (start > 0 && paths[otherPathIndex].indexOf(sep) > -1) ? sep + subpath : subpath;
const isOtherPathEnding: boolean = endsWith(paths[otherPathIndex], subpathWithSep);
match = !isSubpathEnding || isOtherPathEnding;
@@ -226,11 +227,11 @@ export function shorten(paths: string[]): string[] {
// extend subpath to include disk drive prefix
start = 0;
subpathLength++;
subpath = segments[0] + nativeSep + subpath;
subpath = segments[0] + sep + subpath;
}
if (start > 0) {
result = segments[0] + nativeSep;
result = segments[0] + sep;
}
result = prefix + result;
@@ -238,14 +239,14 @@ export function shorten(paths: string[]): string[] {
// add ellipsis at the beginning if neeeded
if (start > 0) {
result = result + ellipsis + nativeSep;
result = result + ellipsis + sep;
}
result = result + subpath;
// add ellipsis at the end if needed
if (start + subpathLength < segments.length) {
result = result + nativeSep + ellipsis;
result = result + sep + ellipsis;
}
shortenedPaths[pathIndex] = result;
+10 -10
View File
@@ -3,9 +3,9 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as paths from 'vs/base/common/paths';
import * as strings from 'vs/base/common/strings';
import * as arrays from 'vs/base/common/arrays';
import { basename, posix, extname } from 'vs/base/common/path';
import { endsWith, startsWithUTF8BOM, startsWith } from 'vs/base/common/strings';
import { coalesce } from 'vs/base/common/arrays';
import { match } from 'vs/base/common/glob';
export const MIME_TEXT = 'text/plain';
@@ -85,7 +85,7 @@ function toTextMimeAssociationItem(association: ITextMimeAssociation): ITextMime
filenameLowercase: association.filename ? association.filename.toLowerCase() : undefined,
extensionLowercase: association.extension ? association.extension.toLowerCase() : undefined,
filepatternLowercase: association.filepattern ? association.filepattern.toLowerCase() : undefined,
filepatternOnPath: association.filepattern ? association.filepattern.indexOf(paths.sep) >= 0 : false
filepatternOnPath: association.filepattern ? association.filepattern.indexOf(posix.sep) >= 0 : false
};
}
@@ -112,7 +112,7 @@ export function guessMimeTypes(path: string | null, firstLine?: string): string[
}
path = path.toLowerCase();
const filename = paths.basename(path);
const filename = basename(path);
// 1.) User configured mappings have highest priority
const configuredMime = guessMimeTypeByPath(path, filename, userRegisteredAssociations);
@@ -166,7 +166,7 @@ function guessMimeTypeByPath(path: string, filename: string, associations: IText
// Longest extension match
if (association.extension) {
if (!extensionMatch || association.extension.length > extensionMatch.extension!.length) {
if (strings.endsWith(filename, association.extensionLowercase!)) {
if (endsWith(filename, association.extensionLowercase!)) {
extensionMatch = association;
}
}
@@ -192,7 +192,7 @@ function guessMimeTypeByPath(path: string, filename: string, associations: IText
}
function guessMimeTypeByFirstline(firstLine: string): string | null {
if (strings.startsWithUTF8BOM(firstLine)) {
if (startsWithUTF8BOM(firstLine)) {
firstLine = firstLine.substr(1);
}
@@ -234,8 +234,8 @@ export function suggestFilename(langId: string, prefix: string): string {
const extensions = registeredAssociations
.filter(assoc => !assoc.userConfigured && assoc.extension && assoc.id === langId)
.map(assoc => assoc.extension);
const extensionsWithDotFirst = arrays.coalesce(extensions)
.filter(assoc => strings.startsWith(assoc, '.'));
const extensionsWithDotFirst = coalesce(extensions)
.filter(assoc => startsWith(assoc, '.'));
if (extensionsWithDotFirst.length > 0) {
return prefix + extensionsWithDotFirst[0];
@@ -299,6 +299,6 @@ const mapExtToMediaMimes: MapExtToMediaMimes = {
};
export function getMediaMime(path: string): string | undefined {
const ext = paths.extname(path);
const ext = extname(path);
return mapExtToMediaMimes[ext.toLowerCase()];
}
File diff suppressed because it is too large Load Diff
+36 -24
View File
@@ -5,39 +5,26 @@
'use strict';
/*global define*/
//@ts-check
// This module can be loaded in an amd and commonjs-context.
// Because we want both instances to use the same perf-data
// we store them globally
// stores data as: 'name','timestamp'
function _factory(sharedObj) {
if (typeof define !== "function" && typeof module === "object" && typeof module.exports === "object") {
// this is commonjs, fake amd
global.define = function (_dep, callback) {
module.exports = callback();
global.define = undefined;
};
}
define([], function () {
global._performanceEntries = global._performanceEntries || [];
sharedObj._performanceEntries = sharedObj._performanceEntries || [];
const _dataLen = 2;
const _timeStamp = typeof console.timeStamp === 'function' ? console.timeStamp.bind(console) : () => { };
function importEntries(entries) {
global._performanceEntries.splice(0, 0, ...entries);
sharedObj._performanceEntries.splice(0, 0, ...entries);
}
function exportEntries() {
return global._performanceEntries.slice(0);
return sharedObj._performanceEntries.slice(0);
}
function getEntries() {
const result = [];
const entries = global._performanceEntries;
const entries = sharedObj._performanceEntries;
for (let i = 0; i < entries.length; i += _dataLen) {
result.push({
name: entries[i],
@@ -48,7 +35,7 @@ define([], function () {
}
function getEntry(name) {
const entries = global._performanceEntries;
const entries = sharedObj._performanceEntries;
for (let i = 0; i < entries.length; i += _dataLen) {
if (entries[i] === name) {
return {
@@ -60,7 +47,7 @@ define([], function () {
}
function getDuration(from, to) {
const entries = global._performanceEntries;
const entries = sharedObj._performanceEntries;
let target = to;
let endIndex = 0;
for (let i = entries.length - _dataLen; i >= 0; i -= _dataLen) {
@@ -79,11 +66,11 @@ define([], function () {
}
function mark(name) {
global._performanceEntries.push(name, Date.now());
sharedObj._performanceEntries.push(name, Date.now());
_timeStamp(name);
}
var exports = {
const exports = {
mark: mark,
getEntries: getEntries,
getEntry: getEntry,
@@ -93,4 +80,29 @@ define([], function () {
};
return exports;
});
}
// This module can be loaded in an amd and commonjs-context.
// Because we want both instances to use the same perf-data
// we store them globally
let sharedObj;
if (typeof global === 'object') {
// nodejs
sharedObj = global;
} else if (typeof self === 'object') {
// browser
sharedObj = self;
} else {
sharedObj = {};
}
if (typeof define === 'function') {
// amd
define([], function () { return _factory(sharedObj); });
} else if (typeof module === "object" && typeof module.exports === "object") {
// commonjs
module.exports = _factory(sharedObj);
} else {
// invalid context...
}
+72 -25
View File
@@ -3,7 +3,8 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as paths from 'vs/base/common/paths';
import * as extpath from 'vs/base/common/extpath';
import * as paths from 'vs/base/common/path';
import { URI } from 'vs/base/common/uri';
import { equalsIgnoreCase } from 'vs/base/common/strings';
import { Schemas } from 'vs/base/common/network';
@@ -32,22 +33,21 @@ export function basenameOrAuthority(resource: URI): string {
export function isEqualOrParent(base: URI, parentCandidate: URI, ignoreCase = hasToIgnoreCase(base)): boolean {
if (base.scheme === parentCandidate.scheme) {
if (base.scheme === Schemas.file) {
return paths.isEqualOrParent(fsPath(base), fsPath(parentCandidate), ignoreCase);
return extpath.isEqualOrParent(originalFSPath(base), originalFSPath(parentCandidate), ignoreCase);
}
if (isEqualAuthority(base.authority, parentCandidate.authority, ignoreCase)) {
return paths.isEqualOrParent(base.path, parentCandidate.path, ignoreCase, '/');
if (isEqualAuthority(base.authority, parentCandidate.authority)) {
return extpath.isEqualOrParent(base.path, parentCandidate.path, ignoreCase, '/');
}
}
return false;
}
function isEqualAuthority(a1: string, a2: string, ignoreCase?: boolean) {
return a1 === a2 || ignoreCase && a1 && a2 && equalsIgnoreCase(a1, a2);
function isEqualAuthority(a1: string, a2: string) {
return a1 === a2 || equalsIgnoreCase(a1, a2);
}
export function isEqual(first: URI | undefined, second: URI | undefined, ignoreCase = hasToIgnoreCase(first)): boolean {
const identityEquals = (first === second);
if (identityEquals) {
if (first === second) {
return true;
}
@@ -55,15 +55,20 @@ export function isEqual(first: URI | undefined, second: URI | undefined, ignoreC
return false;
}
if (ignoreCase) {
return equalsIgnoreCase(first.toString(), second.toString());
if (first.scheme !== second.scheme || !isEqualAuthority(first.authority, second.authority)) {
return false;
}
return first.toString() === second.toString();
const p1 = first.path || '/', p2 = second.path || '/';
return p1 === p2 || ignoreCase && equalsIgnoreCase(p1 || '/', p2 || '/');
}
export function basename(resource: URI): string {
return paths.basename(resource.path);
return paths.posix.basename(resource.path);
}
export function extname(resource: URI): string {
return paths.posix.extname(resource.path);
}
/**
@@ -72,16 +77,17 @@ export function basename(resource: URI): string {
* @param resource The input URI.
* @returns The URI representing the directory of the input URI.
*/
export function dirname(resource: URI): URI | null {
export function dirname(resource: URI): URI {
if (resource.path.length === 0) {
return resource;
}
if (resource.scheme === Schemas.file) {
return URI.file(paths.dirname(fsPath(resource)));
return URI.file(paths.dirname(originalFSPath(resource)));
}
let dirname = paths.dirname(resource.path, '/');
let dirname = paths.posix.dirname(resource.path);
if (resource.authority && dirname.length && dirname.charCodeAt(0) !== CharCode.Slash) {
return null; // If a URI contains an authority component, then the path component must either be empty or begin with a CharCode.Slash ("/") character
console.error(`dirname("${resource.toString})) resulted in a relative path`);
dirname = '/'; // If a URI contains an authority component, then the path component must either be empty or begin with a CharCode.Slash ("/") character
}
return resource.with({
path: dirname
@@ -89,18 +95,18 @@ export function dirname(resource: URI): URI | null {
}
/**
* Join a URI path with a path fragment and normalizes the resulting path.
* Join a URI path with path fragments and normalizes the resulting path.
*
* @param resource The input URI.
* @param pathFragment The path fragment to add to the URI path.
* @returns The resulting URI.
*/
export function joinPath(resource: URI, pathFragment: string): URI {
export function joinPath(resource: URI, ...pathFragment: string[]): URI {
let joinedPath: string;
if (resource.scheme === Schemas.file) {
joinedPath = URI.file(paths.join(fsPath(resource), pathFragment)).path;
joinedPath = URI.file(paths.join(originalFSPath(resource), ...pathFragment)).path;
} else {
joinedPath = paths.join(resource.path, pathFragment);
joinedPath = paths.posix.join(resource.path || '/', ...pathFragment);
}
return resource.with({
path: joinedPath
@@ -119,9 +125,9 @@ export function normalizePath(resource: URI): URI {
}
let normalizedPath: string;
if (resource.scheme === Schemas.file) {
normalizedPath = URI.file(paths.normalize(fsPath(resource))).path;
normalizedPath = URI.file(paths.normalize(originalFSPath(resource))).path;
} else {
normalizedPath = paths.normalize(resource.path);
normalizedPath = paths.posix.normalize(resource.path);
}
return resource.with({
path: normalizedPath
@@ -132,7 +138,7 @@ export function normalizePath(resource: URI): URI {
* Returns the fsPath of an URI where the drive letter is not normalized.
* See #56403.
*/
export function fsPath(uri: URI): string {
export function originalFSPath(uri: URI): string {
let value: string;
const uriPath = uri.path;
if (uri.authority && uriPath.length > 1 && uri.scheme === 'file') {
@@ -141,7 +147,7 @@ export function fsPath(uri: URI): string {
} else if (
isWindows
&& uriPath.charCodeAt(0) === CharCode.Slash
&& paths.isWindowsDriveLetter(uriPath.charCodeAt(1))
&& extpath.isWindowsDriveLetter(uriPath.charCodeAt(1))
&& uriPath.charCodeAt(2) === CharCode.Colon
) {
value = uriPath.substr(1);
@@ -159,7 +165,48 @@ export function fsPath(uri: URI): string {
* Returns true if the URI path is absolute.
*/
export function isAbsolutePath(resource: URI): boolean {
return paths.isAbsolute(resource.path);
return !!resource.path && resource.path[0] === '/';
}
/**
* Returns true if the URI path has a trailing path separator
*/
export function hasTrailingPathSeparator(resource: URI): boolean {
if (resource.scheme === Schemas.file) {
const fsp = originalFSPath(resource);
return fsp.length > extpath.getRoot(fsp).length && fsp[fsp.length - 1] === paths.sep;
} else {
let p = resource.path;
return p.length > 1 && p.charCodeAt(p.length - 1) === CharCode.Slash; // ignore the slash at offset 0
}
}
/**
* Removes a trailing path seperator, if theres one.
* Important: Doesn't remove the first slash, it would make the URI invalid
*/
export function removeTrailingPathSeparator(resource: URI): URI {
if (hasTrailingPathSeparator(resource)) {
return resource.with({ path: resource.path.substr(0, resource.path.length - 1) });
}
return resource;
}
/**
* Returns a relative path between two URIs. If the URIs don't have the same schema or authority, `undefined` is returned.
* The returned relative path always uses forward slashes.
*/
export function relativePath(from: URI, to: URI): string | undefined {
if (from.scheme !== to.scheme || !isEqualAuthority(from.authority, to.authority)) {
return undefined;
}
if (from.scheme === Schemas.file) {
const relativePath = paths.relative(from.path, to.path);
return isWindows ? extpath.toSlashes(relativePath) : relativePath;
}
return paths.posix.relative(from.path || '/', to.path || '/');
}
export function distinctParents<T>(items: T[], resourceAccessor: (item: T) => URI): T[] {
+35 -7
View File
@@ -49,7 +49,7 @@ export function isStringArray(value: any): value is string[] {
* @returns whether the provided parameter is of type `object` but **not**
* `null`, an `array`, a `regexp`, nor a `date`.
*/
export function isObject(obj: any): boolean {
export function isObject(obj: any): obj is Object {
// The method can't do a type cast since there are type (like strings) which
// are subclasses of any put not positvely matched by the function. Hence type
// narrowing results in wrong results.
@@ -143,8 +143,12 @@ export function validateConstraint(arg: any, constraint: TypeConstraint | undefi
throw new Error(`argument does not match constraint: typeof ${constraint}`);
}
} else if (isFunction(constraint)) {
if (arg instanceof constraint) {
return;
try {
if (arg instanceof constraint) {
return;
}
} catch{
// ignore
}
if (!isUndefinedOrNull(arg) && arg.constructor === constraint) {
return;
@@ -161,8 +165,32 @@ export function validateConstraint(arg: any, constraint: TypeConstraint | undefi
* any additional argument supplied.
*/
export function create(ctor: Function, ...args: any[]): any {
let obj = Object.create(ctor.prototype);
ctor.apply(obj, args);
return obj;
if (isNativeClass(ctor)) {
return new (ctor as any)(...args);
} else {
let obj = Object.create(ctor.prototype);
ctor.apply(obj, args);
return obj;
}
}
// https://stackoverflow.com/a/32235645/1499159
function isNativeClass(thing): boolean {
return typeof thing === 'function'
&& thing.hasOwnProperty('prototype')
&& !thing.hasOwnProperty('arguments');
}
/**
*
*
*/
export function getAllPropertyNames(obj: object): string[] {
let res: string[] = [];
let proto = Object.getPrototypeOf(obj);
while (Object.prototype !== proto) {
res = res.concat(Object.getOwnPropertyNames(proto));
proto = Object.getPrototypeOf(proto);
}
return res;
}
+3 -2
View File
@@ -6,6 +6,7 @@
import { transformErrorForSerialization } from 'vs/base/common/errors';
import { Disposable } from 'vs/base/common/lifecycle';
import { isWeb } from 'vs/base/common/platform';
import { getAllPropertyNames } from 'vs/base/common/types';
const INITIALIZE = '$initialize';
@@ -324,7 +325,7 @@ export class SimpleWorkerServer {
if (this._requestHandler) {
// static request handler
let methods: string[] = [];
for (let prop in this._requestHandler) {
for (const prop of getAllPropertyNames(this._requestHandler)) {
if (typeof this._requestHandler[prop] === 'function') {
methods.push(prop);
}
@@ -360,7 +361,7 @@ export class SimpleWorkerServer {
}
let methods: string[] = [];
for (let prop in this._requestHandler) {
for (const prop of getAllPropertyNames(this._requestHandler)) {
if (typeof this._requestHandler[prop] === 'function') {
methods.push(prop);
}
+1 -1
View File
@@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/
import * as fs from 'fs';
import { dirname, basename } from 'path';
import { dirname, basename } from 'vs/base/common/path';
import * as objects from 'vs/base/common/objects';
import { IDisposable, dispose } from 'vs/base/common/lifecycle';
import { Event, Emitter } from 'vs/base/common/event';
+1 -1
View File
@@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/
import * as fs from 'fs';
import * as paths from 'path';
import * as paths from 'vs/base/common/path';
import { nfcall } from 'vs/base/common/async';
import { normalizeNFC } from 'vs/base/common/normalization';
import * as platform from 'vs/base/common/platform';
+1 -1
View File
@@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/
import * as extfs from 'vs/base/node/extfs';
import { join } from 'path';
import { join } from 'vs/base/common/path';
import { nfcall, Queue } from 'vs/base/common/async';
import * as fs from 'fs';
import * as os from 'os';
+3 -3
View File
@@ -3,14 +3,14 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as path from 'path';
import * as path from 'vs/base/common/path';
import * as fs from 'fs';
import * as cp from 'child_process';
import * as nls from 'vs/nls';
import * as Types from 'vs/base/common/types';
import { IStringDictionary } from 'vs/base/common/collections';
import * as Objects from 'vs/base/common/objects';
import * as TPath from 'vs/base/common/paths';
import * as extpath from 'vs/base/common/extpath';
import * as Platform from 'vs/base/common/platform';
import { LineDecoder } from 'vs/base/node/decoder';
import { CommandOptions, ForkOptions, SuccessData, Source, TerminateResponse, TerminateResponseCode, Executable } from 'vs/base/common/processes';
@@ -168,7 +168,7 @@ export abstract class AbstractProcess<TProgressData> {
}
public start(pp: ProgressCallback<TProgressData>): Promise<SuccessData> {
if (Platform.isWindows && ((this.options && this.options.cwd && TPath.isUNC(this.options.cwd)) || !this.options && TPath.isUNC(process.cwd()))) {
if (Platform.isWindows && ((this.options && this.options.cwd && extpath.isUNC(this.options.cwd)) || !this.options && extpath.isUNC(process.cwd()))) {
return Promise.reject(new Error(nls.localize('TaskRunner.UNC', 'Can\'t execute a shell command on a UNC drive.')));
}
return this.useExec().then((useExec) => {
+1 -1
View File
@@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/
import { readdir, stat, exists, readFile } from 'fs';
import { join } from 'path';
import { join } from 'vs/base/common/path';
import { parse, ParseError } from 'vs/base/common/json';
export interface WorkspaceStatItem {
+1 -1
View File
@@ -9,7 +9,7 @@ import { Emitter, Event } from 'vs/base/common/event';
import { ThrottledDelayer, timeout } from 'vs/base/common/async';
import { isUndefinedOrNull } from 'vs/base/common/types';
import { mapToString, setToString } from 'vs/base/common/map';
import { basename } from 'path';
import { basename } from 'vs/base/common/path';
import { copy, renameIgnoreError, unlink } from 'vs/base/node/pfs';
import { fill } from 'vs/base/common/arrays';
@@ -4,12 +4,11 @@
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import * as path from 'path';
import * as path from 'vs/base/common/path';
import * as os from 'os';
import { extract } from 'vs/platform/node/zip';
import { extract } from 'vs/base/node/zip';
import { generateUuid } from 'vs/base/common/uuid';
import { rimraf, exists } from 'vs/base/node/pfs';
import { NullLogService } from 'vs/platform/log/common/log';
import { getPathFromAmdModule } from 'vs/base/common/amd';
import { createCancelablePromise } from 'vs/base/common/async';
@@ -21,7 +20,7 @@ suite('Zip', () => {
const fixture = path.join(fixtures, 'extract.zip');
const target = path.join(os.tmpdir(), generateUuid());
return createCancelablePromise(token => extract(fixture, target, {}, new NullLogService(), token)
return createCancelablePromise(token => extract(fixture, target, {}, token)
.then(() => exists(path.join(target, 'extension')))
.then(exists => assert(exists))
.then(() => rimraf(target)));
@@ -4,14 +4,13 @@
*--------------------------------------------------------------------------------------------*/
import * as nls from 'vs/nls';
import * as path from 'path';
import * as path from 'vs/base/common/path';
import { createWriteStream, WriteStream } from 'fs';
import { Readable } from 'stream';
import { nfcall, ninvoke, Sequencer, createCancelablePromise } from 'vs/base/common/async';
import { mkdirp, rimraf } from 'vs/base/node/pfs';
import { open as _openZip, Entry, ZipFile } from 'yauzl';
import * as yazl from 'yazl';
import { ILogService } from 'vs/platform/log/common/log';
import { CancellationToken } from 'vs/base/common/cancellation';
import { Event } from 'vs/base/common/event';
@@ -104,12 +103,11 @@ function extractEntry(stream: Readable, fileName: string, mode: number, targetPa
}));
}
function extractZip(zipfile: ZipFile, targetPath: string, options: IOptions, logService: ILogService, token: CancellationToken): Promise<void> {
function extractZip(zipfile: ZipFile, targetPath: string, options: IOptions, token: CancellationToken): Promise<void> {
let last = createCancelablePromise<void>(() => Promise.resolve());
let extractedEntriesCount = 0;
Event.once(token.onCancellationRequested)(() => {
logService.debug(targetPath, 'Cancelled.');
last.cancel();
zipfile.close();
});
@@ -195,7 +193,7 @@ export function zip(zipPath: string, files: IFile[]): Promise<string> {
});
}
export function extract(zipPath: string, targetPath: string, options: IExtractOptions = {}, logService: ILogService, token: CancellationToken): Promise<void> {
export function extract(zipPath: string, targetPath: string, options: IExtractOptions = {}, token: CancellationToken): Promise<void> {
const sourcePathRegex = new RegExp(options.sourcePath ? `^${options.sourcePath}` : '');
let promise = openZip(zipPath, true);
@@ -204,7 +202,7 @@ export function extract(zipPath: string, targetPath: string, options: IExtractOp
promise = promise.then(zipfile => rimraf(targetPath).then(() => zipfile));
}
return promise.then(zipfile => extractZip(zipfile, targetPath, { sourcePathRegex }, logService, token));
return promise.then(zipfile => extractZip(zipfile, targetPath, { sourcePathRegex }, token));
}
function read(zipPath: string, filePath: string): Promise<Readable> {
+1 -1
View File
@@ -6,7 +6,7 @@
import { Socket, Server as NetServer, createConnection, createServer } from 'net';
import { Event, Emitter } from 'vs/base/common/event';
import { IMessagePassingProtocol, ClientConnectionEvent, IPCServer, IPCClient } from 'vs/base/parts/ipc/node/ipc';
import { join } from 'path';
import { join } from 'vs/base/common/path';
import { tmpdir } from 'os';
import { generateUuid } from 'vs/base/common/uuid';
import { IDisposable } from 'vs/base/common/lifecycle';
@@ -639,7 +639,7 @@ export class QuickOpenWidget extends Disposable implements IModelProvider {
this.setInput(input, autoFocus);
}
private setInputAndLayout(input: IModel<any>, autoFocus: IAutoFocus): void {
private setInputAndLayout(input: IModel<any>, autoFocus?: IAutoFocus): void {
this.treeContainer.style.height = `${this.getHeight(input)}px`;
this.tree.setInput(null).then(() => {
@@ -873,7 +873,7 @@ export class QuickOpenWidget extends Disposable implements IModelProvider {
}
}
setInput(input: IModel<any>, autoFocus: IAutoFocus, ariaLabel?: string): void {
setInput(input: IModel<any>, autoFocus?: IAutoFocus, ariaLabel?: string): void {
if (!this.isVisible()) {
return;
}
@@ -945,7 +945,7 @@ export class QuickOpenWidget extends Disposable implements IModelProvider {
return this.inputBox;
}
setExtraClass(clazz: string): void {
setExtraClass(clazz: string | null): void {
const previousClass = this.element.getAttribute('quick-open-extra-class');
if (previousClass) {
DOM.removeClasses(this.element, previousClass);
@@ -5,7 +5,7 @@
import { compareAnything } from 'vs/base/common/comparers';
import { matchesPrefix, IMatch, matchesCamelCase, isUpper } from 'vs/base/common/filters';
import { nativeSep } from 'vs/base/common/paths';
import { sep } from 'vs/base/common/path';
import { isWindows, isLinux } from 'vs/base/common/platform';
import { stripWildcards, equalsIgnoreCase } from 'vs/base/common/strings';
import { CharCode } from 'vs/base/common/charCode';
@@ -320,11 +320,11 @@ export function prepareQuery(original: string): IPreparedQuery {
let value = stripWildcards(original).replace(/\s/g, ''); // get rid of all wildcards and whitespace
if (isWindows) {
value = value.replace(/\//g, nativeSep); // Help Windows users to search for paths when using slash
value = value.replace(/\//g, sep); // Help Windows users to search for paths when using slash
}
const lowercase = value.toLowerCase();
const containsPathSeparator = value.indexOf(nativeSep) >= 0;
const containsPathSeparator = value.indexOf(sep) >= 0;
return { original, value, lowercase, containsPathSeparator };
}
@@ -410,7 +410,7 @@ function doScoreItem(label: string, description: string | null, path: string | u
if (description) {
let descriptionPrefix = description;
if (!!path) {
descriptionPrefix = `${description}${nativeSep}`; // assume this is a file path
descriptionPrefix = `${description}${sep}`; // assume this is a file path
}
const descriptionPrefixLength = descriptionPrefix.length;

Some files were not shown because too many files have changed in this diff Show More