commands.ts 11.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

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

J
Joao Moreno 已提交
18
	return scm.getResourceFromURI(uri);
J
Joao Moreno 已提交
19 20
}

J
Joao Moreno 已提交
21 22
function resolveGitResource(uri: Uri): Resource | undefined {
	const resource = resolveGitURI(uri);
J
Joao Moreno 已提交
23

J
Joao Moreno 已提交
24 25 26
	if (!(resource instanceof Resource)) {
		return;
	}
J
Joao Moreno 已提交
27

J
Joao Moreno 已提交
28
	return resource;
J
Joao Moreno 已提交
29 30
}

J
Joao Moreno 已提交
31 32 33 34 35 36 37 38 39 40 41 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 68 69
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 {

	get description(): string { return `Tag at ${this.shortCommit}`; }
}

class CheckoutRemoteHeadItem extends CheckoutItem {

	get description(): string { return `Remote branch at ${this.shortCommit}`; }

	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 已提交
70
export class CommandCenter {
J
Joao Moreno 已提交
71

J
Joao Moreno 已提交
72 73 74 75 76 77 78 79 80 81 82 83 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
	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 => {
				if (err.gitErrorCode) {
					let message: string;

					switch (err.gitErrorCode) {
						case 'DirtyWorkTree':
							message = 'Please clean your repository working tree before checkout.';
							break;
						default:
							message = (err.stderr || err.message).replace(/^error: /, '');
							break;
					}

					const outputChannel = this.outputChannel as OutputChannel;
					const openOutputChannelChoice = 'Open Git Log';
					const choice = await window.showErrorMessage(message, openOutputChannelChoice);

					if (choice === openOutputChannelChoice) {
						outputChannel.show();
					}
				} else if (err.message) {
					window.showErrorMessage(err.message);
					console.error(err);
				} else {
					console.error(err);
				}
			});
		};
	}

	private disposables: Disposable[];
J
Joao Moreno 已提交
122

J
Joao Moreno 已提交
123
	constructor(private model: Model, private outputChannel: OutputChannel) {
J
Joao Moreno 已提交
124 125
		this.disposables = CommandCenter.Commands
			.map(({ commandId, method }) => commands.registerCommand(commandId, method, this));
J
Joao Moreno 已提交
126 127
	}

J
Joao Moreno 已提交
128 129
	@CommandCenter.Command('git.refresh')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
130
	async refresh(): Promise<void> {
J
Joao Moreno 已提交
131
		await this.model.update();
J
Joao Moreno 已提交
132
	}
J
Joao Moreno 已提交
133

J
Joao Moreno 已提交
134 135
	@CommandCenter.Command('git.openChange')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
136
	async openChange(uri: Uri): Promise<void> {
J
Joao Moreno 已提交
137
		const resource = resolveGitResource(uri);
J
Joao Moreno 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175

		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);
				const query = indexStatus ? '~' : 'HEAD';
				return resource.uri.with({ scheme: 'git', query });
		}
J
Joao Moreno 已提交
176
	}
J
Joao Moreno 已提交
177

J
Joao Moreno 已提交
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
	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 已提交
213 214
	@CommandCenter.Command('git.openFile')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
215
	async openFile(uri: Uri): Promise<void> {
J
Joao Moreno 已提交
216
		const resource = resolveGitResource(uri);
J
Joao Moreno 已提交
217 218 219 220 221 222

		if (!resource) {
			return;
		}

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

J
Joao Moreno 已提交
225 226
	@CommandCenter.Command('git.stage')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
227 228
	async stage(uri: Uri): Promise<void> {
		const resource = resolveGitResource(uri);
J
Joao Moreno 已提交
229

J
Joao Moreno 已提交
230 231 232
		if (!resource) {
			return;
		}
J
Joao Moreno 已提交
233

J
Joao Moreno 已提交
234
		return await this.model.stage(resource);
J
Joao Moreno 已提交
235 236
	}

J
Joao Moreno 已提交
237 238
	@CommandCenter.Command('git.stageAll')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
239 240 241
	async stageAll(): Promise<void> {
		return await this.model.stage();
	}
J
Joao Moreno 已提交
242

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

J
Joao Moreno 已提交
248
		if (!resource) {
J
Joao Moreno 已提交
249 250 251
			return;
		}

J
Joao Moreno 已提交
252 253 254
		return await this.model.unstage(resource);
	}

J
Joao Moreno 已提交
255 256
	@CommandCenter.Command('git.unstageAll')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
