debugConfigurationManager.ts 15.8 KB
Newer Older
1 2 3 4 5 6 7
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import path = require('path');
import nls = require('vs/nls');
8
import { sequence } from 'vs/base/common/async';
I
isidor 已提交
9
import { TPromise } from 'vs/base/common/winjs.base';
I
isidor 已提交
10
import strings = require('vs/base/common/strings');
11
import {isLinux, isMacintosh, isWindows} from 'vs/base/common/platform';
12
import Event, { Emitter } from 'vs/base/common/event';
13
import objects = require('vs/base/common/objects');
14
import uri from 'vs/base/common/uri';
A
Alex Dima 已提交
15
import { Schemas } from 'vs/base/common/network';
16 17 18
import paths = require('vs/base/common/paths');
import { IJSONSchema } from 'vs/base/common/jsonSchema';
import editor = require('vs/editor/common/editorCommon');
19
import extensionsRegistry = require('vs/platform/extensions/common/extensionsRegistry');
20
import platform = require('vs/platform/platform');
M
Martin Aeschlimann 已提交
21
import jsonContributionRegistry = require('vs/platform/jsonschemas/common/jsonContributionRegistry');
22 23 24
import { IConfigurationService } from 'vs/platform/configuration/common/configuration';
import { IFileService } from 'vs/platform/files/common/files';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
25
import { IKeybindingService } from 'vs/platform/keybinding/common/keybindingService';
26 27 28 29 30
import debug = require('vs/workbench/parts/debug/common/debug');
import { SystemVariables } from 'vs/workbench/parts/lib/node/systemVariables';
import { Adapter } from 'vs/workbench/parts/debug/node/debugAdapter';
import { IWorkspaceContextService } from 'vs/workbench/services/workspace/common/contextService';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
31
import { IQuickOpenService } from 'vs/workbench/services/quickopen/common/quickOpenService';
32

I
isidor 已提交
33
// debuggers extension point
34

35
export var debuggersExtPoint = extensionsRegistry.ExtensionsRegistry.registerExtensionPoint<debug.IRawAdapter[]>('debuggers', {
36 37
	description: nls.localize('vscode.extension.contributes.debuggers', 'Contributes debug adapters.'),
	type: 'array',
38
	defaultSnippets: [{ body: [{ type: '', extensions: [] }] }],
39 40
	items: {
		type: 'object',
41
		defaultSnippets: [{ body: { type: '', program: '', runtime: '', enableBreakpointsFor: { languageIds: [ '' ] } } }],
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
		properties: {
			type: {
				description: nls.localize('vscode.extension.contributes.debuggers.type', "Unique identifier for this debug adapter."),
				type: 'string'
			},
			label: {
				description: nls.localize('vscode.extension.contributes.debuggers.label', "Display name for this debug adapter."),
				type: 'string'
			},
			enableBreakpointsFor: {
				description: nls.localize('vscode.extension.contributes.debuggers.enableBreakpointsFor', "Allow breakpoints for these languages."),
				type: 'object',
				properties: {
					languageIds : {
						description: nls.localize('vscode.extension.contributes.debuggers.enableBreakpointsFor.languageIds', "List of languages."),
						type: 'array',
						items: {
							type: 'string'
						}
					}
				}
			},
			program: {
				description: nls.localize('vscode.extension.contributes.debuggers.program', "Path to the debug adapter program. Path is either absolute or relative to the extension folder."),
				type: 'string'
			},
68 69 70 71
			args: {
				description: nls.localize('vscode.extension.contributes.debuggers.args', "Optional arguments to pass to the adapter."),
				type: 'array'
			},
72 73 74 75 76 77 78 79
			runtime : {
				description: nls.localize('vscode.extension.contributes.debuggers.runtime', "Optional runtime in case the program attribute is not an executable but requires a runtime."),
				type: 'string'
			},
			runtimeArgs : {
				description: nls.localize('vscode.extension.contributes.debuggers.runtimeArgs', "Optional runtime arguments."),
				type: 'array'
			},
80 81 82 83
			variables : {
				description: nls.localize('vscode.extension.contributes.debuggers.variables', "Mapping from interactive variables (e.g ${action.pickProcess}) in `launch.json` to a command."),
				type: 'object'
			},
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
			initialConfigurations: {
				description: nls.localize('vscode.extension.contributes.debuggers.initialConfigurations', "Configurations for generating the initial \'launch.json\'."),
				type: 'array',
			},
			configurationAttributes: {
				description: nls.localize('vscode.extension.contributes.debuggers.configurationAttributes', "JSON schema configurations for validating \'launch.json\'."),
				type: 'object'
			},
			windows: {
				description: nls.localize('vscode.extension.contributes.debuggers.windows', "Windows specific settings."),
				type: 'object',
				properties: {
					runtime : {
						description: nls.localize('vscode.extension.contributes.debuggers.windows.runtime', "Runtime used for Windows."),
						type: 'string'
					}
				}
			},
			osx: {
				description: nls.localize('vscode.extension.contributes.debuggers.osx', "OS X specific settings."),
				type: 'object',
				properties: {
					runtime : {
						description: nls.localize('vscode.extension.contributes.debuggers.osx.runtime', "Runtime used for OSX."),
						type: 'string'
					}
				}
			},
			linux: {
				description: nls.localize('vscode.extension.contributes.debuggers.linux', "Linux specific settings."),
				type: 'object',
				properties: {
					runtime : {
						description: nls.localize('vscode.extension.contributes.debuggers.linux.runtime', "Runtime used for Linux."),
						type: 'string'
					}
				}
			}
		}
	}
});

