commands.ts 15.0 KB
Newer Older
J
Joao Moreno 已提交
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.
 *--------------------------------------------------------------------------------------------*/

'use strict';

J
Joao Moreno 已提交
8
import { Uri, commands, scm, Disposable, SCMResourceGroup, SCMResource, window, workspace, QuickPickItem, OutputChannel } from 'vscode';
J
Joao Moreno 已提交
9
import { IRef, RefType } from './git';
J
Joao Moreno 已提交
10
import { Model, Resource, Status } from './model';
J
Joao Moreno 已提交
11
import * as path from 'path';
J
Joao Moreno 已提交
12 13 14
import * as nls from 'vscode-nls';

const localize = nls.loadMessageBundle();
J
Joao Moreno 已提交
15

J
Joao Moreno 已提交
16 17 18 19
function resolveGitURI(uri: Uri): SCMResource | SCMResourceGroup | undefined {
	if (uri.authority !== 'git') {
		return;
	}
J
Joao Moreno 已提交
20

J
Joao Moreno 已提交
21
	return scm.getResourceFromURI(uri);
J
Joao Moreno 已提交
22 23
}

J
Joao Moreno 已提交
24 25
function resolveGitResource(uri: Uri): Resource | undefined {
	const resource = resolveGitURI(uri);
J
Joao Moreno 已提交
26

J
Joao Moreno 已提交
27 28 29
	if (!(resource instanceof Resource)) {
		return;
	}
J
Joao Moreno 已提交
30

J
Joao Moreno 已提交
31
	return resource;
J
Joao Moreno 已提交
32 33
}

J
Joao Moreno 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
class CheckoutItem implements QuickPickItem {

	protected get shortCommit(): string { return (this.ref.commit || '').substr(0, 8); }
	protected get treeish(): string | undefined { return this.ref.name; }
	get label(): string { return this.ref.name || this.shortCommit; }
	get description(): string { return this.shortCommit; }

	constructor(protected ref: IRef) { }

	async run(model: Model): Promise<void> {
		const ref = this.treeish;

		if (!ref) {
			return;
		}

		await model.checkout(ref);
	}
}

class CheckoutTagItem extends CheckoutItem {

J
Joao Moreno 已提交
56 57 58
	get description(): string {
		return localize('tag at', "Tag at {0}", this.shortCommit);
	}
J
Joao Moreno 已提交
59 60 61 62
}

class CheckoutRemoteHeadItem extends CheckoutItem {

J
Joao Moreno 已提交
63 64 65
	get description(): string {
		return localize('remote branch at', "Remote branch at {0}", this.shortCommit);
	}
J
Joao Moreno 已提交
66 67 68 69 70 71 72 73 74 75 76

	protected get treeish(): string | undefined {
		if (!this.ref.name) {
			return;
		}

		const match = /^[^/]+\/(.*)$/.exec(this.ref.name);
		return match ? match[1] : this.ref.name;
	}
}

J
Joao Moreno 已提交
77
export class CommandCenter {
J
Joao Moreno 已提交
78

J
Joao Moreno 已提交
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
	private static readonly Commands: { commandId: string; method: any; }[] = [];
	private static Command(commandId: string): Function {
		return (target: any, key: string, descriptor: any) => {
			if (!(typeof descriptor.value === 'function')) {
				throw new Error('not supported');
			}

			CommandCenter.Commands.push({ commandId, method: descriptor.value });
		};
	}

