git.ts 39.0 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 * as which from 'which';
13
import { EventEmitter } from 'events';
14
import iconv = require('iconv-lite');
J
Joao Moreno 已提交
15
import * as filetype from 'file-type';
16
import { assign, groupBy, denodeify, IDisposable, toDisposable, dispose, mkdirp, readBytes, detectUnicodeEncoding, Encoding, onceEvent } from './util';
J
Joao Moreno 已提交
17
import { CancellationToken } from 'vscode';
J
Joao Moreno 已提交
18
import { detectEncoding } from './encoding';
J
Joao Moreno 已提交
19
import { Ref, RefType, Branch, Remote, GitErrorCodes } from './api/git';
J
Joao Moreno 已提交
20

21
const readfile = denodeify<string, string | null, string>(fs.readFile);
J
Joao Moreno 已提交
22 23 24 25 26 27

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

J
Joao Moreno 已提交
28 29 30 31 32 33 34
export interface IFileStatus {
	x: string;
	y: string;
	path: string;
	rename?: string;
}

35
export interface Stash {
J
Joao Moreno 已提交
36
	index: number;
37 38 39
	description: string;
}

J
Joao Moreno 已提交
40 41 42 43
interface MutableRemote extends Remote {
	fetchUrl?: string;
	pushUrl?: string;
	isReadOnly: boolean;
J
Joao Moreno 已提交
44 45
}

J
Joao Moreno 已提交
46 47 48 49
function parseVersion(raw: string): string {
	return raw.replace(/^git version /, '');
}

J
Joao Moreno 已提交
50
function findSpecificGit(path: string, onLookup: (path: string) => void): Promise<IGit> {
J
Joao Moreno 已提交
51
	return new Promise<IGit>((c, e) => {
J
Joao Moreno 已提交
52 53
		onLookup(path);

J
Joao Moreno 已提交
54 55
		const buffers: Buffer[] = [];
		const child = cp.spawn(path, ['--version']);
56
		child.stdout.on('data', (b: Buffer) => buffers.push(b));
J
Joao Moreno 已提交
57
		child.on('error', cpErrorHandler(e));
J
Joao Moreno 已提交
58 59 60 61
		child.on('exit', code => code ? e(new Error('Not found')) : c({ path, version: parseVersion(Buffer.concat(buffers).toString('utf8').trim()) }));
	});
}

J
Joao Moreno 已提交
62
function findGitDarwin(onLookup: (path: string) => void): Promise<IGit> {
J
Joao Moreno 已提交
63 64 65 66 67 68 69 70 71
	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) {
J
Joao Moreno 已提交
72 73
				onLookup(path);

J
Joao Moreno 已提交
74
				// make sure git executes
J
Joao 已提交
75
				cp.exec('git --version', (err, stdout) => {
J
Joao Moreno 已提交
76

J
Joao Moreno 已提交
77 78 79 80
					if (err) {
						return e('git not found');
					}

J
Joao 已提交
81
					return c({ path, version: parseVersion(stdout.trim()) });
J
Joao Moreno 已提交
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
				});
			}

			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);
			});
		});
	});
}

J
Joao Moreno 已提交
104
function findSystemGitWin32(base: string, onLookup: (path: string) => void): Promise<IGit> {
J
Joao Moreno 已提交
105 106 107 108
	if (!base) {
		return Promise.reject<IGit>('Not found');
	}

J
Joao Moreno 已提交
109
	return findSpecificGit(path.join(base, 'Git', 'cmd', 'git.exe'), onLookup);
J
Joao Moreno 已提交
110 111
}

112 113 114 115 116
function findGitWin32InPath(onLookup: (path: string) => void): Promise<IGit> {
	const whichPromise = new Promise<string>((c, e) => which('git.exe', (err, path) => err ? e(err) : c(path)));
	return whichPromise.then(path => findSpecificGit(path, onLookup));
}

J
Joao Moreno 已提交
117 118 119
function findGitWin32(onLookup: (path: string) => void): Promise<IGit> {
	return findSystemGitWin32(process.env['ProgramW6432'] as string, onLookup)
		.then(void 0, () => findSystemGitWin32(process.env['ProgramFiles(x86)'] as string, onLookup))
120 121 122
		.then(void 0, () => findSystemGitWin32(process.env['ProgramFiles'] as string, onLookup))
		.then(void 0, () => findSystemGitWin32(path.join(process.env['LocalAppData'] as string, 'Programs'), onLookup))
		.then(void 0, () => findGitWin32InPath(onLookup));
J
Joao Moreno 已提交
123 124
}

J
Joao Moreno 已提交
125
export function findGit(hint: string | undefined, onLookup: (path: string) => void): Promise<IGit> {
J
Joao Moreno 已提交
126
	const first = hint ? findSpecificGit(hint, onLookup) : Promise.reject<IGit>(null);
J
Joao Moreno 已提交
127

J
Joao Moreno 已提交
128 129 130
	return first
		.then(void 0, () => {
			switch (process.platform) {
J
Joao Moreno 已提交
131 132 133
				case 'darwin': return findGitDarwin(onLookup);
				case 'win32': return findGitWin32(onLookup);
				default: return findSpecificGit('git', onLookup);
J
Joao Moreno 已提交
134 135 136
			}
		})
		.then(null, () => Promise.reject(new Error('Git installation not found.')));
J
Joao Moreno 已提交
137 138
}

J
Joao Moreno 已提交
139
export interface IExecutionResult<T extends string | Buffer> {
J
Joao Moreno 已提交
140
	exitCode: number;
J
Joao Moreno 已提交
141
	stdout: T;
J
Joao Moreno 已提交
142 143 144
	stderr: string;
}

J
Joao Moreno 已提交
145 146 147 148 149 150 151 152 153 154 155 156 157 158
function cpErrorHandler(cb: (reason?: any) => void): (reason?: any) => void {
	return err => {
		if (/ENOENT/.test(err.message)) {
			err = new GitError({
				error: err,
				message: 'Failed to execute git (ENOENT)',
				gitErrorCode: GitErrorCodes.NotAGitRepository
			});
		}

		cb(err);
	};
}

J
Joao Moreno 已提交
159
export interface SpawnOptions extends cp.SpawnOptions {
J
Joao Moreno 已提交
160 161 162
	input?: string;
	encoding?: string;
	log?: boolean;
J
Joao Moreno 已提交
163
	cancellationToken?: CancellationToken;
J
Joao Moreno 已提交
164 165
}

