git.ts 23.4 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5 6 7 8 9
/*---------------------------------------------------------------------------------------------
 *  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 fs from 'fs';
import * as path from 'path';
J
Joao Moreno 已提交
10
import * as os from 'os';
J
Joao Moreno 已提交
11
import * as cp from 'child_process';
12
import { EventEmitter } from 'events';
13
import iconv = require('iconv-lite');
J
Joao Moreno 已提交
14
import { assign, uniqBy, groupBy, denodeify, IDisposable, toDisposable, dispose, mkdirp } from './util';
J
Joao Moreno 已提交
15

J
Joao Moreno 已提交
16 17
const readdir = denodeify<string[]>(fs.readdir);
const readfile = denodeify<string>(fs.readFile);
J
Joao Moreno 已提交
18 19 20 21 22 23

export interface IGit {
	path: string;
	version: string;
}

J
Joao Moreno 已提交
24
export interface PushOptions {
J
Joao Moreno 已提交
25 26 27 28 29 30 31 32 33 34
	setUpstream?: boolean;
}

export interface IFileStatus {
	x: string;
	y: string;
	path: string;
	rename?: string;
}

J
Joao Moreno 已提交
35
export interface Remote {
J
Joao Moreno 已提交
36 37 38 39 40 41 42 43 44 45
	name: string;
	url: string;
}

export enum RefType {
	Head,
	RemoteHead,
	Tag
}

J
Joao Moreno 已提交
46
export interface Ref {
J
Joao Moreno 已提交
47 48 49 50 51 52
	type: RefType;
	name?: string;
	commit?: string;
	remote?: string;
}

J
Joao Moreno 已提交
53
export interface Branch extends Ref {
J
Joao Moreno 已提交
54 55 56 57 58
	upstream?: string;
	ahead?: number;
	behind?: number;
}

J
Joao Moreno 已提交
59 60 61 62 63 64 65 66
function parseVersion(raw: string): string {
	return raw.replace(/^git version /, '');
}

function findSpecificGit(path: string): Promise<IGit> {
	return new Promise<IGit>((c, e) => {
		const buffers: Buffer[] = [];
		const child = cp.spawn(path, ['--version']);
67
		child.stdout.on('data', (b: Buffer) => buffers.push(b));
J
Joao Moreno 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
		child.on('error', e);
		child.on('exit', code => code ? e(new Error('Not found')) : c({ path, version: parseVersion(Buffer.concat(buffers).toString('utf8').trim()) }));
	});
}

function findGitDarwin(): Promise<IGit> {
	return new Promise<IGit>((c, e) => {
		cp.exec('which git', (err, gitPathBuffer) => {
			if (err) {
				return e('git not found');
			}

			const path = gitPathBuffer.toString().replace(/^\s+|\s+$/g, '');

			function getVersion(path: string) {
				// make sure git executes
84
				cp.exec('git --version', (err, stdout: Buffer) => {
J
Joao Moreno 已提交
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 126 127 128 129 130 131 132 133 134 135
					if (err) {
						return e('git not found');
					}

					return c({ path, version: parseVersion(stdout.toString('utf8').trim()) });
				});
			}

			if (path !== '/usr/bin/git') {
				return getVersion(path);
			}

			// must check if XCode is installed
			cp.exec('xcode-select -p', (err: any) => {
				if (err && err.code === 2) {
					// git is not installed, and launching /usr/bin/git
					// will prompt the user to install it

					return e('git not found');
				}

				getVersion(path);
			});
		});
	});
}

function findSystemGitWin32(base: string): Promise<IGit> {
	if (!base) {
		return Promise.reject<IGit>('Not found');
	}

	return findSpecificGit(path.join(base, 'Git', 'cmd', 'git.exe'));
}

function findGitHubGitWin32(): Promise<IGit> {
	const github = path.join(process.env['LOCALAPPDATA'], 'GitHub');

	return readdir(github).then(children => {
		const git = children.filter(child => /^PortableGit/.test(child))[0];

		if (!git) {
			return Promise.reject<IGit>('Not found');
		}

		return findSpecificGit(path.join(github, git, 'cmd', 'git.exe'));
	});
}

function findGitWin32(): Promise<IGit> {
	return findSystemGitWin32(process.env['ProgramW6432'])
J
Joao Moreno 已提交
136 137 138 139
		.then(void 0, () => findSystemGitWin32(process.env['ProgramFiles(x86)']))
		.then(void 0, () => findSystemGitWin32(process.env['ProgramFiles']))
		.then(void 0, () => findSpecificGit('git'))
		.then(void 0, () => findGitHubGitWin32());
J
Joao Moreno 已提交
140 141
}

J
Joao Moreno 已提交
142
export function findGit(hint: string | undefined): Promise<IGit> {
J
Joao Moreno 已提交
143 144
	var first = hint ? findSpecificGit(hint) : Promise.reject<IGit>(null);

J
Joao Moreno 已提交
145
	return first.then(void 0, () => {
J
Joao Moreno 已提交
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
		switch (process.platform) {
			case 'darwin': return findGitDarwin();
			case 'win32': return findGitWin32();
			default: return findSpecificGit('git');
		}
	});
}


export interface IExecutionResult {
	exitCode: number;
	stdout: string;
	stderr: string;
}

161
export async function exec(child: cp.ChildProcess, encoding: string = 'utf8'): Promise<IExecutionResult> {
J
Joao Moreno 已提交
162 163 164 165 166 167 168 169 170 171 172 173
	const disposables: IDisposable[] = [];

	const once = (ee: NodeJS.EventEmitter, name: string, fn: Function) => {
		ee.once(name, fn);
		disposables.push(toDisposable(() => ee.removeListener(name, fn)));
	};

	const on = (ee: NodeJS.EventEmitter, name: string, fn: Function) => {
		ee.on(name, fn);
		disposables.push(toDisposable(() => ee.removeListener(name, fn)));
	};

J
Joao Moreno 已提交
174
	const [exitCode, stdout, stderr] = await Promise.all<any>([
J
Joao Moreno 已提交
175 176 177 178 179
		new Promise<number>((c, e) => {
			once(child, 'error', e);
			once(child, 'exit', c);
		}),
		new Promise<string>(c => {
180
			const buffers: Buffer[] = [];
J
Joao Moreno 已提交
181
			on(child.stdout, 'data', b => buffers.push(b));
J
Joao Moreno 已提交
182
			once(child.stdout, 'close', () => c(iconv.decode(Buffer.concat(buffers), encoding)));
J
Joao Moreno 已提交
183 184
		}),
		new Promise<string>(c => {
185
			const buffers: Buffer[] = [];
J
Joao Moreno 已提交
186
			on(child.stderr, 'data', b => buffers.push(b));
J
Joao Moreno 已提交
187
			once(child.stderr, 'close', () => c(Buffer.concat(buffers).toString('utf8')));
J
Joao Moreno 已提交
188
		})
J
Joao Moreno 已提交
189
	]);
J
Joao Moreno 已提交
190

J
Joao Moreno 已提交
191 192 193
	dispose(disposables);

	return { exitCode, stdout, stderr };
J
Joao Moreno 已提交
194 195 196 197 198 199 200 201 202 203 204 205 206 207
}

export interface IGitErrorData {
	error?: Error;
	message?: string;
	stdout?: string;
	stderr?: string;
	exitCode?: number;
	gitErrorCode?: string;
	gitCommand?: string;
}

export class GitError {

J
Joao Moreno 已提交
208
	error?: Error;
J
Joao Moreno 已提交
209
	message: string;
J
Joao Moreno 已提交
210 211 212 213 214
	stdout?: string;
	stderr?: string;
	exitCode?: number;
	gitErrorCode?: string;
	gitCommand?: string;
J
Joao Moreno 已提交
215 216 217 218 219 220

	constructor(data: IGitErrorData) {
		if (data.error) {
			this.error = data.error;
			this.message = data.error.message;
		} else {
J
Joao Moreno 已提交
221
			this.error = void 0;
J
Joao Moreno 已提交
222 223 224
		}

		this.message = this.message || data.message || 'Git error';
J
Joao Moreno 已提交
225 226 227 228 229
		this.stdout = data.stdout;
		this.stderr = data.stderr;
		this.exitCode = data.exitCode;
		this.gitErrorCode = data.gitErrorCode;
		this.gitCommand = data.gitCommand;
J
Joao Moreno 已提交
230 231 232 233 234 235 236 237 238
	}

	toString(): string {
		let result = this.message + ' ' + JSON.stringify({
			exitCode: this.exitCode,
			gitErrorCode: this.gitErrorCode,
			gitCommand: this.gitCommand,
			stdout: this.stdout,
			stderr: this.stderr
J
Joao Moreno 已提交
239
		}, [], 2);
J
Joao Moreno 已提交
240 241 242 243 244 245 246 247 248 249 250 251

		if (this.error) {
			result += (<any>this.error).stack;
		}

		return result;
	}
}

export interface IGitOptions {
	gitPath: string;
	version: string;
252
	env?: any;
J
Joao Moreno 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
}

export const GitErrorCodes = {
	BadConfigFile: 'BadConfigFile',
	AuthenticationFailed: 'AuthenticationFailed',
	NoUserNameConfigured: 'NoUserNameConfigured',
	NoUserEmailConfigured: 'NoUserEmailConfigured',
	NoRemoteRepositorySpecified: 'NoRemoteRepositorySpecified',
	NotAGitRepository: 'NotAGitRepository',
	NotAtRepositoryRoot: 'NotAtRepositoryRoot',
	Conflict: 'Conflict',
	UnmergedChanges: 'UnmergedChanges',
	PushRejected: 'PushRejected',
	RemoteConnectionError: 'RemoteConnectionError',
	DirtyWorkTree: 'DirtyWorkTree',
	CantOpenResource: 'CantOpenResource',
	GitNotFound: 'GitNotFound',
	CantCreatePipe: 'CantCreatePipe',
	CantAccessRemote: 'CantAccessRemote',
272 273
	RepositoryNotFound: 'RepositoryNotFound',
	RepositoryIsLocked: 'RepositoryIsLocked'
J
Joao Moreno 已提交
274 275 276 277
};

export class Git {

J
Joao Moreno 已提交
278 279
	private gitPath: string;
	private version: string;
280
	private env: any;
J
Joao Moreno 已提交
281

282 283
	private _onOutput = new EventEmitter();
	get onOutput(): EventEmitter { return this._onOutput; }
J
Joao Moreno 已提交
284

J
Joao Moreno 已提交
285 286 287
	constructor(options: IGitOptions) {
		this.gitPath = options.gitPath;
		this.version = options.version;
288
		this.env = options.env || {};
J
Joao Moreno 已提交
289 290
	}

291 292
	open(repository: string): Repository {
		return new Repository(this, repository);
J
Joao Moreno 已提交
293 294
	}

J
Joao Moreno 已提交
295 296 297 298 299
	async init(repository: string): Promise<void> {
		await this.exec(repository, ['init']);
		return;
	}

J
Joao Moreno 已提交
300 301 302 303
	async clone(url: string, parentPath: string): Promise<string> {
		const folderName = url.replace(/^.*\//, '').replace(/\.git$/, '') || 'repository';
		const folderPath = path.join(parentPath, folderName);

J
Joao Moreno 已提交
304
		await mkdirp(parentPath);
J
Joao Moreno 已提交
305 306 307 308
		await this.exec(parentPath, ['clone', url, folderPath]);
		return folderPath;
	}

J
Joao Moreno 已提交
309 310 311 312 313
	async getRepositoryRoot(path: string): Promise<string> {
		const result = await this.exec(path, ['rev-parse', '--show-toplevel']);
		return result.stdout.trim();
	}

J
Joao Moreno 已提交
314
	async exec(cwd: string, args: string[], options: any = {}): Promise<IExecutionResult> {
J
Joao Moreno 已提交
315
		options = assign({ cwd }, options || {});
J
Joao Moreno 已提交
316
		return await this._exec(args, options);
J
Joao Moreno 已提交
317 318 319
	}

	stream(cwd: string, args: string[], options: any = {}): cp.ChildProcess {
J
Joao Moreno 已提交
320
		options = assign({ cwd }, options || {});
J
Joao Moreno 已提交
321
		return this.spawn(args, options);
J
Joao Moreno 已提交
322 323
	}

J
Joao Moreno 已提交
324 325
	private async _exec(args: string[], options: any = {}): Promise<IExecutionResult> {
		const child = this.spawn(args, options);
J
Joao Moreno 已提交
326 327 328 329 330

		if (options.input) {
			child.stdin.end(options.input, 'utf8');
		}

331
		const result = await exec(child, options.encoding);
J
Joao Moreno 已提交
332 333 334 335

		if (result.exitCode) {
			let gitErrorCode: string | undefined = void 0;

336 337 338
			if (/Another git process seems to be running in this repository|If no other git process is currently running/.test(result.stderr)) {
				gitErrorCode = GitErrorCodes.RepositoryIsLocked;
			} else if (/Authentication failed/.test(result.stderr)) {
J
Joao Moreno 已提交
339 340 341 342 343 344 345 346 347 348 349 350
				gitErrorCode = GitErrorCodes.AuthenticationFailed;
			} else if (/Not a git repository/.test(result.stderr)) {
				gitErrorCode = GitErrorCodes.NotAGitRepository;
			} else if (/bad config file/.test(result.stderr)) {
				gitErrorCode = GitErrorCodes.BadConfigFile;
			} else if (/cannot make pipe for command substitution|cannot create standard input pipe/.test(result.stderr)) {
				gitErrorCode = GitErrorCodes.CantCreatePipe;
			} else if (/Repository not found/.test(result.stderr)) {
				gitErrorCode = GitErrorCodes.RepositoryNotFound;
			} else if (/unable to access/.test(result.stderr)) {
				gitErrorCode = GitErrorCodes.CantAccessRemote;
			}
J
Joao Moreno 已提交
351

J
Joao Moreno 已提交
352
			if (options.log !== false) {
J
Joao Moreno 已提交
353
				this.log(`${result.stderr}\n`);
J
Joao Moreno 已提交
354 355
			}

J
Joao Moreno 已提交
356 357 358 359 360 361 362 363 364 365 366
			return Promise.reject<IExecutionResult>(new GitError({
				message: 'Failed to execute git',
				stdout: result.stdout,
				stderr: result.stderr,
				exitCode: result.exitCode,
				gitErrorCode,
				gitCommand: args[0]
			}));
		}

		return result;
J
Joao Moreno 已提交
367 368
	}

J
Joao Moreno 已提交
369
	spawn(args: string[], options: any = {}): cp.ChildProcess {
J
Joao Moreno 已提交
370 371 372 373 374 375 376 377 378 379 380 381
		if (!this.gitPath) {
			throw new Error('git could not be found in the system.');
		}

		if (!options) {
			options = {};
		}

		if (!options.stdio && !options.input) {
			options.stdio = ['ignore', null, null]; // Unless provided, ignore stdin and leave default streams for stdout and stderr
		}

382
		options.env = assign({}, process.env, this.env, options.env || {}, {
J
Joao Moreno 已提交
383
			VSCODE_GIT_COMMAND: args[0],
J
Joao Moreno 已提交
384
			LC_ALL: 'en_US',
J
Joao Moreno 已提交
385 386
			LANG: 'en_US.UTF-8'
		});
J
Joao Moreno 已提交
387 388

		if (options.log !== false) {
J
Joao Moreno 已提交
389
			this.log(`git ${args.join(' ')}\n`);
J
Joao Moreno 已提交
390 391 392 393 394 395
		}

		return cp.spawn(this.gitPath, args, options);
	}

	private log(output: string): void {
396
		this._onOutput.emit('log', output);
J
Joao Moreno 已提交
397
	}
J
Joao Moreno 已提交
398 399
}

J
Joao Moreno 已提交
400
export interface Commit {
J
Joao Moreno 已提交
401 402 403 404
	hash: string;
	message: string;
}

405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
export class GitStatusParser {

	private lastRaw = '';
	private result: IFileStatus[] = [];

	get status(): IFileStatus[] {
		return this.result;
	}

	update(raw: string): void {
		let i = 0;
		let nextI: number | undefined;

		raw = this.lastRaw + raw;

		while ((nextI = this.parseEntry(raw, i)) !== undefined) {
			i = nextI;
		}

		this.lastRaw = raw.substr(i);
	}

	private parseEntry(raw: string, i: number): number | undefined {
		if (i + 4 >= raw.length) {
			return;
		}

		let lastIndex: number;
		const entry: IFileStatus = {
			x: raw.charAt(i++),
			y: raw.charAt(i++),
			rename: undefined,
			path: ''
		};

		// space
		i++;

		if (entry.x === 'R') {
			lastIndex = raw.indexOf('\0', i);

			if (lastIndex === -1) {
				return;
			}

			entry.rename = raw.substring(i, lastIndex);
			i = lastIndex + 1;
		}

		lastIndex = raw.indexOf('\0', i);

		if (lastIndex === -1) {
			return;
		}

		entry.path = raw.substring(i, lastIndex);

		// If path ends with slash, it must be a nested git repo
		if (entry.path[entry.path.length - 1] !== '/') {
			this.result.push(entry);
		}

		return lastIndex + 1;
	}
}

J
Joao Moreno 已提交
471 472 473 474
export class Repository {

	constructor(
		private _git: Git,
475
		private repositoryRoot: string
J
Joao Moreno 已提交
476 477 478 479 480 481
	) { }

	get git(): Git {
		return this._git;
	}

J
Joao Moreno 已提交
482 483
	get root(): string {
		return this.repositoryRoot;
J
Joao Moreno 已提交
484 485 486 487
	}

	// TODO@Joao: rename to exec
	async run(args: string[], options: any = {}): Promise<IExecutionResult> {
J
Joao Moreno 已提交
488
		return await this.git.exec(this.repositoryRoot, args, options);
J
Joao Moreno 已提交
489 490 491
	}

	stream(args: string[], options: any = {}): cp.ChildProcess {
J
Joao Moreno 已提交
492
		return this.git.stream(this.repositoryRoot, args, options);
J
Joao Moreno 已提交
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
	}

	spawn(args: string[], options: any = {}): cp.ChildProcess {
		return this.git.spawn(args, options);
	}

	async config(scope: string, key: string, value: any, options: any): Promise<string> {
		const args = ['config'];

		if (scope) {
			args.push('--' + scope);
		}

		args.push(key);

		if (value) {
			args.push(value);
		}

		const result = await this.run(args, options);
		return result.stdout;
	}

	async buffer(object: string): Promise<string> {
		const child = this.stream(['show', object]);

		if (!child.stdout) {
520
			return Promise.reject<string>('Can\'t open file from git');
J
Joao Moreno 已提交
521 522 523 524
		}

		return await this.doBuffer(object);

J
Joao Moreno 已提交
525
		// TODO@joao
J
Joao Moreno 已提交
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543
		// return new Promise((c, e) => {
		// detectMimesFromStream(child.stdout, null, (err, result) => {
		// 	if (err) {
		// 		e(err);
		// 	} else if (isBinaryMime(result.mimes)) {
		// 		e(<IFileOperationResult>{
		// 			message: localize('fileBinaryError', "File seems to be binary and cannot be opened as text"),
		// 			fileOperationResult: FileOperationResult.FILE_IS_BINARY
		// 		});
		// 	} else {
		// c(this.doBuffer(object));
		// 	}
		// });
		// });
	}

	private async doBuffer(object: string): Promise<string> {
		const child = this.stream(['show', object]);
J
Joao Moreno 已提交
544
		const { exitCode, stdout } = await exec(child);
J
Joao Moreno 已提交
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606

		if (exitCode) {
			return Promise.reject<string>(new GitError({
				message: 'Could not buffer object.',
				exitCode
			}));
		}

		return stdout;
	}

	async add(paths: string[]): Promise<void> {
		const args = ['add', '-A', '--'];

		if (paths && paths.length) {
			args.push.apply(args, paths);
		} else {
			args.push('.');
		}

		await this.run(args);
	}

	async stage(path: string, data: string): Promise<void> {
		const child = this.stream(['hash-object', '--stdin', '-w'], { stdio: [null, null, null] });
		child.stdin.end(data, 'utf8');

		const { exitCode, stdout } = await exec(child);

		if (exitCode) {
			throw new GitError({
				message: 'Could not hash object.',
				exitCode: exitCode
			});
		}

		await this.run(['update-index', '--cacheinfo', '100644', stdout, path]);
	}

	async checkout(treeish: string, paths: string[]): Promise<void> {
		const args = ['checkout', '-q'];

		if (treeish) {
			args.push(treeish);
		}

		if (paths && paths.length) {
			args.push('--');
			args.push.apply(args, paths);
		}

		try {
			await this.run(args);
		} catch (err) {
			if (/Please, commit your changes or stash them/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.DirtyWorkTree;
			}

			throw err;
		}
	}

J
Joao Moreno 已提交
607
	async commit(message: string, opts: { all?: boolean, amend?: boolean, signoff?: boolean } = Object.create(null)): Promise<void> {
J
Joao Moreno 已提交
608 609
		const args = ['commit', '--quiet', '--allow-empty-message', '--file', '-'];

J
Joao Moreno 已提交
610
		if (opts.all) {
J
Joao Moreno 已提交
611 612 613
			args.push('--all');
		}

J
Joao Moreno 已提交
614
		if (opts.amend) {
J
Joao Moreno 已提交
615 616 617
			args.push('--amend');
		}

J
Joao Moreno 已提交
618
		if (opts.signoff) {
J
Joao Moreno 已提交
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
			args.push('--signoff');
		}

		try {
			await this.run(args, { input: message || '' });
		} catch (commitErr) {
			if (/not possible because you have unmerged files/.test(commitErr.stderr || '')) {
				commitErr.gitErrorCode = GitErrorCodes.UnmergedChanges;
				throw commitErr;
			}

			try {
				await this.run(['config', '--get-all', 'user.name']);
			} catch (err) {
				err.gitErrorCode = GitErrorCodes.NoUserNameConfigured;
				throw err;
			}

			try {
				await this.run(['config', '--get-all', 'user.email']);
			} catch (err) {
				err.gitErrorCode = GitErrorCodes.NoUserEmailConfigured;
				throw err;
			}

			throw commitErr;
		}
	}

	async branch(name: string, checkout: boolean): Promise<void> {
		const args = checkout ? ['checkout', '-q', '-b', name] : ['branch', '-q', name];
		await this.run(args);
	}

	async clean(paths: string[]): Promise<void> {
J
Joao Moreno 已提交
654 655 656
		const pathsByGroup = groupBy(paths, p => path.dirname(p));
		const groups = Object.keys(pathsByGroup).map(k => pathsByGroup[k]);
		const tasks = groups.map(paths => () => this.run(['clean', '-f', '-q', '--'].concat(paths)));
J
Joao Moreno 已提交
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756

		for (let task of tasks) {
			await task();
		}
	}

	async undo(): Promise<void> {
		await this.run(['clean', '-fd']);

		try {
			await this.run(['checkout', '--', '.']);
		} catch (err) {
			if (/did not match any file\(s\) known to git\./.test(err.stderr || '')) {
				return;
			}

			throw err;
		}
	}

	async reset(treeish: string, hard: boolean = false): Promise<void> {
		const args = ['reset'];

		if (hard) {
			args.push('--hard');
		}

		args.push(treeish);

		await this.run(args);
	}

	async revertFiles(treeish: string, paths: string[]): Promise<void> {
		const result = await this.run(['branch']);
		let args: string[];

		// In case there are no branches, we must use rm --cached
		if (!result.stdout) {
			args = ['rm', '--cached', '-r', '--'];
		} else {
			args = ['reset', '-q', treeish, '--'];
		}

		if (paths && paths.length) {
			args.push.apply(args, paths);
		} else {
			args.push('.');
		}

		try {
			await this.run(args);
		} catch (err) {
			// In case there are merge conflicts to be resolved, git reset will output
			// some "needs merge" data. We try to get around that.
			if (/([^:]+: needs merge\n)+/m.test(err.stdout || '')) {
				return;
			}

			throw err;
		}
	}

	async fetch(): Promise<void> {
		try {
			await this.run(['fetch']);
		} catch (err) {
			if (/No remote repository specified\./.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoRemoteRepositorySpecified;
			} else if (/Could not read from remote repository/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.RemoteConnectionError;
			}

			throw err;
		}
	}

	async pull(rebase?: boolean): Promise<void> {
		const args = ['pull'];

		if (rebase) {
			args.push('-r');
		}

		try {
			await this.run(args);
		} catch (err) {
			if (/^CONFLICT \([^)]+\): \b/m.test(err.stdout || '')) {
				err.gitErrorCode = GitErrorCodes.Conflict;
			} else if (/Please tell me who you are\./.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoUserNameConfigured;
			} else if (/Could not read from remote repository/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.RemoteConnectionError;
			} else if (/Pull is not possible because you have unmerged files|Cannot pull with rebase: You have unstaged changes|Your local changes to the following files would be overwritten|Please, commit your changes before you can merge/.test(err.stderr)) {
				err.gitErrorCode = GitErrorCodes.DirtyWorkTree;
			}

			throw err;
		}
	}

J
Joao Moreno 已提交
757
	async push(remote?: string, name?: string, options?: PushOptions): Promise<void> {
J
Joao Moreno 已提交
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
		const args = ['push'];

		if (options && options.setUpstream) {
			args.push('-u');
		}

		if (remote) {
			args.push(remote);
		}

		if (name) {
			args.push(name);
		}

		try {
			await this.run(args);
		} catch (err) {
			if (/^error: failed to push some refs to\b/m.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.PushRejected;
			} else if (/Could not read from remote repository/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.RemoteConnectionError;
			}

			throw err;
		}
	}

785 786
	getStatus(limit = 5000): Promise<{ status: IFileStatus[]; didHitLimit: boolean; }> {
		return new Promise<{ status: IFileStatus[]; didHitLimit: boolean; }>((c, e) => {
787 788
			const parser = new GitStatusParser();
			const child = this.stream(['status', '-z', '-u']);
789 790

			const onExit = exitCode => {
791 792 793
				if (exitCode !== 0) {
					e(new GitError({ message: 'Could not get git status.', exitCode }));
				}
J
Joao Moreno 已提交
794

795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813
				c({ status: parser.status, didHitLimit: false });
			};

			const onData = (raw: string) => {
				parser.update(raw);

				if (parser.status.length > 5000) {
					child.removeListener('exit', onExit);
					child.stdout.removeListener('data', onData);
					child.kill();

					c({ status: parser.status.slice(0, 5000), didHitLimit: true });
				}
			};

			child.stdout.setEncoding('utf8');
			child.stdout.on('data', onData);
			child.on('error', e);
			child.on('exit', onExit);
814
		});
J
Joao Moreno 已提交
815 816
	}

J
Joao Moreno 已提交
817
	async getHEAD(): Promise<Ref> {
J
Joao Moreno 已提交
818
		try {
J
Joao Moreno 已提交
819
			const result = await this.run(['symbolic-ref', '--short', 'HEAD']);
J
Joao Moreno 已提交
820 821 822 823 824 825 826

			if (!result.stdout) {
				throw new Error('Not in a branch');
			}

			return { name: result.stdout.trim(), commit: void 0, type: RefType.Head };
		} catch (err) {
J
Joao Moreno 已提交
827
			const result = await this.run(['rev-parse', 'HEAD']);
J
Joao Moreno 已提交
828 829 830 831 832 833 834 835 836

			if (!result.stdout) {
				throw new Error('Error parsing HEAD');
			}

			return { name: void 0, commit: result.stdout.trim(), type: RefType.Head };
		}
	}

J
Joao Moreno 已提交
837
	async getRefs(): Promise<Ref[]> {
J
Joao Moreno 已提交
838
		const result = await this.run(['for-each-ref', '--format', '%(refname) %(objectname)']);
J
Joao Moreno 已提交
839

J
Joao Moreno 已提交
840
		const fn = (line): Ref | null => {
J
Joao Moreno 已提交
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
			let match: RegExpExecArray | null;

			if (match = /^refs\/heads\/([^ ]+) ([0-9a-f]{40})$/.exec(line)) {
				return { name: match[1], commit: match[2], type: RefType.Head };
			} else if (match = /^refs\/remotes\/([^/]+)\/([^ ]+) ([0-9a-f]{40})$/.exec(line)) {
				return { name: `${match[1]}/${match[2]}`, commit: match[3], type: RefType.RemoteHead, remote: match[1] };
			} else if (match = /^refs\/tags\/([^ ]+) ([0-9a-f]{40})$/.exec(line)) {
				return { name: match[1], commit: match[2], type: RefType.Tag };
			}

			return null;
		};

		return result.stdout.trim().split('\n')
			.filter(line => !!line)
			.map(fn)
J
Joao Moreno 已提交
857
			.filter(ref => !!ref) as Ref[];
J
Joao Moreno 已提交
858 859
	}

J
Joao Moreno 已提交
860
	async getRemotes(): Promise<Remote[]> {
J
Joao Moreno 已提交
861
		const result = await this.run(['remote', '--verbose']);
J
Joao Moreno 已提交
862
		const regex = /^([^\s]+)\s+([^\s]+)\s/;
J
Joao Moreno 已提交
863
		const rawRemotes = result.stdout.trim().split('\n')
J
Joao Moreno 已提交
864 865 866
			.filter(b => !!b)
			.map(line => regex.exec(line))
			.filter(g => !!g)
J
Joao Moreno 已提交
867 868 869
			.map((groups: RegExpExecArray) => ({ name: groups[1], url: groups[2] }));

		return uniqBy(rawRemotes, remote => remote.name);
J
Joao Moreno 已提交
870 871
	}

J
Joao Moreno 已提交
872
	async getBranch(name: string): Promise<Branch> {
J
Joao Moreno 已提交
873 874 875 876
		if (name === 'HEAD') {
			return this.getHEAD();
		}

J
Joao Moreno 已提交
877
		const result = await this.run(['rev-parse', name]);
J
Joao Moreno 已提交
878 879

		if (!result.stdout) {
J
Joao Moreno 已提交
880
			return Promise.reject<Branch>(new Error('No such branch'));
J
Joao Moreno 已提交
881 882 883 884 885
		}

		const commit = result.stdout.trim();

		try {
J
Joao Moreno 已提交
886
			const res2 = await this.run(['rev-parse', '--symbolic-full-name', '--abbrev-ref', name + '@{u}']);
J
Joao Moreno 已提交
887 888
			const upstream = res2.stdout.trim();

J
Joao Moreno 已提交
889
			const res3 = await this.run(['rev-list', '--left-right', name + '...' + upstream]);
J
Joao Moreno 已提交
890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923

			let ahead = 0, behind = 0;
			let i = 0;

			while (i < res3.stdout.length) {
				switch (res3.stdout.charAt(i)) {
					case '<': ahead++; break;
					case '>': behind++; break;
					default: i++; break;
				}

				while (res3.stdout.charAt(i++) !== '\n') { /* no-op */ }
			}

			return { name, type: RefType.Head, commit, upstream, ahead, behind };
		} catch (err) {
			return { name, type: RefType.Head, commit };
		}
	}

	async getCommitTemplate(): Promise<string> {
		try {
			const result = await this.run(['config', '--get', 'commit.template']);

			if (!result.stdout) {
				return '';
			}

			// https://github.com/git/git/blob/3a0f269e7c82aa3a87323cb7ae04ac5f129f036b/path.c#L612
			const homedir = os.homedir();
			let templatePath = result.stdout.trim()
				.replace(/^~([^\/]*)\//, (_, user) => `${user ? path.join(path.dirname(homedir), user) : homedir}/`);

			if (!path.isAbsolute(templatePath)) {
J
Joao Moreno 已提交
924
				templatePath = path.join(this.repositoryRoot, templatePath);
J
Joao Moreno 已提交
925 926 927 928 929 930 931 932 933 934
			}

			const raw = await readfile(templatePath, 'utf8');
			return raw.replace(/^\s*#.*$\n?/gm, '').trim();

		} catch (err) {
			return '';
		}
	}

J
Joao Moreno 已提交
935
	async getCommit(ref: string): Promise<Commit> {
J
Joao Moreno 已提交
936 937 938 939
		const result = await this.run(['show', '-s', '--format=%H\n%B', ref]);
		const match = /^([0-9a-f]{40})\n([^]*)$/m.exec(result.stdout.trim());

		if (!match) {
J
Joao Moreno 已提交
940
			return Promise.reject<Commit>('bad commit format');
J
Joao Moreno 已提交
941 942 943 944
		}

		return { hash: match[1], message: match[2] };
	}
J
Joao Moreno 已提交
945
}