git.ts 34.6 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

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

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

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

J
Joao Moreno 已提交
34
export interface Remote {
J
Joao Moreno 已提交
35
	name: string;
36 37
	fetchUrl?: string;
	pushUrl?: string;
J
Joao Moreno 已提交
38
	isReadOnly: boolean;
J
Joao Moreno 已提交
39 40
}

41
export interface Stash {
J
Joao Moreno 已提交
42
	index: number;
43 44 45
	description: string;
}

J
Joao Moreno 已提交
46 47 48 49 50 51
export enum RefType {
	Head,
	RemoteHead,
	Tag
}

J
Joao Moreno 已提交
52
export interface Ref {
J
Joao Moreno 已提交
53 54 55 56 57 58
	type: RefType;
	name?: string;
	commit?: string;
	remote?: string;
}

J
Joao Moreno 已提交
59 60 61 62 63
export interface UpstreamRef {
	remote: string;
	name: string;
}

J
Joao Moreno 已提交
64
export interface Branch extends Ref {
J
Joao Moreno 已提交
65
	upstream?: UpstreamRef;
J
Joao Moreno 已提交
66 67 68 69
	ahead?: number;
	behind?: number;
}

J
Joao Moreno 已提交
70 71 72 73
function parseVersion(raw: string): string {
	return raw.replace(/^git version /, '');
}

J
Joao Moreno 已提交
74
function findSpecificGit(path: string, onLookup: (path: string) => void): Promise<IGit> {
J
Joao Moreno 已提交
75
	return new Promise<IGit>((c, e) => {
J
Joao Moreno 已提交
76 77
		onLookup(path);

J
Joao Moreno 已提交
78 79
		const buffers: Buffer[] = [];
		const child = cp.spawn(path, ['--version']);
80
		child.stdout.on('data', (b: Buffer) => buffers.push(b));
J
Joao Moreno 已提交
81
		child.on('error', cpErrorHandler(e));
J
Joao Moreno 已提交
82 83 84 85
		child.on('exit', code => code ? e(new Error('Not found')) : c({ path, version: parseVersion(Buffer.concat(buffers).toString('utf8').trim()) }));
	});
}

J
Joao Moreno 已提交
86
function findGitDarwin(onLookup: (path: string) => void): Promise<IGit> {
J
Joao Moreno 已提交
87 88 89 90 91 92 93 94 95
	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 已提交
96 97
				onLookup(path);

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

J
Joao Moreno 已提交
101 102 103 104
					if (err) {
						return e('git not found');
					}

J
Joao 已提交
105
					return c({ path, version: parseVersion(stdout.trim()) });
J
Joao Moreno 已提交
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
				});
			}

			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 已提交
128
function findSystemGitWin32(base: string, onLookup: (path: string) => void): Promise<IGit> {
J
Joao Moreno 已提交
129 130 131 132
	if (!base) {
		return Promise.reject<IGit>('Not found');
	}

J
Joao Moreno 已提交
133
	return findSpecificGit(path.join(base, 'Git', 'cmd', 'git.exe'), onLookup);
J
Joao Moreno 已提交
134 135
}

136 137 138 139 140
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 已提交
141 142 143
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))
144 145 146
		.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 已提交
147 148
}

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

J
Joao Moreno 已提交
152 153 154
	return first
		.then(void 0, () => {
			switch (process.platform) {
J
Joao Moreno 已提交
155 156 157
				case 'darwin': return findGitDarwin(onLookup);
				case 'win32': return findGitWin32(onLookup);
				default: return findSpecificGit('git', onLookup);
J
Joao Moreno 已提交
158 159 160
			}
		})
		.then(null, () => Promise.reject(new Error('Git installation not found.')));
J
Joao Moreno 已提交
161 162
}

J
Joao Moreno 已提交
163
export interface IExecutionResult<T extends string | Buffer> {
J
Joao Moreno 已提交
164
	exitCode: number;
J
Joao Moreno 已提交
165
	stdout: T;
J
Joao Moreno 已提交
166 167 168
	stderr: string;
}

J
Joao Moreno 已提交
169 170 171 172 173 174 175 176 177 178 179 180 181 182
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 已提交
183
export interface SpawnOptions extends cp.SpawnOptions {
J
Joao Moreno 已提交
184 185 186
	input?: string;
	encoding?: string;
	log?: boolean;
J
Joao Moreno 已提交
187
	cancellationToken?: CancellationToken;
J
Joao Moreno 已提交
188 189
}