J
Joao Moreno 已提交
166
async function exec(child: cp.ChildProcess, cancellationToken?: CancellationToken): Promise<IExecutionResult<Buffer>> {
J
Joao Moreno 已提交
167
	if (!child.stdout || !child.stderr) {
J
Joao Moreno 已提交
168 169 170 171 172
		throw new GitError({ message: 'Failed to get stdout or stderr from git process.' });
	}

	if (cancellationToken && cancellationToken.isCancellationRequested) {
		throw new GitError({ message: 'Cancelled' });
J
Joao Moreno 已提交
173 174
	}

J
Joao Moreno 已提交
175 176
	const disposables: IDisposable[] = [];

M
Matt Bierner 已提交
177
	const once = (ee: NodeJS.EventEmitter, name: string, fn: (...args: any[]) => void) => {
J
Joao Moreno 已提交
178 179 180 181
		ee.once(name, fn);
		disposables.push(toDisposable(() => ee.removeListener(name, fn)));
	};

M
Matt Bierner 已提交
182
	const on = (ee: NodeJS.EventEmitter, name: string, fn: (...args: any[]) => void) => {
J
Joao Moreno 已提交
183 184 185 186
		ee.on(name, fn);
		disposables.push(toDisposable(() => ee.removeListener(name, fn)));
	};

J
Joao Moreno 已提交
187
	let result = Promise.all<any>([
J
Joao Moreno 已提交
188
		new Promise<number>((c, e) => {
J
Joao Moreno 已提交
189
			once(child, 'error', cpErrorHandler(e));
J
Joao Moreno 已提交
190 191
			once(child, 'exit', c);
		}),
J
Joao Moreno 已提交
192
		new Promise<Buffer>(c => {
193
			const buffers: Buffer[] = [];
M
Matt Bierner 已提交
194
			on(child.stdout, 'data', (b: Buffer) => buffers.push(b));
J
Joao Moreno 已提交
195
			once(child.stdout, 'close', () => c(Buffer.concat(buffers)));
J
Joao Moreno 已提交
196 197
		}),
		new Promise<string>(c => {
198
			const buffers: Buffer[] = [];
M
Matt Bierner 已提交
199
			on(child.stderr, 'data', (b: Buffer) => buffers.push(b));
J
Joao Moreno 已提交
200
			once(child.stderr, 'close', () => c(Buffer.concat(buffers).toString('utf8')));
J
Joao Moreno 已提交
201
		})
J
Joao Moreno 已提交
202 203 204 205 206 207 208 209 210 211
	]) as Promise<[number, Buffer, string]>;

	if (cancellationToken) {
		const cancellationPromise = new Promise<[number, Buffer, string]>((_, e) => {
			onceEvent(cancellationToken.onCancellationRequested)(() => {
				try {
					child.kill();
				} catch (err) {
					// noop
				}
J
Joao Moreno 已提交
212

J
Joao Moreno 已提交
213 214 215 216 217 218
				e(new GitError({ message: 'Cancelled' }));
			});
		});

		result = Promise.race([result, cancellationPromise]);
	}
J
Joao Moreno 已提交
219

J
Joao Moreno 已提交
220 221 222 223 224 225
	try {
		const [exitCode, stdout, stderr] = await result;
		return { exitCode, stdout, stderr };
	} finally {
		dispose(disposables);
	}
J
Joao Moreno 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239
}

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

export class GitError {

J
Joao Moreno 已提交
240
	error?: Error;
J
Joao Moreno 已提交
241
	message: string;
J
Joao Moreno 已提交
242 243 244 245 246
	stdout?: string;
	stderr?: string;
	exitCode?: number;
	gitErrorCode?: string;
	gitCommand?: string;
J
Joao Moreno 已提交
247 248 249 250 251 252

	constructor(data: IGitErrorData) {
		if (data.error) {
			this.error = data.error;
			this.message = data.error.message;
		} else {
J
Joao Moreno 已提交
253
			this.error = void 0;
M
Matt Bierner 已提交
254
			this.message = '';
J
Joao Moreno 已提交
255 256 257
		}

		this.message = this.message || data.message || 'Git error';
J
Joao Moreno 已提交
258 259 260 261 262
		this.stdout = data.stdout;
		this.stderr = data.stderr;
		this.exitCode = data.exitCode;
		this.gitErrorCode = data.gitErrorCode;
		this.gitCommand = data.gitCommand;
J
Joao Moreno 已提交
263 264 265 266 267 268 269 270 271
	}

	toString(): string {
		let result = this.message + ' ' + JSON.stringify({
			exitCode: this.exitCode,
			gitErrorCode: this.gitErrorCode,
			gitCommand: this.gitCommand,
			stdout: this.stdout,
			stderr: this.stderr
272
		}, null, 2);
J
Joao Moreno 已提交
273 274 275 276 277 278 279 280 281 282 283 284

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

		return result;
	}
}

export interface IGitOptions {
	gitPath: string;
	version: string;
285
	env?: any;
J
Joao Moreno 已提交
286 287
}

288 289 290 291 292
function getGitErrorCode(stderr: string): string | undefined {
	if (/Another git process seems to be running in this repository|If no other git process is currently running/.test(stderr)) {
		return GitErrorCodes.RepositoryIsLocked;
	} else if (/Authentication failed/.test(stderr)) {
		return GitErrorCodes.AuthenticationFailed;
J
Joao Moreno 已提交
293
	} else if (/Not a git repository/i.test(stderr)) {
294 295 296 297 298 299 300 301 302
		return GitErrorCodes.NotAGitRepository;
	} else if (/bad config file/.test(stderr)) {
		return GitErrorCodes.BadConfigFile;
	} else if (/cannot make pipe for command substitution|cannot create standard input pipe/.test(stderr)) {
		return GitErrorCodes.CantCreatePipe;
	} else if (/Repository not found/.test(stderr)) {
		return GitErrorCodes.RepositoryNotFound;
	} else if (/unable to access/.test(stderr)) {
		return GitErrorCodes.CantAccessRemote;
303 304
	} else if (/branch '.+' is not fully merged/.test(stderr)) {
		return GitErrorCodes.BranchNotFullyMerged;
305 306
	} else if (/Couldn\'t find remote ref/.test(stderr)) {
		return GitErrorCodes.NoRemoteReference;
307 308 309 310
	} else if (/A branch named '.+' already exists/.test(stderr)) {
		return GitErrorCodes.BranchAlreadyExists;
	} else if (/'.+' is not a valid branch name/.test(stderr)) {
		return GitErrorCodes.InvalidBranchName;
311 312 313 314 315
	}

	return void 0;
}