	private static CatchErrors(target: any, key: string, descriptor: any): void {
		if (!(typeof descriptor.value === 'function')) {
			throw new Error('not supported');
		}

		const fn = descriptor.value;

		descriptor.value = function (...args: any[]) {
			fn.apply(this, args).catch(async err => {
J
Joao Moreno 已提交
99 100 101 102
				let message: string;

				switch (err.gitErrorCode) {
					case 'DirtyWorkTree':
J
Joao Moreno 已提交
103
						message = localize('clean repo', "Please clean your repository working tree before checkout.");
J
Joao Moreno 已提交
104 105
						break;
					default:
106 107 108 109 110 111
						const lines = (err.stderr || err.message || String(err))
							.replace(/^error: /, '')
							.split(/[\r\n]/)
							.filter(line => !!line);

						message = lines[0] || 'Git error';
J
Joao Moreno 已提交
112 113 114 115
						break;
				}

				if (!message) {
J
Joao Moreno 已提交
116
					console.error(err);
J
Joao Moreno 已提交
117 118 119 120
					return;
				}

				const outputChannel = this.outputChannel as OutputChannel;
J
Joao Moreno 已提交
121
				const openOutputChannelChoice = localize('open git log', "Open Git Log");
J
Joao Moreno 已提交
122 123 124 125
				const choice = await window.showErrorMessage(message, openOutputChannelChoice);

				if (choice === openOutputChannelChoice) {
					outputChannel.show();
J
Joao Moreno 已提交
126 127 128 129 130
				}
			});
		};
	}

J
Joao Moreno 已提交
131
	private model: Model;
J
Joao Moreno 已提交
132
	private disposables: Disposable[];
J
Joao Moreno 已提交
133

J
Joao Moreno 已提交
134
	constructor(
J
Joao Moreno 已提交
135
		model: Model | undefined,
J
Joao Moreno 已提交
136 137
		private outputChannel: OutputChannel
	) {
J
Joao Moreno 已提交
138 139 140 141
		if (model) {
			this.model = model;
		}

J
Joao Moreno 已提交
142
		this.disposables = CommandCenter.Commands
J
Joao Moreno 已提交
143 144 145 146 147 148 149 150
			.map(({ commandId, method }) => commands.registerCommand(commandId, (...args) => {
				if (!model) {
					window.showInformationMessage(localize('disabled', "Git is either disabled or not supported in this workspace"));
					return;
				}

				return method.apply(this, args);
			}));
J
Joao Moreno 已提交
151 152
	}

J
Joao Moreno 已提交
153 154
	@CommandCenter.Command('git.refresh')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
155
	async refresh(): Promise<void> {
J
Joao Moreno 已提交
156
		await this.model.status();
J
Joao Moreno 已提交
157
	}
J
Joao Moreno 已提交
158

J
Joao Moreno 已提交
159 160
	@CommandCenter.Command('git.openChange')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
161
	async openChange(uri: Uri): Promise<void> {
J
Joao Moreno 已提交
162
		const resource = resolveGitResource(uri);
J
Joao Moreno 已提交
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197

		if (!resource) {
			return;
		}

		return this.open(resource);
	}

	async open(resource: Resource): Promise<void> {
		const left = this.getLeftResource(resource);
		const right = this.getRightResource(resource);
		const title = this.getTitle(resource);

		if (!left) {
			if (!right) {
				// TODO
				console.error('oh no');
				return;
			}

			return commands.executeCommand<void>('vscode.open', right);
		}

		return commands.executeCommand<void>('vscode.diff', left, right, title);
	}

	private getLeftResource(resource: Resource): Uri | undefined {
		switch (resource.type) {
			case Status.INDEX_MODIFIED:
			case Status.INDEX_RENAMED:
				return resource.uri.with({ scheme: 'git', query: 'HEAD' });

			case Status.MODIFIED:
				const uriString = resource.uri.toString();
				const [indexStatus] = this.model.indexGroup.resources.filter(r => r.uri.toString() === uriString);
J
Joao Moreno 已提交
198 199 200 201 202 203

				if (indexStatus) {
					return resource.uri.with({ scheme: 'git' });
				}

				return resource.uri.with({ scheme: 'git', query: 'HEAD' });
J
Joao Moreno 已提交
204
		}
J
Joao Moreno 已提交
205
	}
J
Joao Moreno 已提交
206

J
Joao Moreno 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
	private getRightResource(resource: Resource): Uri | undefined {
		switch (resource.type) {
			case Status.INDEX_MODIFIED:
			case Status.INDEX_ADDED:
			case Status.INDEX_COPIED:
			case Status.INDEX_RENAMED:
				return resource.uri.with({ scheme: 'git' });

			case Status.INDEX_DELETED:
			case Status.DELETED:
				return resource.uri.with({ scheme: 'git', query: 'HEAD' });

			case Status.MODIFIED:
			case Status.UNTRACKED:
			case Status.IGNORED:
			case Status.BOTH_MODIFIED:
				return resource.uri;
		}
	}