J
Joao Moreno 已提交
190
async function exec(child: cp.ChildProcess, cancellationToken?: CancellationToken): Promise<IExecutionResult<Buffer>> {
J
Joao Moreno 已提交
191
	if (!child.stdout || !child.stderr) {
J
Joao Moreno 已提交
192 193 194 195 196
		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 已提交
197 198
	}

J
Joao Moreno 已提交
199 200
	const disposables: IDisposable[] = [];

M
Matt Bierner 已提交
201
	const once = (ee: NodeJS.EventEmitter, name: string, fn: (...args: any[]) => void) => {
J
Joao Moreno 已提交
202 203 204 205
		ee.once(name, fn);
		disposables.push(toDisposable(() => ee.removeListener(name, fn)));
	};

M
Matt Bierner 已提交
206
	const on = (ee: NodeJS.EventEmitter, name: string, fn: (...args: any[]) => void) => {
J
Joao Moreno 已提交
207 208 209 210
		ee.on(name, fn);
		disposables.push(toDisposable(() => ee.removeListener(name, fn)));
	};

J
Joao Moreno 已提交
211
	let result = Promise.all<any>([
J
Joao Moreno 已提交
212
		new Promise<number>((c, e) => {
J
Joao Moreno 已提交
213
			once(child, 'error', cpErrorHandler(e));
J
Joao Moreno 已提交
214 215
			once(child, 'exit', c);
		}),
J
Joao Moreno 已提交
216
		new Promise<Buffer>(c => {
217
			const buffers: Buffer[] = [];
M
Matt Bierner 已提交
218
			on(child.stdout, 'data', (b: Buffer) => buffers.push(b));
J
Joao Moreno 已提交
219
			once(child.stdout, 'close', () => c(Buffer.concat(buffers)));
J
Joao Moreno 已提交
220 221
		}),
		new Promise<string>(c => {
222
			const buffers: Buffer[] = [];
M
Matt Bierner 已提交
223
			on(child.stderr, 'data', (b: Buffer) => buffers.push(b));
J
Joao Moreno 已提交
224
			once(child.stderr, 'close', () => c(Buffer.concat(buffers).toString('utf8')));
J
Joao Moreno 已提交
225
		})
J
Joao Moreno 已提交
226 227 228 229 230 231 232 233 234 235
	]) 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 已提交
236

J
Joao Moreno 已提交
237 238 239 240 241 242
				e(new GitError({ message: 'Cancelled' }));
			});
		});

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

J
Joao Moreno 已提交
244 245 246 247 248 249
	try {
		const [exitCode, stdout, stderr] = await result;
		return { exitCode, stdout, stderr };
	} finally {
		dispose(disposables);
	}
J
Joao Moreno 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263
}

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

export class GitError {

J
Joao Moreno 已提交
264
	error?: Error;
J
Joao Moreno 已提交
265
	message: string;
J
Joao Moreno 已提交
266 267 268 269 270
	stdout?: string;
	stderr?: string;
	exitCode?: number;
	gitErrorCode?: string;
	gitCommand?: string;
J
Joao Moreno 已提交
271 272 273 274 275 276

	constructor(data: IGitErrorData) {
		if (data.error) {
			this.error = data.error;
			this.message = data.error.message;
		} else {
J
Joao Moreno 已提交
277
			this.error = void 0;
M
Matt Bierner 已提交
278
			this.message = '';
J
Joao Moreno 已提交
279 280 281
		}

		this.message = this.message || data.message || 'Git error';
J
Joao Moreno 已提交
282 283 284 285 286
		this.stdout = data.stdout;
		this.stderr = data.stderr;
		this.exitCode = data.exitCode;
		this.gitErrorCode = data.gitErrorCode;
		this.gitCommand = data.gitCommand;
J
Joao Moreno 已提交
287 288 289 290 291 292 293 294 295
	}

	toString(): string {
		let result = this.message + ' ' + JSON.stringify({
			exitCode: this.exitCode,
			gitErrorCode: this.gitErrorCode,
			gitCommand: this.gitCommand,
			stdout: this.stdout,
			stderr: this.stderr
296
		}, null, 2);
J
Joao Moreno 已提交
297 298 299 300 301 302 303 304 305 306 307 308

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

		return result;
	}
}