J
Joao Moreno 已提交
316 317
export class Git {

J
Joao Moreno 已提交
318
	readonly path: string;
319
	private env: any;
J
Joao Moreno 已提交
320

321 322
	private _onOutput = new EventEmitter();
	get onOutput(): EventEmitter { return this._onOutput; }
J
Joao Moreno 已提交
323

J
Joao Moreno 已提交
324
	constructor(options: IGitOptions) {
J
Joao Moreno 已提交
325
		this.path = options.gitPath;
326
		this.env = options.env || {};
J
Joao Moreno 已提交
327 328
	}

329 330
	open(repository: string): Repository {
		return new Repository(this, repository);
J
Joao Moreno 已提交
331 332
	}

J
Joao Moreno 已提交
333 334 335 336 337
	async init(repository: string): Promise<void> {
		await this.exec(repository, ['init']);
		return;
	}

J
Joao Moreno 已提交
338
	async clone(url: string, parentPath: string, cancellationToken?: CancellationToken): Promise<string> {
339 340 341 342 343 344 345 346 347
		let baseFolderName = decodeURI(url).replace(/^.*\//, '').replace(/\.git$/, '') || 'repository';
		let folderName = baseFolderName;
		let folderPath = path.join(parentPath, folderName);
		let count = 1;

		while (count < 20 && await new Promise(c => fs.exists(folderPath, c))) {
			folderName = `${baseFolderName}-${count++}`;
			folderPath = path.join(parentPath, folderName);
		}
J
Joao Moreno 已提交
348

J
Joao Moreno 已提交
349
		await mkdirp(parentPath);
J
Joao Moreno 已提交
350 351 352 353 354 355 356 357 358 359 360 361

		try {
			await this.exec(parentPath, ['clone', url, folderPath], { cancellationToken });
		} catch (err) {
			if (err.stderr) {
				err.stderr = err.stderr.replace(/^Cloning.+$/m, '').trim();
				err.stderr = err.stderr.replace(/^ERROR:\s+/, '').trim();
			}

			throw err;
		}

J
Joao Moreno 已提交
362 363 364
		return folderPath;
	}

J
Joao Moreno 已提交
365 366 367
	async getRepositoryRoot(repositoryPath: string): Promise<string> {
		const result = await this.exec(repositoryPath, ['rev-parse', '--show-toplevel']);
		return path.normalize(result.stdout.trim());
J
Joao Moreno 已提交
368 369
	}

J
Joao Moreno 已提交
370
	async exec(cwd: string, args: string[], options: SpawnOptions = {}): Promise<IExecutionResult<string>> {
J
Joao Moreno 已提交
371
		options = assign({ cwd }, options || {});
J
Joao Moreno 已提交
372
		return await this._exec(args, options);
J
Joao Moreno 已提交
373 374
	}

J
Joao Moreno 已提交
375 376 377 378
	async exec2(args: string[], options: SpawnOptions = {}): Promise<IExecutionResult<string>> {
		return await this._exec(args, options);
	}

J
Joao Moreno 已提交
379
	stream(cwd: string, args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
380
		options = assign({ cwd }, options || {});
J
Joao Moreno 已提交
381
		return this.spawn(args, options);
J
Joao Moreno 已提交
382 383
	}

J
Joao Moreno 已提交
384
	private async _exec(args: string[], options: SpawnOptions = {}): Promise<IExecutionResult<string>> {
J
Joao Moreno 已提交
385
		const child = this.spawn(args, options);
J
Joao Moreno 已提交
386 387 388 389 390

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

J
Joao Moreno 已提交
391
		const bufferResult = await exec(child, options.cancellationToken);
J
Joao Moreno 已提交
392

J
Joao Moreno 已提交
393 394
		if (options.log !== false && bufferResult.stderr.length > 0) {
			this.log(`${bufferResult.stderr}\n`);
J
Joao Moreno 已提交
395 396
		}

J
Joao Moreno 已提交
397 398 399 400 401 402 403 404 405 406 407
		let encoding = options.encoding || 'utf8';
		encoding = iconv.encodingExists(encoding) ? encoding : 'utf8';

		const result: IExecutionResult<string> = {
			exitCode: bufferResult.exitCode,
			stdout: iconv.decode(bufferResult.stdout, encoding),
			stderr: bufferResult.stderr
		};

		if (bufferResult.exitCode) {
			return Promise.reject<IExecutionResult<string>>(new GitError({
J
Joao Moreno 已提交
408 409 410 411
				message: 'Failed to execute git',
				stdout: result.stdout,
				stderr: result.stderr,
				exitCode: result.exitCode,
412
				gitErrorCode: getGitErrorCode(result.stderr),
J
Joao Moreno 已提交
413 414 415 416 417
				gitCommand: args[0]
			}));
		}

		return result;
J
Joao Moreno 已提交
418 419
	}

J
Joao Moreno 已提交
420
	spawn(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
421
		if (!this.path) {
J
Joao Moreno 已提交
422 423 424 425 426 427 428 429 430 431 432
			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
		}

433
		options.env = assign({}, process.env, this.env, options.env || {}, {
J
Joao Moreno 已提交
434
			VSCODE_GIT_COMMAND: args[0],
435
			LC_ALL: 'en_US.UTF-8',
J
Joao Moreno 已提交
436 437
			LANG: 'en_US.UTF-8'
		});
J
Joao Moreno 已提交
438 439

		if (options.log !== false) {
J
Joao Moreno 已提交
440
			this.log(`> git ${args.join(' ')}\n`);
J
Joao Moreno 已提交
441 442
		}

J
Joao Moreno 已提交
443
		return cp.spawn(this.path, args, options);
J
Joao Moreno 已提交
444 445 446
	}

	private log(output: string): void {
447
		this._onOutput.emit('log', output);
J
Joao Moreno 已提交
448
	}
J
Joao Moreno 已提交
449 450
}

J
Joao Moreno 已提交
451
export interface Commit {
J
Joao Moreno 已提交
452 453
	hash: string;
	message: string;
J
Joao Moreno 已提交
454
	parents: string[];
J
Joao Moreno 已提交
455 456
}

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
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++;

J
Joao Moreno 已提交
495
		if (entry.x === 'R' || entry.x === 'C') {
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
			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;
	}
}