	private getTitle(resource: Resource): string {
		const basename = path.basename(resource.uri.fsPath);

		switch (resource.type) {
			case Status.INDEX_MODIFIED:
			case Status.INDEX_RENAMED:
				return `${basename} (Index)`;

			case Status.MODIFIED:
				return `${basename} (Working Tree)`;
		}

		return '';
	}

J
Joao Moreno 已提交
242 243
	@CommandCenter.Command('git.openFile')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
244
	async openFile(uri: Uri): Promise<void> {
J
Joao Moreno 已提交
245
		const resource = resolveGitResource(uri);
J
Joao Moreno 已提交
246 247 248 249 250 251

		if (!resource) {
			return;
		}

		return commands.executeCommand<void>('vscode.open', resource.uri);
J
Joao Moreno 已提交
252 253
	}

J
Joao Moreno 已提交
254 255
	@CommandCenter.Command('git.stage')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
256 257
	async stage(uri: Uri): Promise<void> {
		const resource = resolveGitResource(uri);
J
Joao Moreno 已提交
258

J
Joao Moreno 已提交
259 260 261
		if (!resource) {
			return;
		}
J
Joao Moreno 已提交
262

J
Joao Moreno 已提交
263
		return await this.model.stage(resource);
J
Joao Moreno 已提交
264 265
	}

J
Joao Moreno 已提交
266 267
	@CommandCenter.Command('git.stageAll')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
268 269 270
	async stageAll(): Promise<void> {
		return await this.model.stage();
	}
J
Joao Moreno 已提交
271

J
Joao Moreno 已提交
272 273
	@CommandCenter.Command('git.unstage')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
274 275
	async unstage(uri: Uri): Promise<void> {
		const resource = resolveGitResource(uri);
J
Joao Moreno 已提交
276

J
Joao Moreno 已提交
277
		if (!resource) {
J
Joao Moreno 已提交
278 279 280
			return;
		}

J
Joao Moreno 已提交
281 282 283
		return await this.model.unstage(resource);
	}

J
Joao Moreno 已提交
284 285
	@CommandCenter.Command('git.unstageAll')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
286 287 288
	async unstageAll(): Promise<void> {
		return await this.model.unstage();
	}
J
Joao Moreno 已提交
289

J
Joao Moreno 已提交
290 291
	@CommandCenter.Command('git.clean')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
292 293 294 295
	async clean(uri: Uri): Promise<void> {
		const resource = resolveGitResource(uri);

		if (!resource) {
J
Joao Moreno 已提交
296 297
			return;
		}
J
Joao Moreno 已提交
298

J
Joao Moreno 已提交
299
		const basename = path.basename(resource.uri.fsPath);
J
Joao Moreno 已提交
300
		const message = localize('confirm clean', "Are you sure you want to clean changes in {0}?", basename);
J
Joao Moreno 已提交
301 302
		const yes = localize('clean', "Clean Changes");
		const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
303

J
Joao Moreno 已提交
304 305 306 307
		if (pick !== yes) {
			return;
		}

J
Joao Moreno 已提交
308
		await this.model.clean(resource);
J
Joao Moreno 已提交
309
	}
J
Joao Moreno 已提交
310

J
Joao Moreno 已提交
311 312
	@CommandCenter.Command('git.cleanAll')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
313
	async cleanAll(): Promise<void> {
J
Joao Moreno 已提交
314
		const message = localize('confirm clean all', "Are you sure you want to clean all changes?");
J
Joao Moreno 已提交
315 316
		const yes = localize('clean', "Clean Changes");
		const pick = await window.showWarningMessage(message, { modal: true }, yes);
J
Joao Moreno 已提交
317 318 319 320 321

		if (pick !== yes) {
			return;
		}

J
Joao Moreno 已提交
322
		await this.model.clean(...this.model.workingTreeGroup.resources);
J
Joao Moreno 已提交
323 324
	}

J
Joao Moreno 已提交
325 326 327 328 329 330 331 332 333 334 335 336 337
	private async _commit(fn: () => Promise<string>): Promise<boolean> {
		if (this.model.indexGroup.resources.length === 0 && this.model.workingTreeGroup.resources.length === 0) {
			window.showInformationMessage(localize('no changes', "There are no changes to commit."));
			return false;
		}

		const message = await fn();

		if (!message) {
			// TODO@joao: show modal dialog to confirm empty message commit
			return false;
		}

J
Joao Moreno 已提交
338
		const all = this.model.indexGroup.resources.length === 0;
J
Joao Moreno 已提交
339 340 341 342 343 344 345 346
		await this.model.commit(message, { all });

		return true;
	}