export interface IGitOptions {
	gitPath: string;
	version: string;
309
	env?: any;
J
Joao Moreno 已提交
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
}

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',
329
	RepositoryNotFound: 'RepositoryNotFound',
330
	RepositoryIsLocked: 'RepositoryIsLocked',
331
	BranchNotFullyMerged: 'BranchNotFullyMerged',
332
	NoRemoteReference: 'NoRemoteReference',
333
	InvalidBranchName: 'InvalidBranchName',
334
	BranchAlreadyExists: 'BranchAlreadyExists',
335 336
	NoLocalChanges: 'NoLocalChanges',
	NoStashFound: 'NoStashFound',
337
	LocalChangesOverwritten: 'LocalChangesOverwritten',
J
Joao Moreno 已提交
338
	NoUpstreamBranch: 'NoUpstreamBranch',
339
	IsInSubmodule: 'IsInSubmodule',
J
Joao Moreno 已提交
340 341
};

342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
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;
	} else if (/Not a git repository/.test(stderr)) {
		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;
357 358
	} else if (/branch '.+' is not fully merged/.test(stderr)) {
		return GitErrorCodes.BranchNotFullyMerged;
359 360
	} else if (/Couldn\'t find remote ref/.test(stderr)) {
		return GitErrorCodes.NoRemoteReference;
361 362 363 364
	} 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;
365 366 367 368 369
	}

	return void 0;
}

J
Joao Moreno 已提交
370 371
export class Git {

J
Joao Moreno 已提交
372
	readonly path: string;
373
	private env: any;
J
Joao Moreno 已提交
374

375 376
	private _onOutput = new EventEmitter();
	get onOutput(): EventEmitter { return this._onOutput; }
J
Joao Moreno 已提交
377

J
Joao Moreno 已提交
378
	constructor(options: IGitOptions) {
J
Joao Moreno 已提交
379
		this.path = options.gitPath;
380
		this.env = options.env || {};
J
Joao Moreno 已提交
381 382
	}

383 384
	open(repository: string): Repository {
		return new Repository(this, repository);
J
Joao Moreno 已提交
385 386
	}

J
Joao Moreno 已提交
387 388 389 390 391
	async init(repository: string): Promise<void> {
		await this.exec(repository, ['init']);
		return;
	}

J
Joao Moreno 已提交
392
	async clone(url: string, parentPath: string, cancellationToken?: CancellationToken): Promise<string> {
393 394 395 396 397 398 399 400 401
		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 已提交
402

J
Joao Moreno 已提交
403
		await mkdirp(parentPath);
J
Joao Moreno 已提交
404 405 406 407 408 409 410 411 412 413 414 415

		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 已提交
416 417 418
		return folderPath;
	}

J
Joao Moreno 已提交
419 420 421
	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 已提交
422 423
	}

J
Joao Moreno 已提交
424
	async exec(cwd: string, args: string[], options: SpawnOptions = {}): Promise<IExecutionResult<string>> {
J
Joao Moreno 已提交
425
		options = assign({ cwd }, options || {});
J
Joao Moreno 已提交
426
		return await this._exec(args, options);
J
Joao Moreno 已提交
427 428
	}

J
Joao Moreno 已提交
429
	stream(cwd: string, args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
430
		options = assign({ cwd }, options || {});
J
Joao Moreno 已提交
431
		return this.spawn(args, options);
J
Joao Moreno 已提交
432 433
	}

J
Joao Moreno 已提交
434
	private async _exec(args: string[], options: SpawnOptions = {}): Promise<IExecutionResult<string>> {
J
Joao Moreno 已提交
435
		const child = this.spawn(args, options);
J
Joao Moreno 已提交
436 437 438 439 440

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

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

J
Joao Moreno 已提交
443 444
		if (options.log !== false && bufferResult.stderr.length > 0) {
			this.log(`${bufferResult.stderr}\n`);
J
Joao Moreno 已提交
445 446
		}

J
Joao Moreno 已提交
447 448 449 450 451 452 453 454 455 456 457
		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 已提交
458 459 460 461
				message: 'Failed to execute git',
				stdout: result.stdout,
				stderr: result.stderr,
				exitCode: result.exitCode,
462
				gitErrorCode: getGitErrorCode(result.stderr),
J
Joao Moreno 已提交
463 464 465 466 467
				gitCommand: args[0]
			}));
		}

		return result;