523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 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
export interface Submodule {
	name: string;
	path: string;
	url: string;
}

export function parseGitmodules(raw: string): Submodule[] {
	const regex = /\r?\n/g;
	let position = 0;
	let match: RegExpExecArray | null = null;

	const result: Submodule[] = [];
	let submodule: Partial<Submodule> = {};

	function parseLine(line: string): void {
		const sectionMatch = /^\s*\[submodule "([^"]+)"\]\s*$/.exec(line);

		if (sectionMatch) {
			if (submodule.name && submodule.path && submodule.url) {
				result.push(submodule as Submodule);
			}

			const name = sectionMatch[1];

			if (name) {
				submodule = { name };
				return;
			}
		}

		if (!submodule) {
			return;
		}

		const propertyMatch = /^\s*(\w+) = (.*)$/.exec(line);

		if (!propertyMatch) {
			return;
		}

		const [, key, value] = propertyMatch;

		switch (key) {
			case 'path': submodule.path = value; break;
			case 'url': submodule.url = value; break;
		}
	}

	while (match = regex.exec(raw)) {
		parseLine(raw.substring(position, match.index));
		position = match.index + match[0].length;
	}

	parseLine(raw.substring(position));

	if (submodule.name && submodule.path && submodule.url) {
		result.push(submodule as Submodule);
	}

	return result;
}

585 586 587 588 589 590
export function parseGitCommit(raw: string): Commit | null {
	const match = /^([0-9a-f]{40})\n(.*)\n([^]*)$/m.exec(raw.trim());
	if (!match) {
		return null;
	}

J
Joao Moreno 已提交
591 592
	const parents = match[2] ? match[2].split(' ') : [];
	return { hash: match[1], message: match[3], parents };
593 594
}

595 596 597 598
interface LsTreeElement {
	mode: string;
	type: string;
	object: string;
J
Joao Moreno 已提交
599
	size: string;
600 601 602 603 604 605
	file: string;
}

export function parseLsTree(raw: string): LsTreeElement[] {
	return raw.split('\n')
		.filter(l => !!l)
J
Joao Moreno 已提交
606
		.map(line => /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.*)$/.exec(line)!)
607
		.filter(m => !!m)
J
Joao Moreno 已提交
608
		.map(([, mode, type, object, size, file]) => ({ mode, type, object, size, file }));
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
}

interface LsFilesElement {
	mode: string;
	object: string;
	stage: string;
	file: string;
}

export function parseLsFiles(raw: string): LsFilesElement[] {
	return raw.split('\n')
		.filter(l => !!l)
		.map(line => /^(\S+)\s+(\S+)\s+(\S+)\s+(.*)$/.exec(line)!)
		.filter(m => !!m)
		.map(([, mode, object, stage, file]) => ({ mode, object, stage, file }));
}

J
Joao Moreno 已提交
626 627 628 629 630 631 632 633
export interface CommitOptions {
	all?: boolean;
	amend?: boolean;
	signoff?: boolean;
	signCommit?: boolean;
	empty?: boolean;
}

J
Joao Moreno 已提交
634 635
export enum ForcePushMode {
	Force,
J
Joao Moreno 已提交
636
	ForceWithLease
J
Joao Moreno 已提交
637 638
}

J
Joao Moreno 已提交
639 640 641 642
export class Repository {

	constructor(
		private _git: Git,
643
		private repositoryRoot: string
J
Joao Moreno 已提交
644 645 646 647 648 649
	) { }

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

J
Joao Moreno 已提交
650 651
	get root(): string {
		return this.repositoryRoot;
J
Joao Moreno 已提交
652 653 654
	}

	// TODO@Joao: rename to exec
J
Joao Moreno 已提交
655
	async run(args: string[], options: SpawnOptions = {}): Promise<IExecutionResult<string>> {
J
Joao Moreno 已提交
656
		return await this.git.exec(this.repositoryRoot, args, options);
J
Joao Moreno 已提交
657 658
	}

J
Joao Moreno 已提交
659
	stream(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
660
		return this.git.stream(this.repositoryRoot, args, options);
J
Joao Moreno 已提交
661 662
	}

J
Joao Moreno 已提交
663
	spawn(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
664 665 666
		return this.git.spawn(args, options);
	}

J
Joao Moreno 已提交
667
	async config(scope: string, key: string, value: any = null, options: SpawnOptions = {}): Promise<string> {
J
Joao Moreno 已提交
668 669 670 671 672 673 674 675 676 677 678 679 680
		const args = ['config'];

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

		args.push(key);

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

		const result = await this.run(args, options);
J
Joao Moreno 已提交
681
		return result.stdout.trim();
J
Joao Moreno 已提交
682 683
	}

J
Joao Moreno 已提交
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
	async getConfigs(scope: string): Promise<{ key: string; value: string; }[]> {
		const args = ['config'];

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

		args.push('-l');

		const result = await this.run(args);
		const lines = result.stdout.trim().split(/\r|\r\n|\n/);

		return lines.map(entry => {
			const equalsIndex = entry.indexOf('=');
			return { key: entry.substr(0, equalsIndex), value: entry.substr(equalsIndex + 1) };
		});
	}

702
	async bufferString(object: string, encoding: string = 'utf8', autoGuessEncoding = false): Promise<string> {
J
Joao Moreno 已提交
703
		const stdout = await this.buffer(object);
704 705 706 707 708

		if (autoGuessEncoding) {
			encoding = detectEncoding(stdout) || encoding;
		}

J
Joao Moreno 已提交
709 710 711
		encoding = iconv.encodingExists(encoding) ? encoding : 'utf8';

		return iconv.decode(stdout, encoding);
J
Joao Moreno 已提交
712 713 714
	}