I
isidor 已提交
126
// debug general schema
127

128
export var schemaId = 'vscode://schemas/launch';
I
isidor 已提交
129
const schema: IJSONSchema = {
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
	id: schemaId,
	type: 'object',
	title: nls.localize('app.launch.json.title', "Launch configuration"),
	required: ['version', 'configurations'],
	properties: {
		version: {
			type: 'string',
			description: nls.localize('app.launch.json.version', "Version of this file format."),
			default: '0.2.0'
		},
		configurations: {
			type: 'array',
			description: nls.localize('app.launch.json.configurations', "List of configurations. Add new configurations or edit existing ones."),
			items: {
				oneOf: []
			}
		}
	}
I
isidor 已提交
148
};
149

I
isidor 已提交
150
const jsonRegistry = <jsonContributionRegistry.IJSONContributionRegistry>platform.Registry.as(jsonContributionRegistry.Extensions.JSONContribution);
151 152
jsonRegistry.registerSchema(schemaId, schema);

153
export class ConfigurationManager implements debug.IConfigurationManager {
154

155
	public configuration: debug.IConfig;
156 157 158
	private systemVariables: SystemVariables;
	private adapters: Adapter[];
	private allModeIdsForBreakpoints: { [key: string]: boolean };
159
	private _onDidConfigurationChange: Emitter<string>;
160 161 162 163 164 165 166 167

	constructor(
		configName: string,
		@IWorkspaceContextService private contextService: IWorkspaceContextService,
		@IFileService private fileService: IFileService,
		@ITelemetryService private telemetryService: ITelemetryService,
		@IWorkbenchEditorService private editorService: IWorkbenchEditorService,
		@IConfigurationService private configurationService: IConfigurationService,
168 169
		@IQuickOpenService private quickOpenService: IQuickOpenService,
		@IKeybindingService private keybindingService: IKeybindingService
170
	) {
171
		this._onDidConfigurationChange = new Emitter<string>();
172
		this.systemVariables = this.contextService.getWorkspace() ? new SystemVariables(this.editorService, this.contextService) : null;
173
		this.setConfiguration(configName);
174 175 176 177 178 179 180 181 182 183
		this.adapters = [];
		this.registerListeners();
		this.allModeIdsForBreakpoints = {};
	}