J
Joao Moreno 已提交
468 469
	}

J
Joao Moreno 已提交
470
	spawn(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
471
		if (!this.path) {
J
Joao Moreno 已提交
472 473 474 475 476 477 478 479 480 481 482
			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
		}

483
		options.env = assign({}, process.env, this.env, options.env || {}, {
J
Joao Moreno 已提交
484
			VSCODE_GIT_COMMAND: args[0],
485
			LC_ALL: 'en_US.UTF-8',
J
Joao Moreno 已提交
486 487
			LANG: 'en_US.UTF-8'
		});
J
Joao Moreno 已提交
488 489

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

J
Joao Moreno 已提交
493
		return cp.spawn(this.path, args, options);
J
Joao Moreno 已提交
494 495 496
	}

	private log(output: string): void {
497
		this._onOutput.emit('log', output);
J
Joao Moreno 已提交
498
	}
J
Joao Moreno 已提交
499 500
}

J
Joao Moreno 已提交
501
export interface Commit {
J
Joao Moreno 已提交
502 503
	hash: string;
	message: string;
504
	previousHashes: string[];
J
Joao Moreno 已提交
505 506
}

507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
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 已提交
545
		if (entry.x === 'R' || entry.x === 'C') {
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
			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;
	}
}

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 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
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;
}

635 636 637 638 639 640 641 642 643 644
export function parseGitCommit(raw: string): Commit | null {
	const match = /^([0-9a-f]{40})\n(.*)\n([^]*)$/m.exec(raw.trim());
	if (!match) {
		return null;
	}

	const previousHashes = match[2] ? match[2].split(' ') : [];
	return { hash: match[1], message: match[3], previousHashes };
}

645 646 647 648
export interface DiffOptions {
	cached?: boolean;
}

J
Joao Moreno 已提交
649 650 651 652
export class Repository {

	constructor(
		private _git: Git,
653
		private repositoryRoot: string
J
Joao Moreno 已提交
654 655 656 657 658 659
	) { }

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

J
Joao Moreno 已提交
660 661
	get root(): string {
		return this.repositoryRoot;
J
Joao Moreno 已提交
662 663 664
	}

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

J
Joao Moreno 已提交
669
	stream(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
670
		return this.git.stream(this.repositoryRoot, args, options);
J
Joao Moreno 已提交
671 672
	}

J
Joao Moreno 已提交
673
	spawn(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
674 675 676
		return this.git.spawn(args, options);
	}

J
Joao Moreno 已提交
677
	async config(scope: string, key: string, value: any, options: SpawnOptions): Promise<string> {
J
Joao Moreno 已提交
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
		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;
	}

694
	async bufferString(object: string, encoding: string = 'utf8', autoGuessEncoding = false): Promise<string> {
J
Joao Moreno 已提交
695
		const stdout = await this.buffer(object);
696 697 698 699 700

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

J
Joao Moreno 已提交
701 702 703
		encoding = iconv.encodingExists(encoding) ? encoding : 'utf8';

		return iconv.decode(stdout, encoding);
J
Joao Moreno 已提交
704 705 706
	}

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

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

J
Joao Moreno 已提交
713
		const { exitCode, stdout } = await exec(child);
J
Joao Moreno 已提交
714 715

		if (exitCode) {
J
Joao Moreno 已提交
716
			return Promise.reject<Buffer>(new GitError({
J
Joao Moreno 已提交
717 718 719 720 721 722
				message: 'Could not show object.',
				exitCode
			}));
		}

		return stdout;
J
Joao Moreno 已提交
723 724
	}