257 258 259
	async unstageAll(): Promise<void> {
		return await this.model.unstage();
	}
J
Joao Moreno 已提交
260

J
Joao Moreno 已提交
261 262
	@CommandCenter.Command('git.clean')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
263 264 265 266
	async clean(uri: Uri): Promise<void> {
		const resource = resolveGitResource(uri);

		if (!resource) {
J
Joao Moreno 已提交
267 268
			return;
		}
J
Joao Moreno 已提交
269

J
Joao Moreno 已提交
270 271 272 273
		const basename = path.basename(resource.uri.fsPath);
		const message = `Are you sure you want to clean changes in ${basename}?`;
		const yes = 'Yes';
		const no = 'No, keep them';
J
Joao Moreno 已提交
274
		const pick = await window.showQuickPick([yes, no], { placeHolder: message });
J
Joao Moreno 已提交
275

J
Joao Moreno 已提交
276 277 278 279 280 281
		if (pick !== yes) {
			return;
		}

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

J
Joao Moreno 已提交
283 284
	@CommandCenter.Command('git.cleanAll')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
285 286 287 288
	async cleanAll(): Promise<void> {
		const message = `Are you sure you want to clean all changes?`;
		const yes = 'Yes';
		const no = 'No, keep them';
J
Joao Moreno 已提交
289
		const pick = await window.showQuickPick([yes, no], { placeHolder: message });
J
Joao Moreno 已提交
290 291 292 293 294 295 296 297

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

		return await this.model.clean(...this.model.workingTreeGroup.resources);
	}

J
Joao Moreno 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
	@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 已提交
328 329
	@CommandCenter.Command('git.checkout')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
	async checkout(): Promise<void> {
		const config = workspace.getConfiguration('git');
		const checkoutType = config.get<string>('checkoutType');
		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 已提交
345 346 347
		const picks = [...heads, ...tags, ...remoteHeads];
		const placeHolder = 'Select a ref to checkout';
		const choice = await window.showQuickPick<CheckoutItem>(picks, { placeHolder });
J
Joao Moreno 已提交
348 349 350 351 352 353

		if (!choice) {
			return;
		}

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

J
Joao Moreno 已提交
356
	@CommandCenter.Command('git.branch')
J
Joao Moreno 已提交
357
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
358 359 360 361 362
	async branch(): Promise<void> {
		const result = await window.showInputBox({
			placeHolder: 'Branch name',
			prompt: 'Please provide a branch name'
		});
J
Joao Moreno 已提交
363

J
Joao Moreno 已提交
364 365 366
		if (!result) {
			return;
		}
J
Joao Moreno 已提交
367

J
Joao Moreno 已提交
368 369
		const name = result.replace(/^\.|\/\.|\.\.|~|\^|:|\/$|\.lock$|\.lock\/|\\|\*|\s|^\s*$|\.$/g, '-');
		await this.model.branch(name);
J
Joao Moreno 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383
	}

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

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

J
Joao Moreno 已提交
384 385 386 387 388 389
	@CommandCenter.Command('git.push')
	@CommandCenter.CatchErrors
	async push(): Promise<void> {
		await Promise.reject('not implemented');
	}

J
Joao Moreno 已提交
390 391 392 393 394 395
	@CommandCenter.Command('git.pushTo')
	@CommandCenter.CatchErrors
	async pushTo(): Promise<void> {
		await Promise.reject('not implemented');
	}

J
Joao Moreno 已提交
396 397
	@CommandCenter.Command('git.sync')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
398 399 400 401
	async sync(): Promise<void> {
		await this.model.sync();
	}

J
Joao Moreno 已提交
402 403
	@CommandCenter.Command('git.publish')
	@CommandCenter.CatchErrors
J
Joao Moreno 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416
	async publish(): Promise<void> {
		const branchName = this.model.HEAD && this.model.HEAD.name || '';
		const picks = this.model.remotes.map(r => r.name);
		const placeHolder = `Pick a remote to publish the branch '${branchName}' to:`;
		const choice = await window.showQuickPick(picks, { placeHolder });

		if (!choice) {
			return;
		}

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

J
Joao Moreno 已提交
417
	@CommandCenter.Command('git.showOutput')
J
Joao Moreno 已提交
418 419 420 421
	showOutput(): void {
		this.outputChannel.show();
	}

J
Joao Moreno 已提交
422 423 424
	dispose(): void {
		this.disposables.forEach(d => d.dispose());
	}
J
Joao Moreno 已提交
425
}