	@CommandCenter.Command('git.commit')
	@CommandCenter.CatchErrors
	async commit(): Promise<void> {
347
		const message = scm.inputBox.value;
J
Joao Moreno 已提交
348 349 350 351 352 353 354 355 356 357 358 359 360

		const didCommit = await this._commit(async () => {
			if (message) {
				return message;
			}

			return await window.showInputBox({
				placeHolder: localize('commit message', "Commit message"),
				prompt: localize('provide commit message', "Please provide a commit message")
			});
		});

		if (message && didCommit) {
361
			scm.inputBox.value = '';
J
Joao Moreno 已提交
362
		}
J
Joao Moreno 已提交
363 364 365 366 367
	}

	@CommandCenter.Command('git.commitWithInput')
	@CommandCenter.CatchErrors
	async commitWithInput(): Promise<void> {
368
		const didCommit = await this._commit(async () => scm.inputBox.value);
J
Joao Moreno 已提交
369 370

		if (didCommit) {
371
			scm.inputBox.value = '';
J
Joao Moreno 已提交
372
		}
J
Joao Moreno 已提交
373 374
	}

J
Joao Moreno 已提交
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404
	@CommandCenter.Command('git.commitStaged')
	@CommandCenter.CatchErrors
	async commitStaged(): Promise<void> {
		await Promise.reject('not implemented');
	}

	@CommandCenter.Command('git.commitStagedSigned')
	@CommandCenter.CatchErrors
	async commitStagedSigned(): Promise<void> {
		await Promise.reject('not implemented');
	}

	@CommandCenter.Command('git.commitAll')
	@CommandCenter.CatchErrors
	async commitAll(): Promise<void> {
		await Promise.reject('not implemented');
	}

	@CommandCenter.Command('git.commitAllSigned')
	@CommandCenter.CatchErrors
	async commitAllSigned(): Promise<void> {
		await Promise.reject('not implemented');
	}

	@CommandCenter.Command('git.undoCommit')
	@CommandCenter.CatchErrors
	async undoCommit(): Promise<void> {
		await Promise.reject('not implemented');
	}

J
Joao Moreno 已提交
405 406
	@CommandCenter.Command('git.checkout')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
407 408
	async checkout(): Promise<void> {
		const config = workspace.getConfiguration('git');
J
Joao Moreno 已提交
409
		const checkoutType = config.get<string>('checkoutType') || 'all';
J
Joao Moreno 已提交
410 411 412 413 414 415 416 417 418 419 420 421
		const includeTags = checkoutType === 'all' || checkoutType === 'tags';
		const includeRemotes = checkoutType === 'all' || checkoutType === 'remote';

		const heads = this.model.refs.filter(ref => ref.type === RefType.Head)
			.map(ref => new CheckoutItem(ref));

		const tags = (includeTags ? this.model.refs.filter(ref => ref.type === RefType.Tag) : [])
			.map(ref => new CheckoutTagItem(ref));

		const remoteHeads = (includeRemotes ? this.model.refs.filter(ref => ref.type === RefType.RemoteHead) : [])
			.map(ref => new CheckoutRemoteHeadItem(ref));

J
Joao Moreno 已提交
422 423 424
		const picks = [...heads, ...tags, ...remoteHeads];
		const placeHolder = 'Select a ref to checkout';
		const choice = await window.showQuickPick<CheckoutItem>(picks, { placeHolder });
J
Joao Moreno 已提交
425 426 427 428 429 430

		if (!choice) {
			return;
		}

		await choice.run(this.model);
J
Joao Moreno 已提交
431 432
	}

J
Joao Moreno 已提交
433
	@CommandCenter.Command('git.branch')
J
Joao Moreno 已提交
434
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
435 436
	async branch(): Promise<void> {
		const result = await window.showInputBox({
J
Joao Moreno 已提交
437 438
			placeHolder: localize('branch name', "Branch name"),
			prompt: localize('provide branch name', "Please provide a branch name")
J
Joao Moreno 已提交
439
		});
J
Joao Moreno 已提交
440

J
Joao Moreno 已提交
441 442 443
		if (!result) {
			return;
		}
J
Joao Moreno 已提交
444

J
Joao Moreno 已提交
445 446
		const name = result.replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$/g, '-');
		await this.model.branch(name);
J
Joao Moreno 已提交
447 448 449 450 451
	}

	@CommandCenter.Command('git.pull')
	@CommandCenter.CatchErrors
	async pull(): Promise<void> {
J
Joao Moreno 已提交
452 453 454 455 456 457 458 459
		const remotes = this.model.remotes;

		if (remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to pull', "Your repository has no remotes configured to pull from."));
			return;
		}

		await this.model.pull();
J
Joao Moreno 已提交
460 461 462 463 464
	}

	@CommandCenter.Command('git.pullRebase')
	@CommandCenter.CatchErrors
	async pullRebase(): Promise<void> {
J
Joao Moreno 已提交
465 466 467 468 469 470 471 472
		const remotes = this.model.remotes;

		if (remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to pull', "Your repository has no remotes configured to pull from."));
			return;
		}

		await this.model.pull(true);
J
Joao Moreno 已提交
473 474
	}