J
Joao Moreno 已提交
725
	async lstree(treeish: string, path: string): Promise<{ mode: string, object: string, size: number }> {
J
Joao Moreno 已提交
726 727 728 729 730 731 732 733 734 735 736 737 738
		if (!treeish) { // index
			const { stdout } = await this.run(['ls-files', '--stage', '--', path]);

			const match = /^(\d+)\s+([0-9a-f]{40})\s+(\d+)/.exec(stdout);

			if (!match) {
				throw new GitError({ message: 'Error running ls-files' });
			}

			const [, mode, object] = match;
			const catFile = await this.run(['cat-file', '-s', object]);
			const size = parseInt(catFile.stdout);

J
Joao Moreno 已提交
739
			return { mode, object, size };
J
Joao Moreno 已提交
740 741
		}

J
Joao Moreno 已提交
742 743 744 745 746 747 748 749
		const { stdout } = await this.run(['ls-tree', '-l', treeish, '--', path]);

		const match = /^(\d+)\s+(\w+)\s+([0-9a-f]{40})\s+(\d+)/.exec(stdout);

		if (!match) {
			throw new GitError({ message: 'Error running ls-tree' });
		}

J
Joao Moreno 已提交
750
		const [, mode, , object, size] = match;
J
Joao Moreno 已提交
751
		return { mode, object, size: parseInt(size) };
J
Joao Moreno 已提交
752 753 754 755 756 757 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 785 786 787 788 789 790 791 792 793
	}

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

794 795 796 797 798 799 800 801 802 803 804 805 806
	async diff(path: string, options: DiffOptions = {}): Promise<string> {
		const args = ['diff'];

		if (options.cached) {
			args.push('--cached');
		}

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

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

J
Joao Moreno 已提交
807 808 809 810 811 812 813 814 815 816 817 818 819
	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> {
820
		const child = this.stream(['hash-object', '--stdin', '-w', '--path', path], { stdio: [null, null, null] });
J
Joao Moreno 已提交
821 822 823
		child.stdin.end(data, 'utf8');

		const { exitCode, stdout } = await exec(child);
J
Joao Moreno 已提交
824
		const hash = stdout.toString('utf8');
J
Joao Moreno 已提交
825 826 827 828 829 830 831 832

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

J
Joao Moreno 已提交
833 834 835 836 837 838 839 840 841 842
		let mode: string;

		try {
			const details = await this.lstree('HEAD', path);
			mode = details.mode;
		} catch (err) {
			mode = '100644';
		}

		await this.run(['update-index', '--cacheinfo', mode, hash, path]);
J
Joao Moreno 已提交
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
	}

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

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

J
Joao Moreno 已提交
871
		if (opts.all) {
J
Joao Moreno 已提交
872 873 874
			args.push('--all');
		}

J
Joao Moreno 已提交
875
		if (opts.amend) {
J
Joao Moreno 已提交
876 877 878
			args.push('--amend');
		}

J
Joao Moreno 已提交
879
		if (opts.signoff) {
J
Joao Moreno 已提交
880 881 882
			args.push('--signoff');
		}

883 884 885 886
		if (opts.signCommit) {
			args.push('-S');
		}

J
Joao Moreno 已提交
887 888 889
		try {
			await this.run(args, { input: message || '' });
		} catch (commitErr) {
890 891 892
			await this.handleCommitError(commitErr);
		}
	}
J
Joao Moreno 已提交
893

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

897 898 899 900 901 902
		try {
			await this.run(args);
		} catch (commitErr) {
			await this.handleCommitError(commitErr);
		}
	}
J
Joao Moreno 已提交
903

904 905 906
	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 已提交
907 908
			throw commitErr;
		}
909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924

		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;
J
Joao Moreno 已提交
925 926 927 928 929 930 931
	}

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

932 933
	async deleteBranch(name: string, force?: boolean): Promise<void> {
		const args = ['branch', force ? '-D' : '-d', name];
M
Maik Riechert 已提交
934 935 936
		await this.run(args);
	}

937 938 939 940 941
	async renameBranch(name: string): Promise<void> {
		const args = ['branch', '-m', name];
		await this.run(args);
	}

942 943 944 945 946
	async deleteRef(ref: string): Promise<void> {
		const args = ['update-ref', '-d', ref];
		await this.run(args);
	}

J
Joao Moreno 已提交
947 948 949 950 951 952 953 954 955 956 957 958
	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;
		}
959 960
	}

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

J
Joao Moreno 已提交
964 965
		if (message) {
			args = [...args, '-a', name, '-m', message];
966
		} else {
J
Joao Moreno 已提交
967
			args = [...args, name];
968 969 970 971 972
		}

		await this.run(args);
	}