	async buffer(object: string): Promise<Buffer> {
J
Joao Moreno 已提交
715 716 717
		const child = this.stream(['show', object]);

		if (!child.stdout) {
J
Joao Moreno 已提交
718
			return Promise.reject<Buffer>('Can\'t open file from git');
J
Joao Moreno 已提交
719 720
		}

721
		const { exitCode, stdout, stderr } = await exec(child);
J
Joao Moreno 已提交
722 723

		if (exitCode) {
724
			const err = new GitError({
J
Joao Moreno 已提交
725 726
				message: 'Could not show object.',
				exitCode
727 728 729 730 731 732 733
			});

			if (/exists on disk, but not in/.test(stderr)) {
				err.gitErrorCode = GitErrorCodes.WrongCase;
			}

			return Promise.reject<Buffer>(err);
J
Joao Moreno 已提交
734 735 736
		}

		return stdout;
J
Joao Moreno 已提交
737 738
	}

J
Joao Moreno 已提交
739
	async getObjectDetails(treeish: string, path: string): Promise<{ mode: string, object: string, size: number }> {
J
Joao Moreno 已提交
740
		if (!treeish) { // index
J
Joao Moreno 已提交
741
			const elements = await this.lsfiles(path);
J
Joao Moreno 已提交
742

J
Joao Moreno 已提交
743
			if (elements.length === 0) {
J
Joao Moreno 已提交
744 745 746
				throw new GitError({ message: 'Error running ls-files' });
			}

J
Joao Moreno 已提交
747
			const { mode, object } = elements[0];
J
Joao Moreno 已提交
748 749 750
			const catFile = await this.run(['cat-file', '-s', object]);
			const size = parseInt(catFile.stdout);

J
Joao Moreno 已提交
751
			return { mode, object, size };
J
Joao Moreno 已提交
752 753
		}

J
Joao Moreno 已提交
754
		const elements = await this.lstree(treeish, path);
J
Joao Moreno 已提交
755

J
Joao Moreno 已提交
756 757
		if (elements.length === 0) {
			throw new GitError({ message: 'Error running ls-files' });
J
Joao Moreno 已提交
758 759
		}

J
Joao Moreno 已提交
760
		const { mode, object, size } = elements[0];
J
Joao Moreno 已提交
761
		return { mode, object, size: parseInt(size) };
J
Joao Moreno 已提交
762 763
	}

J
Joao Moreno 已提交
764 765
	async lstree(treeish: string, path: string): Promise<LsTreeElement[]> {
		const { stdout } = await this.run(['ls-tree', '-l', treeish, '--', path]);
766 767
		return parseLsTree(stdout);
	}
768

769 770 771
	async lsfiles(path: string): Promise<LsFilesElement[]> {
		const { stdout } = await this.run(['ls-files', '--stage', '--', path]);
		return parseLsFiles(stdout);
772 773
	}

J
Joao Moreno 已提交
774
	async getGitRelativePath(ref: string, relativePath: string): Promise<string> {
775 776
		const relativePathLowercase = relativePath.toLowerCase();
		const dirname = path.posix.dirname(relativePath) + '/';
J
Joao Moreno 已提交
777
		const elements: { file: string; }[] = ref ? await this.lstree(ref, dirname) : await this.lsfiles(dirname);
778 779 780 781
		const element = elements.filter(file => file.file.toLowerCase() === relativePathLowercase)[0];

		if (!element) {
			throw new GitError({ message: 'Git relative path not found.' });
782
		}
783 784

		return element.file;
785 786
	}

J
Joao Moreno 已提交
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
	async detectObjectType(object: string): Promise<{ mimetype: string, encoding?: string }> {
		const child = await this.stream(['show', object]);
		const buffer = await readBytes(child.stdout, 4100);

		try {
			child.kill();
		} catch (err) {
			// noop
		}

		const encoding = detectUnicodeEncoding(buffer);
		let isText = true;

		if (encoding !== Encoding.UTF16be && encoding !== Encoding.UTF16le) {
			for (let i = 0; i < buffer.length; i++) {
				if (buffer.readInt8(i) === 0) {
					isText = false;
					break;
				}
			}
		}

		if (!isText) {
			const result = filetype(buffer);

			if (!result) {
				return { mimetype: 'application/octet-stream' };
			} else {
				return { mimetype: result.mime };
			}
		}

		if (encoding) {
			return { mimetype: 'text/plain', encoding };
		} else {
			// TODO@JOAO: read the setting OUTSIDE!
			return { mimetype: 'text/plain' };
		}
	}

J
Joao Moreno 已提交
827
	async diff(path: string, cached = false): Promise<string> {
828 829
		const args = ['diff'];

J
Joao Moreno 已提交
830
		if (cached) {
831 832 833 834 835 836 837 838 839
			args.push('--cached');
		}

		args.push('--', path);

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

J
Joao Moreno 已提交
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
	async diffWithHEAD(path: string): Promise<string> {
		const args = ['diff', '--', path];
		const result = await this.run(args);
		return result.stdout;
	}

	async diffWith(ref: string, path: string): Promise<string> {
		const args = ['diff', ref, '--', path];
		const result = await this.run(args);
		return result.stdout;
	}

	async diffIndexWithHEAD(path: string): Promise<string> {
		const args = ['diff', '--cached', '--', path];
		const result = await this.run(args);
		return result.stdout;
	}

	async diffIndexWith(ref: string, path: string): Promise<string> {
		const args = ['diff', '--cached', ref, '--', path];
		const result = await this.run(args);
		return result.stdout;
	}

	async diffBlobs(object1: string, object2: string): Promise<string> {
		const args = ['diff', object1, object2];
		const result = await this.run(args);
		return result.stdout;
	}

J
Joao Moreno 已提交
870 871 872 873 874 875 876 877 878 879 880 881 882 883
	async diffBetween(ref1: string, ref2: string, path: string): Promise<string> {
		const args = ['diff', `${ref1}...${ref2}`, '--', path];
		const result = await this.run(args);

		return result.stdout.trim();
	}

	async getMergeBase(ref1: string, ref2: string): Promise<string> {
		const args = ['merge-base', ref1, ref2];
		const result = await this.run(args);

		return result.stdout.trim();
	}

J
Joao Moreno 已提交
884 885 886 887 888 889 890
	async hashObject(data: string): Promise<string> {
		const args = ['hash-object', '-w', '--stdin'];
		const result = await this.run(args, { input: data });

		return result.stdout.trim();
	}

J
Joao Moreno 已提交
891 892 893 894 895 896 897 898 899 900 901 902
	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);
	}

J
Joao Moreno 已提交
903 904 905 906 907 908 909 910 911 912 913 914
	async rm(paths: string[]): Promise<void> {
		const args = ['rm', '--'];

		if (!paths || !paths.length) {
			return;
		}

		args.push(...paths);

		await this.run(args);
	}