	private registerListeners(): void {
		debuggersExtPoint.setHandler((extensions) => {

			extensions.forEach(extension => {
				extension.value.forEach(rawAdapter => {
184
					const adapter = new Adapter(rawAdapter, this.systemVariables, extension.description);
185 186 187 188 189 190 191 192 193 194
					const duplicate = this.adapters.filter(a => a.type === adapter.type)[0];
					if (!rawAdapter.type || (typeof rawAdapter.type !== 'string')) {
						extension.collector.error(nls.localize('debugNoType', "Debug adapter 'type' can not be omitted and must be of type 'string'."));
					}

					if (duplicate) {
						Object.keys(adapter).forEach(attribute => {
							if (adapter[attribute]) {
								if (attribute === 'enableBreakpointsFor') {
									Object.keys(adapter.enableBreakpointsFor).forEach(languageId => duplicate.enableBreakpointsFor[languageId] = true);
195
								} else if (duplicate[attribute] && attribute !== 'type' && attribute !== 'extensionDescription') {
I
isidor 已提交
196
									// give priority to the later registered extension.
197
									duplicate[attribute] = adapter[attribute];
198
									extension.collector.error(nls.localize('duplicateDebuggerType', "Debug type '{0}' is already registered and has attribute '{1}', ignoring attribute '{1}'.", adapter.type, attribute));
199 200 201 202 203 204 205 206 207
								} else {
									duplicate[attribute] = adapter[attribute];
								}
							}
						});
					} else {
						this.adapters.push(adapter);
					}

I
isidor 已提交
208 209 210 211 212
					if (adapter.enableBreakpointsFor) {
						adapter.enableBreakpointsFor.languageIds.forEach(modeId => {
							this.allModeIdsForBreakpoints[modeId] = true;
						});
					}
213 214 215
				});
			});

I
isidor 已提交
216
			// update the schema to include all attributes and types from extensions.
217 218 219 220
			// debug.schema.properties['configurations'].items.properties.type.enum = this.adapters.map(adapter => adapter.type);
			this.adapters.forEach(adapter => {
				const schemaAttributes = adapter.getSchemaAttributes();
				if (schemaAttributes) {
221
					(<IJSONSchema> schema.properties['configurations'].items).oneOf.push(...schemaAttributes);
222 223 224 225 226
				}
			});
		});
	}

227 228
	public get onDidConfigurationChange(): Event<string> {
		return this._onDidConfigurationChange.event;
229 230
	}

231
	public get configurationName(): string {
232 233 234
		return this.configuration ? this.configuration.name : null;
	}

235
	public get adapter(): Adapter {
I
isidor 已提交
236 237 238 239
		if (!this.configuration || !this.configuration.type) {
			return null;
		}

I
isidor 已提交
240
		return this.adapters.filter(adapter => strings.equalsIgnoreCase(adapter.type, this.configuration.type)).pop();
241 242
	}

243
	/**
I
isidor 已提交
244
	 * Resolve all interactive variables in configuration #6569
245 246
	 */
	public resolveInteractiveVariables(): TPromise<debug.IConfig>  {
I
isidor 已提交
247 248 249 250
		if (!this.configuration) {
			return TPromise.as(null);
		}

251 252
		const factory = Object.keys(this.configuration).map(key => {
			return () => {
253 254 255 256 257 258 259 260 261 262
				if (typeof this.configuration[key] === 'string') {
					const matches = /\${action.(.+)}/.exec(this.configuration[key]);
					if (matches && matches.length === 2) {
						const commandId = this.adapter.variables[matches[1]];
						if (!commandId) {
							return TPromise.wrapError(nls.localize('interactiveVariableNotFound', "Adapter {0} does not contribute variable {1} that is specified in launch configuration.", this.adapter.type, matches[1]));
						} else {
							return this.keybindingService.executeCommand<string>(commandId, this.configuration)
								.then(result => result ? this.configuration[key] = result : this.configuration.silentlyAbort = true);
						}
263
					}
264
				}
265 266 267

				return TPromise.as(null);
			};
268 269
		});

270
		return sequence(factory).then(() => this.configuration);
271 272
	}

273
	public setConfiguration(nameOrConfig: string|debug.IConfig): TPromise<void> {
274
		return this.loadLaunchConfig().then(config => {
275
			if (typeof nameOrConfig === 'string' && (!config || !config.configurations)) {
276 277 278 279
				this.configuration = null;
				return;
			}

280 281 282 283 284 285 286 287 288 289 290
			if (typeof nameOrConfig === 'string') {
				// if the configuration name is not set yet, take the first launch config (can happen if debug viewlet has not been opened yet).
				const filtered = nameOrConfig ? config.configurations.filter(cfg => cfg.name === nameOrConfig) : [config.configurations[0]];

				this.configuration = filtered.length === 1 ? objects.deepClone(filtered[0]) : null;
				if (config && this.configuration) {
					this.configuration.debugServer = config.debugServer;
				}
			} else {
				this.configuration = objects.deepClone(nameOrConfig);
			}
291

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308
			// Set operating system specific properties #1873
			if (isWindows && this.configuration.windows) {
				Object.keys(this.configuration.windows).forEach(key => {
					this.configuration[key] = this.configuration.windows[key];
				});
			}
			if (isMacintosh && this.configuration.osx) {
				Object.keys(this.configuration.osx).forEach(key => {
					this.configuration[key] = this.configuration.osx[key];
				});
			}
			if (isLinux && this.configuration.linux) {
				Object.keys(this.configuration.linux).forEach(key => {
					this.configuration[key] = this.configuration.linux[key];
				});
			}

I
isidor 已提交
309
			// massage configuration attributes - append workspace path to relatvie paths, substitute variables in paths.
310 311 312 313
			if (this.configuration && this.systemVariables) {
				Object.keys(this.configuration).forEach(key => {
					this.configuration[key] = this.systemVariables.resolveAny(this.configuration[key]);
				});
314
			}
315
		}).then(() => this._onDidConfigurationChange.fire(this.configurationName));
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
	}