J
Joao Moreno 已提交
973
	async clean(paths: string[]): Promise<void> {
J
Joao Moreno 已提交
974 975 976
		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 已提交
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008

		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 已提交
1009
	async revert(treeish: string, paths: string[]): Promise<void> {
J
Joao Moreno 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
		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;
		}
	}

M
Matt Shirley 已提交
1053
	async pull(rebase?: boolean, remote?: string, branch?: string): Promise<void> {
J
Joao Moreno 已提交
1054
		const args = ['pull', '--tags'];
J
Joao Moreno 已提交
1055 1056 1057 1058 1059

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

M
Matt Shirley 已提交
1060
		if (remote && branch) {
1061
			args.push(remote);
M
Matt Shirley 已提交
1062
			args.push(branch);
1063 1064
		}

J
Joao Moreno 已提交
1065 1066 1067 1068 1069 1070 1071 1072 1073
		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 已提交
1074 1075
			} 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 已提交
1076 1077 1078 1079 1080 1081 1082
				err.gitErrorCode = GitErrorCodes.DirtyWorkTree;
			}

			throw err;
		}
	}

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

J
Joao Moreno 已提交
1086
		if (setUpstream) {
J
Joao Moreno 已提交
1087 1088 1089
			args.push('-u');
		}

1090 1091
		if (tags) {
			args.push('--tags');
J
Joao Moreno 已提交
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
		}

		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;
1109 1110
			} else if (/^fatal: The current branch .* has no upstream branch/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoUpstreamBranch;
J
Joao Moreno 已提交
1111 1112 1113 1114 1115 1116
			}

			throw err;
		}
	}

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

1121 1122 1123 1124
			if (includeUntracked) {
				args.push('-u');
			}

J
Joao Moreno 已提交
1125 1126
			if (message) {
				args.push('--', message);
1127 1128 1129 1130 1131 1132 1133
			}

			await this.run(args);
		} catch (err) {
			if (/No local changes to save/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoLocalChanges;
			}
J
Joao Moreno 已提交
1134 1135 1136 1137 1138 1139 1140 1141 1142

			throw err;
		}
	}

	async popStash(index?: number): Promise<void> {
		try {
			const args = ['stash', 'pop'];

1143
			if (typeof index === 'number') {
J
Joao Moreno 已提交
1144
				args.push(`stash@{${index}}`);
1145
			}
J
Joao Moreno 已提交
1146 1147 1148 1149 1150 1151

			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 || '')) {
1152 1153
				err.gitErrorCode = GitErrorCodes.LocalChangesOverwritten;
			}
J
Joao Moreno 已提交
1154

1155 1156 1157 1158
			throw err;
		}
	}

1159 1160
	getStatus(limit = 5000): Promise<{ status: IFileStatus[]; didHitLimit: boolean; }> {
		return new Promise<{ status: IFileStatus[]; didHitLimit: boolean; }>((c, e) => {
1161
			const parser = new GitStatusParser();
J
Joao Moreno 已提交
1162 1163
			const env = { GIT_OPTIONAL_LOCKS: '0' };
			const child = this.stream(['status', '-z', '-u'], { env });
1164

M
Matt Bierner 已提交
1165
			const onExit = (exitCode: number) => {
1166
				if (exitCode !== 0) {
1167 1168 1169 1170 1171 1172 1173 1174
					const stderr = stderrData.join('');
					return e(new GitError({
						message: 'Failed to execute git',
						stderr,
						exitCode,
						gitErrorCode: getGitErrorCode(stderr),
						gitCommand: 'status'
					}));
1175
				}
J
Joao Moreno 已提交
1176

1177 1178 1179
				c({ status: parser.status, didHitLimit: false });
			};

1180
			const onStdoutData = (raw: string) => {
1181 1182
				parser.update(raw);

J
Joao Moreno 已提交
1183
				if (parser.status.length > limit) {
1184
					child.removeListener('exit', onExit);
1185
					child.stdout.removeListener('data', onStdoutData);
1186 1187
					child.kill();

J
Joao Moreno 已提交
1188
					c({ status: parser.status.slice(0, limit), didHitLimit: true });
1189 1190 1191 1192
				}
			};

			child.stdout.setEncoding('utf8');
1193 1194 1195 1196 1197 1198
			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 已提交
1199
			child.on('error', cpErrorHandler(e));
1200
			child.on('exit', onExit);
1201
		});
J
Joao Moreno 已提交
1202 1203
	}