J
Joao Moreno 已提交
915
	async stage(path: string, data: string): Promise<void> {
916
		const child = this.stream(['hash-object', '--stdin', '-w', '--path', path], { stdio: [null, null, null] });
J
Joao Moreno 已提交
917 918 919
		child.stdin.end(data, 'utf8');

		const { exitCode, stdout } = await exec(child);
J
Joao Moreno 已提交
920
		const hash = stdout.toString('utf8');
J
Joao Moreno 已提交
921 922 923 924 925 926 927 928

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

J
Joao Moreno 已提交
929 930 931
		let mode: string;

		try {
J
Joao Moreno 已提交
932
			const details = await this.getObjectDetails('HEAD', path);
J
Joao Moreno 已提交
933 934 935 936 937 938
			mode = details.mode;
		} catch (err) {
			mode = '100644';
		}

		await this.run(['update-index', '--cacheinfo', mode, hash, path]);
J
Joao Moreno 已提交
939 940
	}

941
	async checkout(treeish: string, paths: string[], opts: { track?: boolean } = Object.create(null)): Promise<void> {
J
Joao Moreno 已提交
942 943
		const args = ['checkout', '-q'];

944 945 946 947
		if (opts.track) {
			args.push('--track');
		}

J
Joao Moreno 已提交
948 949 950 951 952 953 954 955 956 957 958 959
		if (treeish) {
			args.push(treeish);
		}

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

		try {
			await this.run(args);
		} catch (err) {
J
Joao Moreno 已提交
960
			if (/Please,? commit your changes or stash them/.test(err.stderr || '')) {
J
Joao Moreno 已提交
961 962 963 964 965 966 967
				err.gitErrorCode = GitErrorCodes.DirtyWorkTree;
			}

			throw err;
		}
	}

J
Joao Moreno 已提交
968
	async commit(message: string, opts: CommitOptions = Object.create(null)): Promise<void> {
J
Joao Moreno 已提交
969 970
		const args = ['commit', '--quiet', '--allow-empty-message', '--file', '-'];

J
Joao Moreno 已提交
971
		if (opts.all) {
J
Joao Moreno 已提交
972 973 974
			args.push('--all');
		}

J
Joao Moreno 已提交
975
		if (opts.amend) {
J
Joao Moreno 已提交
976 977 978
			args.push('--amend');
		}

J
Joao Moreno 已提交
979
		if (opts.signoff) {
J
Joao Moreno 已提交
980 981 982
			args.push('--signoff');
		}

983 984 985
		if (opts.signCommit) {
			args.push('-S');
		}
T
Tom Basche 已提交
986 987 988
		if (opts.empty) {
			args.push('--allow-empty');
		}
989

J
Joao Moreno 已提交
990 991 992
		try {
			await this.run(args, { input: message || '' });
		} catch (commitErr) {
993 994 995
			await this.handleCommitError(commitErr);
		}
	}
J
Joao Moreno 已提交
996

997 998
	async rebaseContinue(): Promise<void> {
		const args = ['rebase', '--continue'];
J
Joao Moreno 已提交
999

1000 1001 1002 1003 1004 1005
		try {
			await this.run(args);
		} catch (commitErr) {
			await this.handleCommitError(commitErr);
		}
	}
J
Joao Moreno 已提交
1006

1007 1008 1009
	private async handleCommitError(commitErr: any): Promise<void> {
		if (/not possible because you have unmerged files/.test(commitErr.stderr || '')) {
			commitErr.gitErrorCode = GitErrorCodes.UnmergedChanges;
J
Joao Moreno 已提交
1010 1011
			throw commitErr;
		}
1012 1013

		try {
J
Joao Moreno 已提交
1014 1015 1016 1017 1018
			await this.run(['config', '--get-all', 'user.name']);
		} catch (err) {
			err.gitErrorCode = GitErrorCodes.NoUserNameConfigured;
			throw err;
		}
1019 1020

		try {
J
Joao Moreno 已提交
1021 1022 1023 1024
			await this.run(['config', '--get-all', 'user.email']);
		} catch (err) {
			err.gitErrorCode = GitErrorCodes.NoUserEmailConfigured;
			throw err;
1025 1026 1027
		}

		throw commitErr;
J
Joao Moreno 已提交
1028 1029
	}

J
Joao Moreno 已提交
1030
	async branch(name: string, checkout: boolean, ref?: string): Promise<void> {
J
Joao Moreno 已提交
1031
		const args = checkout ? ['checkout', '-q', '-b', name] : ['branch', '-q', name];
J
Joao Moreno 已提交
1032 1033 1034 1035 1036

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

J
Joao Moreno 已提交
1037 1038 1039
		await this.run(args);
	}

1040 1041
	async deleteBranch(name: string, force?: boolean): Promise<void> {
		const args = ['branch', force ? '-D' : '-d', name];
M
Maik Riechert 已提交
1042 1043 1044
		await this.run(args);
	}

1045 1046 1047 1048 1049
	async renameBranch(name: string): Promise<void> {
		const args = ['branch', '-m', name];
		await this.run(args);
	}

J
Joao Moreno 已提交
1050 1051 1052 1053 1054
	async setBranchUpstream(name: string, upstream: string): Promise<void> {
		const args = ['branch', '--set-upstream-to', upstream, name];
		await this.run(args);
	}

1055 1056 1057 1058 1059
	async deleteRef(ref: string): Promise<void> {
		const args = ['update-ref', '-d', ref];
		await this.run(args);
	}

J
Joao Moreno 已提交
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
	async merge(ref: string): Promise<void> {
		const args = ['merge', ref];

		try {
			await this.run(args);
		} catch (err) {
			if (/^CONFLICT /m.test(err.stdout || '')) {
				err.gitErrorCode = GitErrorCodes.Conflict;
			}

			throw err;
		}
1072 1073
	}

J
Joao Moreno 已提交
1074
	async tag(name: string, message?: string): Promise<void> {
1075 1076
		let args = ['tag'];

J
Joao Moreno 已提交
1077 1078
		if (message) {
			args = [...args, '-a', name, '-m', message];
1079
		} else {
J
Joao Moreno 已提交
1080
			args = [...args, name];
1081 1082 1083 1084 1085
		}

		await this.run(args);
	}

J
Joao Moreno 已提交
1086
	async clean(paths: string[]): Promise<void> {
J
Joao Moreno 已提交
1087 1088 1089
		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 已提交
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121

		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);
	}

J
Joao Moreno 已提交
1122
	async revert(treeish: string, paths: string[]): Promise<void> {
J
Joao Moreno 已提交
1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
		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;
		}
	}

J
Joao Moreno 已提交
1152 1153 1154 1155 1156
	async addRemote(name: string, url: string): Promise<void> {
		const args = ['remote', 'add', name, url];
		await this.run(args);
	}