	public openConfigFile(sideBySide: boolean): TPromise<boolean> {
		const resource = uri.file(paths.join(this.contextService.getWorkspace().resource.fsPath, '/.vscode/launch.json'));

		return this.fileService.resolveContent(resource).then(content => true, err =>
			this.getInitialConfigFileContent().then(content => {
				if (!content) {
					return false;
				}

				return this.fileService.updateContent(resource, content).then(() => true);
			}
		)).then(configFileCreated => {
			if (!configFileCreated) {
				return false;
			}
			this.telemetryService.publicLog('debugConfigure');

			return this.editorService.openEditor({
				resource: resource,
				options: {
					forceOpen: true
				}
			}, sideBySide).then(() => true);
		}, (error) => {
			throw new Error(nls.localize('DebugConfig.failed', "Unable to create 'launch.json' file inside the '.vscode' folder ({0}).", error));
		});
	}

	private getInitialConfigFileContent(): TPromise<string> {
I
isidor 已提交
347
		return this.quickOpenService.pick(this.adapters, { placeHolder: nls.localize('selectDebug', "Select Environment") })
348 349 350 351 352
		.then(adapter => {
			if (!adapter) {
				return null;
			}

353 354 355 356 357 358 359 360
			return this.massageInitialConfigurations(adapter).then(() => {
				let editorConfig = this.configurationService.getConfiguration<any>();
				return JSON.stringify(
					{
						version: '0.2.0',
						configurations: adapter.initialConfigurations ? adapter.initialConfigurations : []
					},
					null,
361
					editorConfig.editor.insertSpaces ? strings.repeat(' ', editorConfig.editor.tabSize) : '\t');
362
			});
363 364 365
		});
	}

I
isidor 已提交
366
	private massageInitialConfigurations(adapter: Adapter): TPromise<void> {
367
		if (!adapter || !adapter.initialConfigurations || adapter.type !== 'node') {
I
isidor 已提交
368
			return TPromise.as(undefined);
369 370
		}

I
isidor 已提交
371
		// check package.json for 'main' or 'scripts' so we generate a more pecise 'program' attribute in launch.json.
372 373 374 375 376 377 378 379 380 381 382 383 384
		const packageJsonUri = uri.file(paths.join(this.contextService.getWorkspace().resource.fsPath, '/package.json'));
		return this.fileService.resolveContent(packageJsonUri).then(jsonContent => {
			try {
				const jsonObject = JSON.parse(jsonContent.value);
				if (jsonObject.main) {
					return jsonObject.main;
				} else if (jsonObject.scripts && typeof jsonObject.scripts.start === 'string') {
					return (<string>jsonObject.scripts.start).split(' ').pop();
				}

			} catch (error) { }

			return null;
385
		}, err => null).then((program: string) => {
386
			adapter.initialConfigurations.forEach(config => {
I
isidor 已提交
387
				if (program && config.program) {
388
					if (!path.isAbsolute(program)) {
I
isidor 已提交
389
						program = paths.join('${workspaceRoot}', program);
390 391
					}

I
isidor 已提交
392
					config.program = program;
393 394 395 396 397
				}
			});
		});
	}

I
isidor 已提交
398
	public canSetBreakpointsIn(model: editor.IModel): boolean {
399
		if (model.uri.scheme === Schemas.inMemory) {
400 401 402
			return false;
		}

I
isidor 已提交
403 404
		const mode = model ? model.getMode() : null;
		const modeId = mode ? mode.getId() : null;
405 406 407 408 409

		return !!this.allModeIdsForBreakpoints[modeId];
	}

	public loadLaunchConfig(): TPromise<debug.IGlobalConfig> {
410
		return TPromise.as(this.configurationService.getConfiguration<debug.IGlobalConfig>('launch'));
411 412
	}
}