J
Joao Moreno 已提交
1204
	async getHEAD(): Promise<Ref> {
J
Joao Moreno 已提交
1205
		try {
J
Joao Moreno 已提交
1206
			const result = await this.run(['symbolic-ref', '--short', 'HEAD']);
J
Joao Moreno 已提交
1207 1208 1209 1210 1211 1212 1213

			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 已提交
1214
			const result = await this.run(['rev-parse', 'HEAD']);
J
Joao Moreno 已提交
1215 1216 1217 1218 1219 1220 1221 1222 1223

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

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

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

M
Matt Bierner 已提交
1227
		const fn = (line: string): Ref | null => {
J
Joao Moreno 已提交
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
			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 已提交
1244
			.filter(ref => !!ref) as Ref[];
J
Joao Moreno 已提交
1245 1246
	}

1247 1248
	async getStashes(): Promise<Stash[]> {
		const result = await this.run(['stash', 'list']);
J
Joao Moreno 已提交
1249
		const regex = /^stash@{(\d+)}:(.+)$/;
1250 1251
		const rawStashes = result.stdout.trim().split('\n')
			.filter(b => !!b)
M
Matt Bierner 已提交
1252
			.map(line => regex.exec(line) as RegExpExecArray)
1253
			.filter(g => !!g)
J
Joao Moreno 已提交
1254
			.map(([, index, description]: RegExpExecArray) => ({ index: parseInt(index), description }));
1255

J
Joao Moreno 已提交
1256 1257
		return rawStashes;
	}
1258

J
Joao Moreno 已提交
1259
	async getRemotes(): Promise<Remote[]> {
J
Joao Moreno 已提交
1260
		const result = await this.run(['remote', '--verbose']);
1261
		const lines = result.stdout.trim().split('\n').filter(l => !!l);
J
Joao Moreno 已提交
1262 1263
		const remotes: Remote[] = [];

1264 1265
		for (const line of lines) {
			const parts = line.split(/\s/);
J
Joao Moreno 已提交
1266 1267 1268 1269
			const [name, url, type] = parts;

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

1270
			if (!remote) {
J
Joao Moreno 已提交
1271
				remote = { name, isReadOnly: false };
1272 1273 1274
				remotes.push(remote);
			}

J
Joao Moreno 已提交
1275 1276 1277 1278 1279 1280 1281
			if (/fetch/i.test(type)) {
				remote.fetchUrl = url;
			} else if (/push/i.test(type)) {
				remote.pushUrl = url;
			} else {
				remote.fetchUrl = url;
				remote.pushUrl = url;
1282 1283 1284
			}

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

1288
		return remotes;
J
Joao Moreno 已提交
1289 1290
	}

J
Joao Moreno 已提交
1291
	async getBranch(name: string): Promise<Branch> {
J
Joao Moreno 已提交
1292 1293 1294 1295
		if (name === 'HEAD') {
			return this.getHEAD();
		}

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

		if (!result.stdout) {
J
Joao Moreno 已提交
1299
			return Promise.reject<Branch>(new Error('No such branch'));
J
Joao Moreno 已提交
1300 1301 1302 1303 1304
		}

		const commit = result.stdout.trim();

		try {
J
Joao Moreno 已提交
1305 1306 1307 1308 1309 1310 1311
			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 已提交
1312

J
Joao Moreno 已提交
1313 1314
			const upstream = { remote: match[1], name: match[2] };
			const res3 = await this.run(['rev-list', '--left-right', name + '...' + fullUpstream]);
J
Joao Moreno 已提交
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348

			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 已提交
1349
				templatePath = path.join(this.repositoryRoot, templatePath);
J
Joao Moreno 已提交
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
			}

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

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

J
Joao Moreno 已提交
1360
	async getCommit(ref: string): Promise<Commit> {
1361
		const result = await this.run(['show', '-s', '--format=%H\n%P\n%B', ref]);
1362
		return parseGitCommit(result.stdout) || Promise.reject<Commit>('bad commit format');
J
Joao Moreno 已提交
1363
	}
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383

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