J
Joao Moreno 已提交
1157 1158 1159 1160 1161
	async removeRemote(name: string): Promise<void> {
		const args = ['remote', 'rm', name];
		await this.run(args);
	}

J
Joao Moreno 已提交
1162
	async fetch(options: { remote?: string, ref?: string, all?: boolean } = {}): Promise<void> {
J
Joao Moreno 已提交
1163 1164
		const args = ['fetch'];

J
Joao Moreno 已提交
1165 1166
		if (options.remote) {
			args.push(options.remote);
J
Joao Moreno 已提交
1167

J
Joao Moreno 已提交
1168 1169
			if (options.ref) {
				args.push(options.ref);
J
Joao Moreno 已提交
1170
			}
J
Joao Moreno 已提交
1171 1172
		} else if (options.all) {
			args.push('--all');
J
Joao Moreno 已提交
1173 1174
		}

J
Joao Moreno 已提交
1175
		try {
J
Joao Moreno 已提交
1176
			await this.run(args);
J
Joao Moreno 已提交
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
		} 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;
		}
	}

M
Matt Shirley 已提交
1188
	async pull(rebase?: boolean, remote?: string, branch?: string): Promise<void> {
J
Joao Moreno 已提交
1189
		const args = ['pull', '--tags'];
J
Joao Moreno 已提交
1190 1191 1192 1193 1194

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

M
Matt Shirley 已提交
1195
		if (remote && branch) {
1196
			args.push(remote);
M
Matt Shirley 已提交
1197
			args.push(branch);
1198 1199
		}

J
Joao Moreno 已提交
1200 1201 1202 1203 1204 1205 1206 1207 1208
		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;
J
Joao Moreno 已提交
1209 1210
			} 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/i.test(err.stderr)) {
				err.stderr = err.stderr.replace(/Cannot pull with rebase: You have unstaged changes/i, 'Cannot pull with rebase, you have unstaged changes');
J
Joao Moreno 已提交
1211
				err.gitErrorCode = GitErrorCodes.DirtyWorkTree;
J
Joao Moreno 已提交
1212 1213 1214 1215
			} else if (/cannot lock ref|unable to update local ref/i.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.CantLockRef;
			} else if (/cannot rebase onto multiple branches/i.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.CantRebaseMultipleBranches;
J
Joao Moreno 已提交
1216 1217 1218 1219 1220 1221
			}

			throw err;
		}
	}

1222
	async push(remote?: string, name?: string, setUpstream: boolean = false, tags = false, forcePushMode?: ForcePushMode): Promise<void> {
J
Joao Moreno 已提交
1223 1224
		const args = ['push'];

J
Joao Moreno 已提交
1225 1226 1227 1228
		if (forcePushMode === ForcePushMode.ForceWithLease) {
			args.push('--force-with-lease');
		} else if (forcePushMode === ForcePushMode.Force) {
			args.push('--force');
1229 1230
		}

J
Joao Moreno 已提交
1231
		if (setUpstream) {
J
Joao Moreno 已提交
1232 1233 1234
			args.push('-u');
		}

1235 1236
		if (tags) {
			args.push('--tags');
J
Joao Moreno 已提交
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
		}

		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;
1254 1255
			} else if (/^fatal: The current branch .* has no upstream branch/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoUpstreamBranch;
J
Joao Moreno 已提交
1256 1257 1258 1259 1260 1261
			}

			throw err;
		}
	}

1262
	async createStash(message?: string, includeUntracked?: boolean): Promise<void> {
1263
		try {
J
Joao Moreno 已提交
1264
			const args = ['stash', 'save'];
1265

1266 1267 1268 1269
			if (includeUntracked) {
				args.push('-u');
			}

J
Joao Moreno 已提交
1270 1271
			if (message) {
				args.push('--', message);
1272 1273 1274 1275 1276 1277 1278
			}

			await this.run(args);
		} catch (err) {
			if (/No local changes to save/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoLocalChanges;
			}
J
Joao Moreno 已提交
1279 1280 1281 1282 1283 1284

			throw err;
		}
	}

	async popStash(index?: number): Promise<void> {
1285
		const args = ['stash', 'pop'];
J
Joao Moreno 已提交
1286
		await this.popOrApplyStash(args, index);
1287 1288 1289 1290
	}

	async applyStash(index?: number): Promise<void> {
		const args = ['stash', 'apply'];
J
Joao Moreno 已提交
1291
		await this.popOrApplyStash(args, index);
1292
	}
J
Joao Moreno 已提交
1293

1294 1295
	private async popOrApplyStash(args: string[], index?: number): Promise<void> {
		try {
1296
			if (typeof index === 'number') {
J
Joao Moreno 已提交
1297
				args.push(`stash@{${index}}`);
1298
			}
J
Joao Moreno 已提交
1299 1300 1301 1302 1303 1304

			await this.run(args);
		} catch (err) {
			if (/No stash found/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoStashFound;
			} else if (/error: Your local changes to the following files would be overwritten/.test(err.stderr || '')) {
1305
				err.gitErrorCode = GitErrorCodes.LocalChangesOverwritten;
J
Joao Moreno 已提交
1306 1307
			} else if (/^CONFLICT/m.test(err.stdout || '')) {
				err.gitErrorCode = GitErrorCodes.StashConflict;
1308
			}
J
Joao Moreno 已提交
1309

1310 1311 1312 1313
			throw err;
		}
	}

1314 1315
	getStatus(limit = 5000): Promise<{ status: IFileStatus[]; didHitLimit: boolean; }> {
		return new Promise<{ status: IFileStatus[]; didHitLimit: boolean; }>((c, e) => {
1316
			const parser = new GitStatusParser();
J
Joao Moreno 已提交
1317 1318
			const env = { GIT_OPTIONAL_LOCKS: '0' };
			const child = this.stream(['status', '-z', '-u'], { env });
1319

M
Matt Bierner 已提交
1320
			const onExit = (exitCode: number) => {
1321
				if (exitCode !== 0) {
1322 1323 1324 1325 1326 1327 1328 1329
					const stderr = stderrData.join('');
					return e(new GitError({
						message: 'Failed to execute git',
						stderr,
						exitCode,
						gitErrorCode: getGitErrorCode(stderr),
						gitCommand: 'status'
					}));
1330
				}
J
Joao Moreno 已提交
1331

1332 1333 1334
				c({ status: parser.status, didHitLimit: false });
			};

1335
			const onStdoutData = (raw: string) => {
1336 1337
				parser.update(raw);

J
Joao Moreno 已提交
1338
				if (parser.status.length > limit) {
1339
					child.removeListener('exit', onExit);
1340
					child.stdout.removeListener('data', onStdoutData);
1341 1342
					child.kill();

J
Joao Moreno 已提交
1343
					c({ status: parser.status.slice(0, limit), didHitLimit: true });
1344 1345 1346 1347
				}
			};

			child.stdout.setEncoding('utf8');
1348 1349 1350 1351 1352 1353
			child.stdout.on('data', onStdoutData);

			const stderrData: string[] = [];
			child.stderr.setEncoding('utf8');
			child.stderr.on('data', raw => stderrData.push(raw as string));

J
Joao Moreno 已提交
1354
			child.on('error', cpErrorHandler(e));
1355
			child.on('exit', onExit);
1356
		});
J
Joao Moreno 已提交
1357 1358
	}