J
Joao Moreno 已提交
475 476 477
	@CommandCenter.Command('git.push')
	@CommandCenter.CatchErrors
	async push(): Promise<void> {
J
Joao Moreno 已提交
478 479 480 481 482 483 484 485
		const remotes = this.model.remotes;

		if (remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to push', "Your repository has no remotes configured to push to."));
			return;
		}

		await this.model.push();
J
Joao Moreno 已提交
486 487
	}

J
Joao Moreno 已提交
488 489 490
	@CommandCenter.Command('git.pushTo')
	@CommandCenter.CatchErrors
	async pushTo(): Promise<void> {
J
Joao Moreno 已提交
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
		const remotes = this.model.remotes;

		if (remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to push', "Your repository has no remotes configured to push to."));
			return;
		}

		if (!this.model.HEAD || !this.model.HEAD.name) {
			window.showWarningMessage(localize('nobranch', "Please check out a branch to push to a remote."));
			return;
		}

		const branchName = this.model.HEAD.name;
		const picks = remotes.map(r => ({ label: r.name, description: r.url }));
		const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
		const pick = await window.showQuickPick(picks, { placeHolder });

		if (!pick) {
			return;
		}

		this.model.push(pick.label, branchName);
J
Joao Moreno 已提交
513 514
	}

J
Joao Moreno 已提交
515 516
	@CommandCenter.Command('git.sync')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
517
	async sync(): Promise<void> {
J
Joao Moreno 已提交
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
		const HEAD = this.model.HEAD;

		if (!HEAD || !HEAD.upstream) {
			return;
		}

		const config = workspace.getConfiguration('git');
		const shouldPrompt = config.get<boolean>('confirmSync') === true;

		if (shouldPrompt) {
			const message = localize('sync is unpredictable', "This action will push and pull commits to and from '{0}'.", HEAD.upstream);
			const yes = localize('ok', "OK");
			const neverAgain = localize('never again', "OK, Never Show Again");
			const pick = await window.showWarningMessage(message, { modal: true }, yes, neverAgain);

			if (pick === neverAgain) {
				await config.update('confirmSync', false, true);
			} else if (pick !== yes) {
				return;
			}
		}

J
Joao Moreno 已提交
540 541 542
		await this.model.sync();
	}

J
Joao Moreno 已提交
543 544
	@CommandCenter.Command('git.publish')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
545
	async publish(): Promise<void> {
J
Joao Moreno 已提交
546 547 548 549 550 551 552
		const remotes = this.model.remotes;

		if (remotes.length === 0) {
			window.showWarningMessage(localize('no remotes to publish', "Your repository has no remotes configured to publish to."));
			return;
		}

J
Joao Moreno 已提交
553 554
		const branchName = this.model.HEAD && this.model.HEAD.name || '';
		const picks = this.model.remotes.map(r => r.name);
J
Joao Moreno 已提交
555
		const placeHolder = localize('pick remote', "Pick a remote to publish the branch '{0}' to:", branchName);
J
Joao Moreno 已提交
556 557 558 559 560 561 562 563 564
		const choice = await window.showQuickPick(picks, { placeHolder });

		if (!choice) {
			return;
		}

		await this.model.push(choice, branchName, { setUpstream: true });
	}

J
Joao Moreno 已提交
565
	@CommandCenter.Command('git.showOutput')
J
Joao Moreno 已提交
566 567 568 569
	showOutput(): void {
		this.outputChannel.show();
	}

J
Joao Moreno 已提交
570 571 572
	dispose(): void {
		this.disposables.forEach(d => d.dispose());
	}
J
Joao Moreno 已提交
573
}