J
Joao Moreno 已提交
1359
	async getHEAD(): Promise<Ref> {
J
Joao Moreno 已提交
1360
		try {
J
Joao Moreno 已提交
1361
			const result = await this.run(['symbolic-ref', '--short', 'HEAD']);
J
Joao Moreno 已提交
1362 1363 1364 1365 1366 1367 1368

			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 已提交
1369
			const result = await this.run(['rev-parse', 'HEAD']);
J
Joao Moreno 已提交
1370 1371 1372 1373 1374 1375 1376 1377 1378

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

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

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

M
Matt Bierner 已提交
1382
		const fn = (line: string): Ref | null => {
J
Joao Moreno 已提交
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
			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 已提交
1399
			.filter(ref => !!ref) as Ref[];
J
Joao Moreno 已提交
1400 1401
	}

1402 1403
	async getStashes(): Promise<Stash[]> {
		const result = await this.run(['stash', 'list']);
J
Joao Moreno 已提交
1404
		const regex = /^stash@{(\d+)}:(.+)$/;
1405 1406
		const rawStashes = result.stdout.trim().split('\n')
			.filter(b => !!b)
M
Matt Bierner 已提交
1407
			.map(line => regex.exec(line) as RegExpExecArray)
1408
			.filter(g => !!g)
J
Joao Moreno 已提交
1409
			.map(([, index, description]: RegExpExecArray) => ({ index: parseInt(index), description }));
1410

J
Joao Moreno 已提交
1411 1412
		return rawStashes;
	}
1413

J
Joao Moreno 已提交
1414
	async getRemotes(): Promise<Remote[]> {
J
Joao Moreno 已提交
1415
		const result = await this.run(['remote', '--verbose']);
1416
		const lines = result.stdout.trim().split('\n').filter(l => !!l);
J
Joao Moreno 已提交
1417
		const remotes: MutableRemote[] = [];
J
Joao Moreno 已提交
1418

1419 1420
		for (const line of lines) {
			const parts = line.split(/\s/);
J
Joao Moreno 已提交
1421 1422 1423 1424
			const [name, url, type] = parts;

			let remote = remotes.find(r => r.name === name);

1425
			if (!remote) {
J
Joao Moreno 已提交
1426
				remote = { name, isReadOnly: false };
1427 1428 1429
				remotes.push(remote);
			}

J
Joao Moreno 已提交
1430 1431 1432 1433 1434 1435 1436
			if (/fetch/i.test(type)) {
				remote.fetchUrl = url;
			} else if (/push/i.test(type)) {
				remote.pushUrl = url;
			} else {
				remote.fetchUrl = url;
				remote.pushUrl = url;
1437 1438 1439
			}

			// https://github.com/Microsoft/vscode/issues/45271
J
Joao Moreno 已提交
1440
			remote.isReadOnly = remote.pushUrl === undefined || remote.pushUrl === 'no_push';
1441
		}
J
Joao Moreno 已提交
1442

1443
		return remotes;
J
Joao Moreno 已提交
1444 1445
	}

J
Joao Moreno 已提交
1446
	async getBranch(name: string): Promise<Branch> {
J
Joao Moreno 已提交
1447 1448
		if (name === 'HEAD') {
			return this.getHEAD();
1449 1450 1451 1452
		} else if (/^@/.test(name)) {
			const symbolicFullNameResult = await this.run(['rev-parse', '--symbolic-full-name', name]);
			const symbolicFullName = symbolicFullNameResult.stdout.trim();
			name = symbolicFullName || name;
J
Joao Moreno 已提交
1453 1454
		}

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

		if (!result.stdout) {
J
Joao Moreno 已提交
1458
			return Promise.reject<Branch>(new Error('No such branch'));
J
Joao Moreno 已提交
1459 1460 1461 1462 1463
		}

		const commit = result.stdout.trim();

		try {
J
Joao Moreno 已提交
1464 1465 1466 1467 1468 1469 1470
			const res2 = await this.run(['rev-parse', '--symbolic-full-name', name + '@{u}']);
			const fullUpstream = res2.stdout.trim();
			const match = /^refs\/remotes\/([^/]+)\/(.+)$/.exec(fullUpstream);

			if (!match) {
				throw new Error(`Could not parse upstream branch: ${fullUpstream}`);
			}
J
Joao Moreno 已提交
1471

J
Joao Moreno 已提交
1472 1473
			const upstream = { remote: match[1], name: match[2] };
			const res3 = await this.run(['rev-list', '--left-right', name + '...' + fullUpstream]);
J
Joao Moreno 已提交
1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507

			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 已提交
1508
				templatePath = path.join(this.repositoryRoot, templatePath);
J
Joao Moreno 已提交
1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
			}

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

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

J
Joao Moreno 已提交
1519
	async getCommit(ref: string): Promise<Commit> {
1520
		const result = await this.run(['show', '-s', '--format=%H\n%P\n%B', ref]);
1521
		return parseGitCommit(result.stdout) || Promise.reject<Commit>('bad commit format');
J
Joao Moreno 已提交
1522
	}
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542

	async updateSubmodules(paths: string[]): Promise<void> {
		const args = ['submodule', 'update', '--', ...paths];
		await this.run(args);
	}

	async getSubmodules(): Promise<Submodule[]> {
		const gitmodulesPath = path.join(this.root, '.gitmodules');

		try {
			const gitmodulesRaw = await readfile(gitmodulesPath, 'utf8');
			return parseGitmodules(gitmodulesRaw);
		} catch (err) {
			if (/ENOENT/.test(err.message)) {
				return [];
			}

			throw err;
		}
	}
1543
}