git.ts 54.0 KB
Newer Older
J
Joao Moreno 已提交
1 2 3 4 5
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

6
import { promises as fs, exists, realpath } from 'fs';
J
Joao Moreno 已提交
7
import * as path from 'path';
J
Joao Moreno 已提交
8
import * as os from 'os';
J
Joao Moreno 已提交
9
import * as cp from 'child_process';
10
import * as which from 'which';
11
import { EventEmitter } from 'events';
12
import * as iconv from 'iconv-lite-umd';
J
Joao Moreno 已提交
13
import * as filetype from 'file-type';
J
Joao Moreno 已提交
14
import { assign, groupBy, IDisposable, toDisposable, dispose, mkdirp, readBytes, detectUnicodeEncoding, Encoding, onceEvent, splitInChunks, Limiter } from './util';
15
import { CancellationToken, Progress, Uri, workspace } from 'vscode';
J
Joao Moreno 已提交
16
import { detectEncoding } from './encoding';
17
import { Ref, RefType, Branch, Remote, GitErrorCodes, LogOptions, Change, Status, CommitOptions, BranchQuery } from './api/git';
J
Joao Moreno 已提交
18 19
import * as byline from 'byline';
import { StringDecoder } from 'string_decoder';
J
Joao Moreno 已提交
20

J
Joao Moreno 已提交
21 22
// https://github.com/microsoft/vscode/issues/65693
const MAX_CLI_LENGTH = 30000;
23
const isWindows = process.platform === 'win32';
J
Joao Moreno 已提交
24 25 26 27 28 29

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

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

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

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

48
// TODO@eamodio: Move to git.d.ts once we are good with the api
E
Eric Amodio 已提交
49 50 51 52
/**
 * Log file options.
 */
export interface LogFileOptions {
53 54 55 56 57 58 59
	/** Optional. The maximum number of log entries to retrieve. */
	readonly maxEntries?: number | string;
	/** Optional. The Git sha (hash) to start retrieving log entries from. */
	readonly hash?: string;
	/** Optional. Specifies whether to start retrieving log entries in reverse order. */
	readonly reverse?: boolean;
	readonly sortByAuthorDate?: boolean;
E
Eric Amodio 已提交
60 61
}

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

J
Joao Moreno 已提交
66
function findSpecificGit(path: string, onLookup: (path: string) => void): Promise<IGit> {
J
Joao Moreno 已提交
67
	return new Promise<IGit>((c, e) => {
J
Joao Moreno 已提交
68 69
		onLookup(path);

J
Joao Moreno 已提交
70 71
		const buffers: Buffer[] = [];
		const child = cp.spawn(path, ['--version']);
72
		child.stdout.on('data', (b: Buffer) => buffers.push(b));
J
Joao Moreno 已提交
73
		child.on('error', cpErrorHandler(e));
J
Joao Moreno 已提交
74 75 76 77
		child.on('exit', code => code ? e(new Error('Not found')) : c({ path, version: parseVersion(Buffer.concat(buffers).toString('utf8').trim()) }));
	});
}

J
Joao Moreno 已提交
78
function findGitDarwin(onLookup: (path: string) => void): Promise<IGit> {
J
Joao Moreno 已提交
79 80 81 82 83 84 85 86 87
	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 已提交
88 89
				onLookup(path);

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

J
Joao Moreno 已提交
93 94 95 96
					if (err) {
						return e('git not found');
					}

J
Joao 已提交
97
					return c({ path, version: parseVersion(stdout.trim()) });
J
Joao Moreno 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
				});
			}

			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 已提交
120
function findSystemGitWin32(base: string, onLookup: (path: string) => void): Promise<IGit> {
J
Joao Moreno 已提交
121 122 123 124
	if (!base) {
		return Promise.reject<IGit>('Not found');
	}

J
Joao Moreno 已提交
125
	return findSpecificGit(path.join(base, 'Git', 'cmd', 'git.exe'), onLookup);
J
Joao Moreno 已提交
126 127
}

128 129 130 131 132
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 已提交
133 134
function findGitWin32(onLookup: (path: string) => void): Promise<IGit> {
	return findSystemGitWin32(process.env['ProgramW6432'] as string, onLookup)
R
Rob Lourens 已提交
135 136 137 138
		.then(undefined, () => findSystemGitWin32(process.env['ProgramFiles(x86)'] as string, onLookup))
		.then(undefined, () => findSystemGitWin32(process.env['ProgramFiles'] as string, onLookup))
		.then(undefined, () => findSystemGitWin32(path.join(process.env['LocalAppData'] as string, 'Programs'), onLookup))
		.then(undefined, () => findGitWin32InPath(onLookup));
J
Joao Moreno 已提交
139 140
}

W
WhizSid 已提交
141 142
export async function findGit(hint: string | string[] | undefined, onLookup: (path: string) => void): Promise<IGit> {
	const hints = Array.isArray(hint) ? hint : hint ? [hint] : [];
J
Joao Moreno 已提交
143

W
WhizSid 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
	for (const hint of hints) {
		try {
			return await findSpecificGit(hint, onLookup);
		} catch {
			// noop
		}
	}

	try {
		switch (process.platform) {
			case 'darwin': return await findGitDarwin(onLookup);
			case 'win32': return await findGitWin32(onLookup);
			default: return await findSpecificGit('git', onLookup);
		}
	} catch {
		// noop
	}

	throw new Error('Git installation not found.');
J
Joao Moreno 已提交
163 164
}

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

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

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

J
Joao Moreno 已提交
202 203
	const disposables: IDisposable[] = [];

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

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

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

J
Joao Moreno 已提交
240 241 242 243 244 245
				e(new GitError({ message: 'Cancelled' }));
			});
		});

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

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

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

export class GitError {

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

	constructor(data: IGitErrorData) {
		if (data.error) {
			this.error = data.error;
			this.message = data.error.message;
		} else {
R
Rob Lourens 已提交
280
			this.error = undefined;
M
Matt Bierner 已提交
281
			this.message = '';
J
Joao Moreno 已提交
282 283 284
		}

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

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

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

		return result;
	}
}

export interface IGitOptions {
	gitPath: string;
	version: string;
312
	env?: any;
J
Joao Moreno 已提交
313 314
}

315 316 317
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;
318
	} else if (/Authentication failed/i.test(stderr)) {
319
		return GitErrorCodes.AuthenticationFailed;
J
Joao Moreno 已提交
320
	} else if (/Not a git repository/i.test(stderr)) {
321 322 323 324 325 326 327 328 329
		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;
330 331
	} else if (/branch '.+' is not fully merged/.test(stderr)) {
		return GitErrorCodes.BranchNotFullyMerged;
332 333
	} else if (/Couldn\'t find remote ref/.test(stderr)) {
		return GitErrorCodes.NoRemoteReference;
334 335 336 337
	} 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;
338 339
	} else if (/Please,? commit your changes or stash them/.test(stderr)) {
		return GitErrorCodes.DirtyWorkTree;
340 341
	}

R
Rob Lourens 已提交
342
	return undefined;
343 344
}

J
Joao Moreno 已提交
345 346 347 348 349 350
// https://github.com/microsoft/vscode/issues/89373
// https://github.com/git-for-windows/git/issues/2478
function sanitizePath(path: string): string {
	return path.replace(/^([a-z]):\\/i, (_, letter) => `${letter.toUpperCase()}:\\`);
}

351
const COMMIT_FORMAT = '%H%n%aN%n%aE%n%at%n%ct%n%P%n%B';
352

J
João Moreno 已提交
353 354 355 356 357
export interface ICloneOptions {
	readonly parentPath: string;
	readonly progress: Progress<{ increment: number }>;
	readonly recursive?: boolean;
}
358

J
Joao Moreno 已提交
359 360
export class Git {

J
Joao Moreno 已提交
361
	readonly path: string;
362
	private env: any;
J
Joao Moreno 已提交
363

364 365
	private _onOutput = new EventEmitter();
	get onOutput(): EventEmitter { return this._onOutput; }
J
Joao Moreno 已提交
366

J
Joao Moreno 已提交
367
	constructor(options: IGitOptions) {
J
Joao Moreno 已提交
368
		this.path = options.gitPath;
369
		this.env = options.env || {};
J
Joao Moreno 已提交
370 371
	}

J
Joao Moreno 已提交
372 373
	open(repository: string, dotGit: string): Repository {
		return new Repository(this, repository, dotGit);
J
Joao Moreno 已提交
374 375
	}

J
Joao Moreno 已提交
376 377 378 379 380
	async init(repository: string): Promise<void> {
		await this.exec(repository, ['init']);
		return;
	}

J
João Moreno 已提交
381
	async clone(url: string, options: ICloneOptions, cancellationToken?: CancellationToken): Promise<string> {
382
		let baseFolderName = decodeURI(url).replace(/[\/]+$/, '').replace(/^.*[\/\\]/, '').replace(/\.git$/, '') || 'repository';
383
		let folderName = baseFolderName;
J
João Moreno 已提交
384
		let folderPath = path.join(options.parentPath, folderName);
385 386
		let count = 1;

J
Joao Moreno 已提交
387
		while (count < 20 && await new Promise(c => exists(folderPath, c))) {
388
			folderName = `${baseFolderName}-${count++}`;
J
João Moreno 已提交
389
			folderPath = path.join(options.parentPath, folderName);
390
		}
J
Joao Moreno 已提交
391

J
João Moreno 已提交
392
		await mkdirp(options.parentPath);
J
Joao Moreno 已提交
393

J
Joao Moreno 已提交
394 395 396
		const onSpawn = (child: cp.ChildProcess) => {
			const decoder = new StringDecoder('utf8');
			const lineStream = new byline.LineStream({ encoding: 'utf8' });
397
			child.stderr!.on('data', (buffer: Buffer) => lineStream.write(decoder.write(buffer)));
J
Joao Moreno 已提交
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415

			let totalProgress = 0;
			let previousProgress = 0;

			lineStream.on('data', (line: string) => {
				let match: RegExpMatchArray | null = null;

				if (match = /Counting objects:\s*(\d+)%/i.exec(line)) {
					totalProgress = Math.floor(parseInt(match[1]) * 0.1);
				} else if (match = /Compressing objects:\s*(\d+)%/i.exec(line)) {
					totalProgress = 10 + Math.floor(parseInt(match[1]) * 0.1);
				} else if (match = /Receiving objects:\s*(\d+)%/i.exec(line)) {
					totalProgress = 20 + Math.floor(parseInt(match[1]) * 0.4);
				} else if (match = /Resolving deltas:\s*(\d+)%/i.exec(line)) {
					totalProgress = 60 + Math.floor(parseInt(match[1]) * 0.4);
				}

				if (totalProgress !== previousProgress) {
J
João Moreno 已提交
416
					options.progress.report({ increment: totalProgress - previousProgress });
J
Joao Moreno 已提交
417 418 419 420 421
					previousProgress = totalProgress;
				}
			});
		};

J
Joao Moreno 已提交
422
		try {
J
Jordan Bayles 已提交
423
			let command = ['clone', url.includes(' ') ? encodeURI(url) : url, folderPath, '--progress'];
J
João Moreno 已提交
424
			if (options.recursive) {
J
Jordan Bayles 已提交
425 426
				command.push('--recursive');
			}
J
João Moreno 已提交
427
			await this.exec(options.parentPath, command, { cancellationToken, onSpawn });
J
Joao Moreno 已提交
428 429 430 431 432 433 434 435 436
		} 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 已提交
437 438 439
		return folderPath;
	}

J
Joao Moreno 已提交
440
	async getRepositoryRoot(repositoryPath: string): Promise<string> {
441
		const result = await this.exec(repositoryPath, ['rev-parse', '--show-toplevel'], { log: false });
442

J
jeanp413 已提交
443
		// Keep trailing spaces which are part of the directory name
J
João Moreno 已提交
444
		const repoPath = path.normalize(result.stdout.trimLeft().replace(/[\r\n]+$/, ''));
445 446 447 448 449 450 451 452 453 454 455 456

		if (isWindows) {
			// On Git 2.25+ if you call `rev-parse --show-toplevel` on a mapped drive, instead of getting the mapped drive path back, you get the UNC path for the mapped drive.
			// So we will try to normalize it back to the mapped drive path, if possible
			const repoUri = Uri.file(repoPath);
			const pathUri = Uri.file(repositoryPath);
			if (repoUri.authority.length !== 0 && pathUri.authority.length === 0) {
				let match = /(?<=^\/?)([a-zA-Z])(?=:\/)/.exec(pathUri.path);
				if (match !== null) {
					const [, letter] = match;

					try {
457
						const networkPath = await new Promise<string | undefined>(resolve =>
458
							realpath.native(`${letter}:`, { encoding: 'utf8' }, (err, resolvedPath) =>
E
Eric Amodio 已提交
459
								resolve(err !== null ? undefined : resolvedPath),
460 461 462
							),
						);
						if (networkPath !== undefined) {
463
							return path.normalize(
464 465 466 467
								repoUri.fsPath.replace(
									networkPath,
									`${letter.toLowerCase()}:${networkPath.endsWith('\\') ? '\\' : ''}`
								),
468 469 470 471 472 473 474 475 476 477
							);
						}
					} catch { }
				}

				return path.normalize(pathUri.fsPath);
			}
		}

		return repoPath;
J
Joao Moreno 已提交
478 479
	}

J
Joao Moreno 已提交
480
	async getRepositoryDotGit(repositoryPath: string): Promise<string> {
481 482 483 484 485 486 487 488
		const result = await this.exec(repositoryPath, ['rev-parse', '--git-dir']);
		let dotGitPath = result.stdout.trim();

		if (!path.isAbsolute(dotGitPath)) {
			dotGitPath = path.join(repositoryPath, dotGitPath);
		}

		return path.normalize(dotGitPath);
J
Joao Moreno 已提交
489 490
	}

J
Joao Moreno 已提交
491
	async exec(cwd: string, args: string[], options: SpawnOptions = {}): Promise<IExecutionResult<string>> {
J
Joao Moreno 已提交
492
		options = assign({ cwd }, options || {});
J
Joao Moreno 已提交
493
		return await this._exec(args, options);
J
Joao Moreno 已提交
494 495
	}

J
Joao Moreno 已提交
496 497 498 499
	async exec2(args: string[], options: SpawnOptions = {}): Promise<IExecutionResult<string>> {
		return await this._exec(args, options);
	}

J
Joao Moreno 已提交
500
	stream(cwd: string, args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
501
		options = assign({ cwd }, options || {});
J
Joao Moreno 已提交
502
		return this.spawn(args, options);
J
Joao Moreno 已提交
503 504
	}

J
Joao Moreno 已提交
505
	private async _exec(args: string[], options: SpawnOptions = {}): Promise<IExecutionResult<string>> {
J
Joao Moreno 已提交
506
		const child = this.spawn(args, options);
J
Joao Moreno 已提交
507

J
Joao Moreno 已提交
508 509 510 511
		if (options.onSpawn) {
			options.onSpawn(child);
		}

J
Joao Moreno 已提交
512
		if (options.input) {
513
			child.stdin!.end(options.input, 'utf8');
J
Joao Moreno 已提交
514 515
		}

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

J
Joao Moreno 已提交
518 519
		if (options.log !== false && bufferResult.stderr.length > 0) {
			this.log(`${bufferResult.stderr}\n`);
J
Joao Moreno 已提交
520 521
		}

J
Joao Moreno 已提交
522 523 524 525 526 527 528 529 530 531 532
		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 已提交
533 534 535 536
				message: 'Failed to execute git',
				stdout: result.stdout,
				stderr: result.stderr,
				exitCode: result.exitCode,
537
				gitErrorCode: getGitErrorCode(result.stderr),
J
Joao Moreno 已提交
538 539 540 541 542
				gitCommand: args[0]
			}));
		}

		return result;
J
Joao Moreno 已提交
543 544
	}

J
Joao Moreno 已提交
545
	spawn(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
546
		if (!this.path) {
J
Joao Moreno 已提交
547 548 549 550 551 552 553 554 555 556 557
			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
		}

558
		options.env = assign({}, process.env, this.env, options.env || {}, {
J
Joao Moreno 已提交
559
			VSCODE_GIT_COMMAND: args[0],
560
			LC_ALL: 'en_US.UTF-8',
561
			LANG: 'en_US.UTF-8',
562
			GIT_PAGER: 'cat'
J
Joao Moreno 已提交
563
		});
J
Joao Moreno 已提交
564

J
Joao Moreno 已提交
565 566 567 568
		if (options.cwd) {
			options.cwd = sanitizePath(options.cwd);
		}

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

J
Joao Moreno 已提交
573
		return cp.spawn(this.path, args, options);
J
Joao Moreno 已提交
574 575 576
	}

	private log(output: string): void {
577
		this._onOutput.emit('log', output);
J
Joao Moreno 已提交
578
	}
J
Joao Moreno 已提交
579 580
}

J
Joao Moreno 已提交
581
export interface Commit {
J
Joao Moreno 已提交
582 583
	hash: string;
	message: string;
J
Joao Moreno 已提交
584
	parents: string[];
585 586 587
	authorDate?: Date;
	authorName?: string;
	authorEmail?: string;
588
	commitDate?: Date;
J
Joao Moreno 已提交
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
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 已提交
629
		if (entry.x === 'R' || entry.x === 'C') {
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
			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;
	}
}

657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
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;
		}

J
João Moreno 已提交
691
		const propertyMatch = /^\s*(\w+)\s*=\s*(.*)$/.exec(line);
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718

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

719
const commitRegex = /([0-9a-f]{40})\n(.*)\n(.*)\n(.*)\n(.*)\n(.*)(?:\n([^]*?))?(?:\x00)/gm;
720 721 722 723 724

export function parseGitCommits(data: string): Commit[] {
	let commits: Commit[] = [];

	let ref;
725 726 727 728
	let authorName;
	let authorEmail;
	let authorDate;
	let commitDate;
729 730 731 732 733 734 735 736 737 738
	let parents;
	let message;
	let match;

	do {
		match = commitRegex.exec(data);
		if (match === null) {
			break;
		}

739
		[, ref, authorName, authorEmail, authorDate, commitDate, parents, message] = match;
740

741 742 743 744 745 746 747 748 749
		if (message[message.length - 1] === '\n') {
			message = message.substr(0, message.length - 1);
		}

		// Stop excessive memory usage by using substr -- https://bugs.chromium.org/p/v8/issues/detail?id=2869
		commits.push({
			hash: ` ${ref}`.substr(1),
			message: ` ${message}`.substr(1),
			parents: parents ? parents.split(' ') : [],
750 751 752 753
			authorDate: new Date(Number(authorDate) * 1000),
			authorName: ` ${authorName}`.substr(1),
			authorEmail: ` ${authorEmail}`.substr(1),
			commitDate: new Date(Number(commitDate) * 1000),
754 755
		});
	} while (true);
756

757
	return commits;
758 759
}

760 761 762 763
interface LsTreeElement {
	mode: string;
	type: string;
	object: string;
J
Joao Moreno 已提交
764
	size: string;
765 766 767 768 769 770
	file: string;
}

export function parseLsTree(raw: string): LsTreeElement[] {
	return raw.split('\n')
		.filter(l => !!l)
J
Joao Moreno 已提交
771
		.map(line => /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.*)$/.exec(line)!)
772
		.filter(m => !!m)
J
Joao Moreno 已提交
773
		.map(([, mode, type, object, size, file]) => ({ mode, type, object, size, file }));
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
}

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

791 792
export interface PullOptions {
	unshallow?: boolean;
J
Joao Moreno 已提交
793
	tags?: boolean;
794
	readonly cancellationToken?: CancellationToken;
795 796
}

J
Joao Moreno 已提交
797 798
export enum ForcePushMode {
	Force,
J
Joao Moreno 已提交
799
	ForceWithLease
J
Joao Moreno 已提交
800 801
}

J
Joao Moreno 已提交
802 803 804 805
export class Repository {

	constructor(
		private _git: Git,
J
Joao Moreno 已提交
806 807
		private repositoryRoot: string,
		readonly dotGit: string
J
Joao Moreno 已提交
808 809 810 811 812 813
	) { }

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

J
Joao Moreno 已提交
814 815
	get root(): string {
		return this.repositoryRoot;
J
Joao Moreno 已提交
816 817 818
	}

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

J
Joao Moreno 已提交
823
	stream(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
824
		return this.git.stream(this.repositoryRoot, args, options);
J
Joao Moreno 已提交
825 826
	}

J
Joao Moreno 已提交
827
	spawn(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
828 829 830
		return this.git.spawn(args, options);
	}

J
Joao Moreno 已提交
831
	async config(scope: string, key: string, value: any = null, options: SpawnOptions = {}): Promise<string> {
J
Joao Moreno 已提交
832 833 834 835 836 837 838 839 840 841 842 843 844
		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 已提交
845
		return result.stdout.trim();
J
Joao Moreno 已提交
846 847
	}

J
Joao Moreno 已提交
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
	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) };
		});
	}

866
	async log(options?: LogOptions): Promise<Commit[]> {
E
Eric Amodio 已提交
867 868
		const maxEntries = options?.maxEntries ?? 32;
		const args = ['log', `-n${maxEntries}`, `--format=${COMMIT_FORMAT}`, '-z', '--'];
A
Alex Ross 已提交
869 870 871
		if (options?.path) {
			args.push(options.path);
		}
872

873 874
		const result = await this.run(args);
		if (result.exitCode) {
875
			// An empty repo
876 877 878
			return [];
		}

879 880
		return parseGitCommits(result.stdout);
	}
881

882
	async logFile(uri: Uri, options?: LogFileOptions): Promise<Commit[]> {
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
		const args = ['log', `--format=${COMMIT_FORMAT}`, '-z'];

		if (options?.maxEntries && !options?.reverse) {
			args.push(`-n${options.maxEntries}`);
		}

		if (options?.hash) {
			// If we are reversing, we must add a range (with HEAD) because we are using --ancestry-path for better reverse walking
			if (options?.reverse) {
				args.push('--reverse', '--ancestry-path', `${options.hash}..HEAD`);
			} else {
				args.push(options.hash);
			}
		}

		if (options?.sortByAuthorDate) {
			args.push('--author-date-order');
		}

		args.push('--', uri.fsPath);
903

904 905 906 907
		const result = await this.run(args);
		if (result.exitCode) {
			// No file history, e.g. a new file or untracked
			return [];
908 909
		}

910
		return parseGitCommits(result.stdout);
911 912
	}

913
	async bufferString(object: string, encoding: string = 'utf8', autoGuessEncoding = false): Promise<string> {
J
Joao Moreno 已提交
914
		const stdout = await this.buffer(object);
915 916 917 918 919

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

J
Joao Moreno 已提交
920 921 922
		encoding = iconv.encodingExists(encoding) ? encoding : 'utf8';

		return iconv.decode(stdout, encoding);
J
Joao Moreno 已提交
923 924 925
	}

	async buffer(object: string): Promise<Buffer> {
J
João Moreno 已提交
926
		const child = this.stream(['show', '--textconv', object]);
J
Joao Moreno 已提交
927 928

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

932
		const { exitCode, stdout, stderr } = await exec(child);
J
Joao Moreno 已提交
933 934

		if (exitCode) {
935
			const err = new GitError({
J
Joao Moreno 已提交
936 937
				message: 'Could not show object.',
				exitCode
938 939 940 941 942 943 944
			});

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

			return Promise.reject<Buffer>(err);
J
Joao Moreno 已提交
945 946 947
		}

		return stdout;
J
Joao Moreno 已提交
948 949
	}

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

J
Joao Moreno 已提交
954
			if (elements.length === 0) {
J
Joao Moreno 已提交
955
				throw new GitError({ message: 'Path not known by git', gitErrorCode: GitErrorCodes.UnknownPath });
J
Joao Moreno 已提交
956 957
			}

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

J
Joao Moreno 已提交
962
			return { mode, object, size };
J
Joao Moreno 已提交
963 964
		}

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

J
Joao Moreno 已提交
967
		if (elements.length === 0) {
J
Joao Moreno 已提交
968
			throw new GitError({ message: 'Path not known by git', gitErrorCode: GitErrorCodes.UnknownPath });
J
Joao Moreno 已提交
969 970
		}

J
Joao Moreno 已提交
971
		const { mode, object, size } = elements[0];
J
Joao Moreno 已提交
972
		return { mode, object, size: parseInt(size) };
J
Joao Moreno 已提交
973 974
	}

J
Joao Moreno 已提交
975
	async lstree(treeish: string, path: string): Promise<LsTreeElement[]> {
J
Joao Moreno 已提交
976
		const { stdout } = await this.run(['ls-tree', '-l', treeish, '--', sanitizePath(path)]);
977 978
		return parseLsTree(stdout);
	}
979

980
	async lsfiles(path: string): Promise<LsFilesElement[]> {
J
Joao Moreno 已提交
981
		const { stdout } = await this.run(['ls-files', '--stage', '--', sanitizePath(path)]);
982
		return parseLsFiles(stdout);
983 984
	}

J
Joao Moreno 已提交
985
	async getGitRelativePath(ref: string, relativePath: string): Promise<string> {
986 987
		const relativePathLowercase = relativePath.toLowerCase();
		const dirname = path.posix.dirname(relativePath) + '/';
J
Joao Moreno 已提交
988
		const elements: { file: string; }[] = ref ? await this.lstree(ref, dirname) : await this.lsfiles(dirname);
989 990 991 992
		const element = elements.filter(file => file.file.toLowerCase() === relativePathLowercase)[0];

		if (!element) {
			throw new GitError({ message: 'Git relative path not found.' });
993
		}
994 995

		return element.file;
996 997
	}

J
Joao Moreno 已提交
998
	async detectObjectType(object: string): Promise<{ mimetype: string, encoding?: string }> {
J
João Moreno 已提交
999
		const child = await this.stream(['show', '--textconv', object]);
1000
		const buffer = await readBytes(child.stdout!, 4100);
J
Joao Moreno 已提交
1001 1002 1003 1004 1005 1006 1007 1008 1009 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

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

1038 1039 1040 1041 1042 1043 1044
	async apply(patch: string, reverse?: boolean): Promise<void> {
		const args = ['apply', patch];

		if (reverse) {
			args.push('-R');
		}

1045 1046 1047 1048 1049 1050 1051 1052 1053
		try {
			await this.run(args);
		} catch (err) {
			if (/patch does not apply/.test(err.stderr)) {
				err.gitErrorCode = GitErrorCodes.PatchDoesNotApply;
			}

			throw err;
		}
1054 1055 1056
	}

	async diff(cached = false): Promise<string> {
1057 1058
		const args = ['diff'];

J
Joao Moreno 已提交
1059
		if (cached) {
1060 1061 1062 1063 1064 1065 1066
			args.push('--cached');
		}

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

1067 1068 1069 1070
	diffWithHEAD(): Promise<Change[]>;
	diffWithHEAD(path: string): Promise<string>;
	diffWithHEAD(path?: string | undefined): Promise<string | Change[]>;
	async diffWithHEAD(path?: string | undefined): Promise<string | Change[]> {
1071 1072 1073 1074
		if (!path) {
			return await this.diffFiles(false);
		}

J
Joao Moreno 已提交
1075
		const args = ['diff', '--', sanitizePath(path)];
J
Joao Moreno 已提交
1076 1077 1078 1079
		const result = await this.run(args);
		return result.stdout;
	}

1080 1081 1082
	diffWith(ref: string): Promise<Change[]>;
	diffWith(ref: string, path: string): Promise<string>;
	diffWith(ref: string, path?: string | undefined): Promise<string | Change[]>;
1083 1084 1085 1086 1087
	async diffWith(ref: string, path?: string): Promise<string | Change[]> {
		if (!path) {
			return await this.diffFiles(false, ref);
		}

J
Joao Moreno 已提交
1088
		const args = ['diff', ref, '--', sanitizePath(path)];
J
Joao Moreno 已提交
1089 1090 1091 1092
		const result = await this.run(args);
		return result.stdout;
	}

1093 1094 1095
	diffIndexWithHEAD(): Promise<Change[]>;
	diffIndexWithHEAD(path: string): Promise<string>;
	diffIndexWithHEAD(path?: string | undefined): Promise<string | Change[]>;
1096 1097 1098 1099 1100
	async diffIndexWithHEAD(path?: string): Promise<string | Change[]> {
		if (!path) {
			return await this.diffFiles(true);
		}

J
Joao Moreno 已提交
1101
		const args = ['diff', '--cached', '--', sanitizePath(path)];
J
Joao Moreno 已提交
1102 1103 1104 1105
		const result = await this.run(args);
		return result.stdout;
	}

1106 1107 1108
	diffIndexWith(ref: string): Promise<Change[]>;
	diffIndexWith(ref: string, path: string): Promise<string>;
	diffIndexWith(ref: string, path?: string | undefined): Promise<string | Change[]>;
1109 1110 1111 1112 1113
	async diffIndexWith(ref: string, path?: string): Promise<string | Change[]> {
		if (!path) {
			return await this.diffFiles(true, ref);
		}

J
Joao Moreno 已提交
1114
		const args = ['diff', '--cached', ref, '--', sanitizePath(path)];
J
Joao Moreno 已提交
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
		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;
	}

1125 1126 1127
	diffBetween(ref1: string, ref2: string): Promise<Change[]>;
	diffBetween(ref1: string, ref2: string, path: string): Promise<string>;
	diffBetween(ref1: string, ref2: string, path?: string | undefined): Promise<string | Change[]>;
1128 1129 1130 1131 1132 1133
	async diffBetween(ref1: string, ref2: string, path?: string): Promise<string | Change[]> {
		const range = `${ref1}...${ref2}`;
		if (!path) {
			return await this.diffFiles(false, range);
		}

J
Joao Moreno 已提交
1134
		const args = ['diff', range, '--', sanitizePath(path)];
J
Joao Moreno 已提交
1135 1136 1137 1138 1139
		const result = await this.run(args);

		return result.stdout.trim();
	}

1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
	private async diffFiles(cached: boolean, ref?: string): Promise<Change[]> {
		const args = ['diff', '--name-status', '-z', '--diff-filter=ADMR'];
		if (cached) {
			args.push('--cached');
		}

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

		const gitResult = await this.run(args);
		if (gitResult.exitCode) {
			return [];
		}

		const entries = gitResult.stdout.split('\x00');
		let index = 0;
		const result: Change[] = [];

		entriesLoop:
		while (index < entries.length - 1) {
			const change = entries[index++];
			const resourcePath = entries[index++];
			if (!change || !resourcePath) {
				break;
			}

E
Eric Amodio 已提交
1167
			const originalUri = Uri.file(path.isAbsolute(resourcePath) ? resourcePath : path.join(this.repositoryRoot, resourcePath));
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
			let status: Status = Status.UNTRACKED;

			// Copy or Rename status comes with a number, e.g. 'R100'. We don't need the number, so we use only first character of the status.
			switch (change[0]) {
				case 'M':
					status = Status.MODIFIED;
					break;

				case 'A':
					status = Status.INDEX_ADDED;
					break;

				case 'D':
					status = Status.DELETED;
					break;

				// Rename contains two paths, the second one is what the file is renamed/copied to.
				case 'R':
					if (index >= entries.length) {
						break;
					}

					const newPath = entries[index++];
					if (!newPath) {
						break;
					}

E
Eric Amodio 已提交
1195
					const uri = Uri.file(path.isAbsolute(newPath) ? newPath : path.join(this.repositoryRoot, newPath));
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220
					result.push({
						uri,
						renameUri: uri,
						originalUri,
						status: Status.INDEX_RENAMED
					});

					continue;

				default:
					// Unknown status
					break entriesLoop;
			}

			result.push({
				status,
				originalUri,
				uri: originalUri,
				renameUri: originalUri,
			});
		}

		return result;
	}

J
Joao Moreno 已提交
1221 1222 1223 1224 1225 1226 1227
	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 已提交
1228 1229 1230 1231 1232 1233 1234
	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 已提交
1235 1236 1237 1238 1239 1240 1241 1242 1243
	async add(paths: string[], opts?: { update?: boolean }): Promise<void> {
		const args = ['add'];

		if (opts && opts.update) {
			args.push('-u');
		} else {
			args.push('-A');
		}

J
Joao Moreno 已提交
1244
		if (paths && paths.length) {
1245
			for (const chunk of splitInChunks(paths.map(sanitizePath), MAX_CLI_LENGTH)) {
J
João Moreno 已提交
1246
				await this.run([...args, '--', ...chunk]);
1247
			}
J
Joao Moreno 已提交
1248
		} else {
J
João Moreno 已提交
1249
			await this.run([...args, '--', '.']);
J
Joao Moreno 已提交
1250 1251 1252
		}
	}

J
Joao Moreno 已提交
1253 1254 1255 1256 1257 1258 1259
	async rm(paths: string[]): Promise<void> {
		const args = ['rm', '--'];

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

J
Joao Moreno 已提交
1260
		args.push(...paths.map(sanitizePath));
J
Joao Moreno 已提交
1261 1262 1263 1264

		await this.run(args);
	}

J
Joao Moreno 已提交
1265
	async stage(path: string, data: string): Promise<void> {
J
Joao Moreno 已提交
1266
		const child = this.stream(['hash-object', '--stdin', '-w', '--path', sanitizePath(path)], { stdio: [null, null, null] });
1267
		child.stdin!.end(data, 'utf8');
J
Joao Moreno 已提交
1268 1269

		const { exitCode, stdout } = await exec(child);
J
Joao Moreno 已提交
1270
		const hash = stdout.toString('utf8');
J
Joao Moreno 已提交
1271 1272 1273 1274 1275 1276 1277 1278

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

J
Joao Moreno 已提交
1279
		const treeish = await this.getCommit('HEAD').then(() => 'HEAD', () => '');
J
Joao Moreno 已提交
1280
		let mode: string;
D
Darrien Singleton 已提交
1281
		let add: string = '';
J
Joao Moreno 已提交
1282 1283

		try {
1284
			const details = await this.getObjectDetails(treeish, path);
J
Joao Moreno 已提交
1285 1286
			mode = details.mode;
		} catch (err) {
J
Joao Moreno 已提交
1287 1288 1289 1290
			if (err.gitErrorCode !== GitErrorCodes.UnknownPath) {
				throw err;
			}

J
Joao Moreno 已提交
1291
			mode = '100644';
D
Darrien Singleton 已提交
1292
			add = '--add';
J
Joao Moreno 已提交
1293 1294
		}

D
Darrien Singleton 已提交
1295
		await this.run(['update-index', add, '--cacheinfo', mode, hash, path]);
J
Joao Moreno 已提交
1296 1297
	}

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

1301 1302 1303 1304
		if (opts.track) {
			args.push('--track');
		}

J
Joao Moreno 已提交
1305 1306 1307 1308 1309
		if (treeish) {
			args.push(treeish);
		}

		try {
J
Joao Moreno 已提交
1310
			if (paths && paths.length > 0) {
J
Joao Moreno 已提交
1311
				for (const chunk of splitInChunks(paths.map(sanitizePath), MAX_CLI_LENGTH)) {
J
Joao Moreno 已提交
1312 1313 1314 1315 1316
					await this.run([...args, '--', ...chunk]);
				}
			} else {
				await this.run(args);
			}
J
Joao Moreno 已提交
1317
		} catch (err) {
J
Joao Moreno 已提交
1318
			if (/Please,? commit your changes or stash them/.test(err.stderr || '')) {
J
Joao Moreno 已提交
1319 1320 1321 1322 1323 1324 1325
				err.gitErrorCode = GitErrorCodes.DirtyWorkTree;
			}

			throw err;
		}
	}

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

J
Joao Moreno 已提交
1329
		if (opts.all) {
J
Joao Moreno 已提交
1330 1331 1332
			args.push('--all');
		}

J
Joao Moreno 已提交
1333
		if (opts.amend) {
J
Joao Moreno 已提交
1334 1335 1336
			args.push('--amend');
		}

J
Joao Moreno 已提交
1337
		if (opts.signoff) {
J
Joao Moreno 已提交
1338 1339 1340
			args.push('--signoff');
		}

1341 1342 1343
		if (opts.signCommit) {
			args.push('-S');
		}
1344

T
Tom Basche 已提交
1345 1346 1347
		if (opts.empty) {
			args.push('--allow-empty');
		}
1348

1349 1350 1351 1352
		if (opts.noVerify) {
			args.push('--no-verify');
		}

J
Joao Moreno 已提交
1353 1354 1355
		try {
			await this.run(args, { input: message || '' });
		} catch (commitErr) {
1356 1357 1358
			await this.handleCommitError(commitErr);
		}
	}
J
Joao Moreno 已提交
1359

1360 1361 1362 1363
	async rebaseAbort(): Promise<void> {
		await this.run(['rebase', '--abort']);
	}

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

1367 1368 1369 1370 1371 1372
		try {
			await this.run(args);
		} catch (commitErr) {
			await this.handleCommitError(commitErr);
		}
	}
J
Joao Moreno 已提交
1373

1374 1375 1376
	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 已提交
1377 1378
			throw commitErr;
		}
1379 1380

		try {
J
Joao Moreno 已提交
1381 1382 1383 1384 1385
			await this.run(['config', '--get-all', 'user.name']);
		} catch (err) {
			err.gitErrorCode = GitErrorCodes.NoUserNameConfigured;
			throw err;
		}
1386 1387

		try {
J
Joao Moreno 已提交
1388 1389 1390 1391
			await this.run(['config', '--get-all', 'user.email']);
		} catch (err) {
			err.gitErrorCode = GitErrorCodes.NoUserEmailConfigured;
			throw err;
1392 1393 1394
		}

		throw commitErr;
J
Joao Moreno 已提交
1395 1396
	}

J
Joao Moreno 已提交
1397
	async branch(name: string, checkout: boolean, ref?: string): Promise<void> {
J
Joao Moreno 已提交
1398
		const args = checkout ? ['checkout', '-q', '-b', name, '--no-track'] : ['branch', '-q', name];
J
Joao Moreno 已提交
1399 1400 1401 1402 1403

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

J
Joao Moreno 已提交
1404 1405 1406
		await this.run(args);
	}

1407 1408
	async deleteBranch(name: string, force?: boolean): Promise<void> {
		const args = ['branch', force ? '-D' : '-d', name];
M
Maik Riechert 已提交
1409 1410 1411
		await this.run(args);
	}

1412 1413 1414 1415 1416
	async renameBranch(name: string): Promise<void> {
		const args = ['branch', '-m', name];
		await this.run(args);
	}

J
Joao Moreno 已提交
1417 1418 1419 1420 1421
	async setBranchUpstream(name: string, upstream: string): Promise<void> {
		const args = ['branch', '--set-upstream-to', upstream, name];
		await this.run(args);
	}

1422 1423 1424 1425 1426
	async deleteRef(ref: string): Promise<void> {
		const args = ['update-ref', '-d', ref];
		await this.run(args);
	}

J
Joao Moreno 已提交
1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
	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;
		}
1439 1440
	}

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

J
Joao Moreno 已提交
1444 1445
		if (message) {
			args = [...args, '-a', name, '-m', message];
1446
		} else {
J
Joao Moreno 已提交
1447
			args = [...args, name];
1448 1449 1450 1451 1452
		}

		await this.run(args);
	}

X
Xhulio Hasani 已提交
1453 1454 1455 1456 1457
	async deleteTag(name: string): Promise<void> {
		let args = ['tag', '-d', name];
		await this.run(args);
	}

J
Joao Moreno 已提交
1458
	async clean(paths: string[]): Promise<void> {
J
Joao Moreno 已提交
1459
		const pathsByGroup = groupBy(paths.map(sanitizePath), p => path.dirname(p));
J
Joao Moreno 已提交
1460
		const groups = Object.keys(pathsByGroup).map(k => pathsByGroup[k]);
J
Joao Moreno 已提交
1461

J
Joao Moreno 已提交
1462 1463
		const limiter = new Limiter(5);
		const promises: Promise<any>[] = [];
J
João Moreno 已提交
1464
		const args = ['clean', '-f', '-q'];
J
Joao Moreno 已提交
1465 1466

		for (const paths of groups) {
1467
			for (const chunk of splitInChunks(paths.map(sanitizePath), MAX_CLI_LENGTH)) {
J
João Moreno 已提交
1468
				promises.push(limiter.queue(() => this.run([...args, '--', ...chunk])));
J
Joao Moreno 已提交
1469
			}
J
Joao Moreno 已提交
1470
		}
J
Joao Moreno 已提交
1471 1472

		await Promise.all(promises);
J
Joao Moreno 已提交
1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
	}

	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> {
1490
		const args = ['reset', hard ? '--hard' : '--soft', treeish];
J
Joao Moreno 已提交
1491 1492 1493
		await this.run(args);
	}

J
Joao Moreno 已提交
1494
	async revert(treeish: string, paths: string[]): Promise<void> {
J
Joao Moreno 已提交
1495 1496 1497 1498 1499
		const result = await this.run(['branch']);
		let args: string[];

		// In case there are no branches, we must use rm --cached
		if (!result.stdout) {
J
João Moreno 已提交
1500
			args = ['rm', '--cached', '-r'];
J
Joao Moreno 已提交
1501
		} else {
J
João Moreno 已提交
1502
			args = ['reset', '-q', treeish];
J
Joao Moreno 已提交
1503 1504 1505
		}

		try {
1506
			if (paths && paths.length > 0) {
1507
				for (const chunk of splitInChunks(paths.map(sanitizePath), MAX_CLI_LENGTH)) {
J
João Moreno 已提交
1508
					await this.run([...args, '--', ...chunk]);
1509 1510
				}
			} else {
J
João Moreno 已提交
1511
				await this.run([...args, '--', '.']);
1512
			}
J
Joao Moreno 已提交
1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
		} 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 已提交
1524 1525 1526 1527 1528
	async addRemote(name: string, url: string): Promise<void> {
		const args = ['remote', 'add', name, url];
		await this.run(args);
	}

J
Joao Moreno 已提交
1529
	async removeRemote(name: string): Promise<void> {
J
João Moreno 已提交
1530 1531 1532 1533 1534 1535
		const args = ['remote', 'remove', name];
		await this.run(args);
	}

	async renameRemote(name: string, newName: string): Promise<void> {
		const args = ['remote', 'rename', name, newName];
J
Joao Moreno 已提交
1536 1537 1538
		await this.run(args);
	}

J
Joao Moreno 已提交
1539
	async fetch(options: { remote?: string, ref?: string, all?: boolean, prune?: boolean, depth?: number, silent?: boolean } = {}): Promise<void> {
J
Joao Moreno 已提交
1540
		const args = ['fetch'];
J
Joao Moreno 已提交
1541
		const spawnOptions: SpawnOptions = {};
J
Joao Moreno 已提交
1542

J
Joao Moreno 已提交
1543 1544
		if (options.remote) {
			args.push(options.remote);
J
Joao Moreno 已提交
1545

J
Joao Moreno 已提交
1546 1547
			if (options.ref) {
				args.push(options.ref);
J
Joao Moreno 已提交
1548
			}
J
Joao Moreno 已提交
1549 1550
		} else if (options.all) {
			args.push('--all');
J
Joao Moreno 已提交
1551 1552
		}

R
Ryan Scott 已提交
1553
		if (options.prune) {
R
Ryan Scott 已提交
1554
			args.push('--prune');
R
Ryan Scott 已提交
1555 1556
		}

1557
		if (typeof options.depth === 'number') {
1558 1559
			args.push(`--depth=${options.depth}`);
		}
R
Ryan Scott 已提交
1560

J
Joao Moreno 已提交
1561 1562 1563 1564
		if (options.silent) {
			spawnOptions.env = { 'VSCODE_GIT_FETCH_SILENT': 'true' };
		}

J
Joao Moreno 已提交
1565
		try {
J
Joao Moreno 已提交
1566
			await this.run(args, spawnOptions);
J
Joao Moreno 已提交
1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
		} 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;
		}
	}

1578
	async pull(rebase?: boolean, remote?: string, branch?: string, options: PullOptions = {}): Promise<void> {
H
Hao Hu 已提交
1579 1580
		const args = ['pull'];

J
Joao Moreno 已提交
1581
		if (options.tags) {
H
Hao Hu 已提交
1582 1583
			args.push('--tags');
		}
1584 1585 1586 1587

		if (options.unshallow) {
			args.push('--unshallow');
		}
J
Joao Moreno 已提交
1588 1589 1590 1591 1592

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

M
Matt Shirley 已提交
1593
		if (remote && branch) {
1594
			args.push(remote);
M
Matt Shirley 已提交
1595
			args.push(branch);
1596 1597
		}

J
Joao Moreno 已提交
1598
		try {
1599
			await this.run(args, options);
J
Joao Moreno 已提交
1600 1601 1602 1603 1604 1605 1606
		} 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 已提交
1607 1608
			} 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 已提交
1609
				err.gitErrorCode = GitErrorCodes.DirtyWorkTree;
J
Joao Moreno 已提交
1610 1611 1612 1613
			} 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 已提交
1614 1615 1616 1617 1618 1619
			}

			throw err;
		}
	}

T
tomerstav 已提交
1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637
	async rebase(branch: string, options: PullOptions = {}): Promise<void> {
		const args = ['rebase'];

		args.push(branch);

		try {
			await this.run(args, options);
		} catch (err) {
			if (/^CONFLICT \([^)]+\): \b/m.test(err.stdout || '')) {
				err.gitErrorCode = GitErrorCodes.Conflict;
			} else if (/cannot rebase onto multiple branches/i.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.CantRebaseMultipleBranches;
			}

			throw err;
		}
	}

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

J
Joao Moreno 已提交
1641 1642 1643 1644
		if (forcePushMode === ForcePushMode.ForceWithLease) {
			args.push('--force-with-lease');
		} else if (forcePushMode === ForcePushMode.Force) {
			args.push('--force');
1645 1646
		}

J
Joao Moreno 已提交
1647
		if (setUpstream) {
J
Joao Moreno 已提交
1648 1649 1650
			args.push('-u');
		}

1651
		if (tags) {
1652
			args.push('--follow-tags');
J
Joao Moreno 已提交
1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
		}

		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;
1670 1671
			} else if (/^fatal: The current branch .* has no upstream branch/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoUpstreamBranch;
J
João Moreno 已提交
1672 1673
			} else if (/Permission.*denied/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.PermissionDenied;
J
Joao Moreno 已提交
1674 1675 1676 1677 1678 1679
			}

			throw err;
		}
	}

R
rebornix 已提交
1680 1681
	async blame(path: string): Promise<string> {
		try {
J
Joao Moreno 已提交
1682 1683
			const args = ['blame', sanitizePath(path)];
			const result = await this.run(args);
R
rebornix 已提交
1684 1685
			return result.stdout.trim();
		} catch (err) {
R
rebornix 已提交
1686 1687 1688 1689
			if (/^fatal: no such path/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoPathFound;
			}

R
rebornix 已提交
1690 1691 1692 1693
			throw err;
		}
	}

1694
	async createStash(message?: string, includeUntracked?: boolean): Promise<void> {
1695
		try {
J
Joao Moreno 已提交
1696
			const args = ['stash', 'push'];
1697

1698 1699 1700 1701
			if (includeUntracked) {
				args.push('-u');
			}

J
Joao Moreno 已提交
1702
			if (message) {
J
Joao Moreno 已提交
1703
				args.push('-m', message);
1704 1705 1706 1707 1708 1709 1710
			}

			await this.run(args);
		} catch (err) {
			if (/No local changes to save/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoLocalChanges;
			}
J
Joao Moreno 已提交
1711 1712 1713 1714 1715 1716

			throw err;
		}
	}

	async popStash(index?: number): Promise<void> {
1717
		const args = ['stash', 'pop'];
J
Joao Moreno 已提交
1718
		await this.popOrApplyStash(args, index);
1719 1720 1721 1722
	}

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

1726 1727
	private async popOrApplyStash(args: string[], index?: number): Promise<void> {
		try {
1728
			if (typeof index === 'number') {
J
Joao Moreno 已提交
1729
				args.push(`stash@{${index}}`);
1730
			}
J
Joao Moreno 已提交
1731 1732 1733 1734 1735 1736

			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 || '')) {
1737
				err.gitErrorCode = GitErrorCodes.LocalChangesOverwritten;
J
Joao Moreno 已提交
1738 1739
			} else if (/^CONFLICT/m.test(err.stdout || '')) {
				err.gitErrorCode = GitErrorCodes.StashConflict;
1740
			}
J
Joao Moreno 已提交
1741

1742 1743 1744 1745
			throw err;
		}
	}

J
Joao Moreno 已提交
1746
	async dropStash(index?: number): Promise<void> {
1747 1748
		const args = ['stash', 'drop'];

D
Drew Cross 已提交
1749 1750
		if (typeof index === 'number') {
			args.push(`stash@{${index}}`);
J
Joao Moreno 已提交
1751
		}
1752

J
Joao Moreno 已提交
1753 1754
		try {
			await this.run(args);
1755 1756 1757 1758 1759 1760 1761 1762 1763
		} catch (err) {
			if (/No stash found/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoStashFound;
			}

			throw err;
		}
	}

1764 1765
	getStatus(limit = 5000): Promise<{ status: IFileStatus[]; didHitLimit: boolean; }> {
		return new Promise<{ status: IFileStatus[]; didHitLimit: boolean; }>((c, e) => {
1766
			const parser = new GitStatusParser();
J
Joao Moreno 已提交
1767
			const env = { GIT_OPTIONAL_LOCKS: '0' };
F
Fmstrat 已提交
1768 1769 1770 1771 1772 1773 1774

			const config = workspace.getConfiguration('git');
			const args = ['status', '-z', '-u'];
			if (config.get<boolean>('ignoreSubmodules')) {
				args.push('--ignore-submodules');
			}
			const child = this.stream(args, { env });
1775

M
Matt Bierner 已提交
1776
			const onExit = (exitCode: number) => {
1777
				if (exitCode !== 0) {
1778 1779 1780 1781 1782 1783 1784 1785
					const stderr = stderrData.join('');
					return e(new GitError({
						message: 'Failed to execute git',
						stderr,
						exitCode,
						gitErrorCode: getGitErrorCode(stderr),
						gitCommand: 'status'
					}));
1786
				}
J
Joao Moreno 已提交
1787

1788 1789 1790
				c({ status: parser.status, didHitLimit: false });
			};

1791
			const onStdoutData = (raw: string) => {
1792 1793
				parser.update(raw);

J
Joao Moreno 已提交
1794
				if (parser.status.length > limit) {
1795
					child.removeListener('exit', onExit);
1796
					child.stdout!.removeListener('data', onStdoutData);
1797 1798
					child.kill();

J
Joao Moreno 已提交
1799
					c({ status: parser.status.slice(0, limit), didHitLimit: true });
1800 1801 1802
				}
			};

1803 1804
			child.stdout!.setEncoding('utf8');
			child.stdout!.on('data', onStdoutData);
1805 1806

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

J
Joao Moreno 已提交
1810
			child.on('error', cpErrorHandler(e));
1811
			child.on('exit', onExit);
1812
		});
J
Joao Moreno 已提交
1813 1814
	}

J
Joao Moreno 已提交
1815
	async getHEAD(): Promise<Ref> {
J
Joao Moreno 已提交
1816
		try {
J
Joao Moreno 已提交
1817
			const result = await this.run(['symbolic-ref', '--short', 'HEAD']);
J
Joao Moreno 已提交
1818 1819 1820 1821 1822

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

R
Rob Lourens 已提交
1823
			return { name: result.stdout.trim(), commit: undefined, type: RefType.Head };
J
Joao Moreno 已提交
1824
		} catch (err) {
J
Joao Moreno 已提交
1825
			const result = await this.run(['rev-parse', 'HEAD']);
J
Joao Moreno 已提交
1826 1827 1828 1829 1830

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

R
Rob Lourens 已提交
1831
			return { name: undefined, commit: result.stdout.trim(), type: RefType.Head };
J
Joao Moreno 已提交
1832 1833 1834
		}
	}

J
Joao Moreno 已提交
1835 1836
	async findTrackingBranches(upstreamBranch: string): Promise<Branch[]> {
		const result = await this.run(['for-each-ref', '--format', '%(refname:short)%00%(upstream:short)', 'refs/heads']);
1837
		return result.stdout.trim().split('\n')
J
Joao Moreno 已提交
1838 1839 1840
			.map(line => line.trim().split('\0'))
			.filter(([_, upstream]) => upstream === upstreamBranch)
			.map(([ref]) => ({ name: ref, type: RefType.Head } as Branch));
1841 1842
	}

1843 1844 1845 1846 1847 1848
	async getRefs(opts?: { sort?: 'alphabetically' | 'committerdate', contains?: string, pattern?: string, count?: number }): Promise<Ref[]> {
		const args = ['for-each-ref'];

		if (opts?.count) {
			args.push(`--count=${opts.count}`);
		}
S
skprabhanjan 已提交
1849

J
Joao Moreno 已提交
1850
		if (opts && opts.sort && opts.sort !== 'alphabetically') {
1851
			args.push('--sort', `-${opts.sort}`);
S
skprabhanjan 已提交
1852 1853
		}

1854 1855 1856 1857 1858 1859
		args.push('--format', '%(refname) %(objectname)');

		if (opts?.pattern) {
			args.push(opts.pattern);
		}

1860 1861 1862 1863
		if (opts?.contains) {
			args.push('--contains', opts.contains);
		}

S
skprabhanjan 已提交
1864
		const result = await this.run(args);
J
Joao Moreno 已提交
1865

M
Matt Bierner 已提交
1866
		const fn = (line: string): Ref | null => {
J
Joao Moreno 已提交
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882
			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 已提交
1883
			.filter(ref => !!ref) as Ref[];
J
Joao Moreno 已提交
1884 1885
	}

1886 1887
	async getStashes(): Promise<Stash[]> {
		const result = await this.run(['stash', 'list']);
J
Joao Moreno 已提交
1888
		const regex = /^stash@{(\d+)}:(.+)$/;
1889 1890
		const rawStashes = result.stdout.trim().split('\n')
			.filter(b => !!b)
M
Matt Bierner 已提交
1891
			.map(line => regex.exec(line) as RegExpExecArray)
1892
			.filter(g => !!g)
J
Joao Moreno 已提交
1893
			.map(([, index, description]: RegExpExecArray) => ({ index: parseInt(index), description }));
1894

J
Joao Moreno 已提交
1895 1896
		return rawStashes;
	}
1897

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

1903 1904
		for (const line of lines) {
			const parts = line.split(/\s/);
J
Joao Moreno 已提交
1905 1906 1907 1908
			const [name, url, type] = parts;

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

1909
			if (!remote) {
J
Joao Moreno 已提交
1910
				remote = { name, isReadOnly: false };
1911 1912 1913
				remotes.push(remote);
			}

J
Joao Moreno 已提交
1914 1915 1916 1917 1918 1919 1920
			if (/fetch/i.test(type)) {
				remote.fetchUrl = url;
			} else if (/push/i.test(type)) {
				remote.pushUrl = url;
			} else {
				remote.fetchUrl = url;
				remote.pushUrl = url;
1921 1922
			}

C
ChaseKnowlden 已提交
1923
			// https://github.com/microsoft/vscode/issues/45271
J
Joao Moreno 已提交
1924
			remote.isReadOnly = remote.pushUrl === undefined || remote.pushUrl === 'no_push';
1925
		}
J
Joao Moreno 已提交
1926

1927
		return remotes;
J
Joao Moreno 已提交
1928 1929
	}

J
Joao Moreno 已提交
1930
	async getBranch(name: string): Promise<Branch> {
J
Joao Moreno 已提交
1931 1932 1933 1934
		if (name === 'HEAD') {
			return this.getHEAD();
		}

1935 1936 1937 1938 1939 1940 1941 1942
		let result = await this.run(['rev-parse', name]);

		if (!result.stdout && /^@/.test(name)) {
			const symbolicFullNameResult = await this.run(['rev-parse', '--symbolic-full-name', name]);
			name = symbolicFullNameResult.stdout.trim();

			result = await this.run(['rev-parse', name]);
		}
J
Joao Moreno 已提交
1943 1944

		if (!result.stdout) {
J
Joao Moreno 已提交
1945
			return Promise.reject<Branch>(new Error('No such branch'));
J
Joao Moreno 已提交
1946 1947 1948 1949 1950
		}

		const commit = result.stdout.trim();

		try {
J
Joao Moreno 已提交
1951 1952 1953 1954 1955 1956 1957
			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 已提交
1958

J
Joao Moreno 已提交
1959 1960
			const upstream = { remote: match[1], name: match[2] };
			const res3 = await this.run(['rev-list', '--left-right', name + '...' + fullUpstream]);
J
Joao Moreno 已提交
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980

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

1981
	async getBranches(query: BranchQuery): Promise<Ref[]> {
1982
		const refs = await this.getRefs({ contains: query.contains, pattern: query.pattern ? `refs/${query.pattern}` : undefined, count: query.count });
1983 1984 1985
		return refs.filter(value => (value.type !== RefType.Tag) && (query.remote || !value.remote));
	}

1986 1987 1988
	// TODO: Support core.commentChar
	stripCommitMessageComments(message: string): string {
		return message.replace(/^\s*#.*$\n?/gm, '').trim();
1989 1990
	}

1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
	async getSquashMessage(): Promise<string | undefined> {
		const squashMsgPath = path.join(this.repositoryRoot, '.git', 'SQUASH_MSG');

		try {
			const raw = await fs.readFile(squashMsgPath, 'utf8');
			return this.stripCommitMessageComments(raw);
		} catch {
			return undefined;
		}
	}

2002 2003
	async getMergeMessage(): Promise<string | undefined> {
		const mergeMsgPath = path.join(this.repositoryRoot, '.git', 'MERGE_MSG');
2004

2005
		try {
J
Joao Moreno 已提交
2006
			const raw = await fs.readFile(mergeMsgPath, 'utf8');
2007
			return this.stripCommitMessageComments(raw);
J
Joao Moreno 已提交
2008
		} catch {
2009 2010 2011 2012
			return undefined;
		}
	}

J
Joao Moreno 已提交
2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
	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 已提交
2027
				templatePath = path.join(this.repositoryRoot, templatePath);
J
Joao Moreno 已提交
2028 2029
			}

J
Joao Moreno 已提交
2030
			const raw = await fs.readFile(templatePath, 'utf8');
2031
			return this.stripCommitMessageComments(raw);
J
Joao Moreno 已提交
2032 2033 2034 2035 2036
		} catch (err) {
			return '';
		}
	}

J
Joao Moreno 已提交
2037
	async getCommit(ref: string): Promise<Commit> {
2038 2039 2040 2041 2042 2043
		const result = await this.run(['show', '-s', `--format=${COMMIT_FORMAT}`, '-z', ref]);
		const commits = parseGitCommits(result.stdout);
		if (commits.length === 0) {
			return Promise.reject<Commit>('bad commit format');
		}
		return commits[0];
J
Joao Moreno 已提交
2044
	}
2045 2046

	async updateSubmodules(paths: string[]): Promise<void> {
J
João Moreno 已提交
2047
		const args = ['submodule', 'update'];
J
Joao Moreno 已提交
2048

J
Joao Moreno 已提交
2049
		for (const chunk of splitInChunks(paths.map(sanitizePath), MAX_CLI_LENGTH)) {
J
João Moreno 已提交
2050
			await this.run([...args, '--', ...chunk]);
J
Joao Moreno 已提交
2051
		}
2052 2053 2054 2055 2056 2057
	}

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

		try {
J
Joao Moreno 已提交
2058
			const gitmodulesRaw = await fs.readFile(gitmodulesPath, 'utf8');
2059 2060 2061 2062 2063 2064 2065 2066 2067
			return parseGitmodules(gitmodulesRaw);
		} catch (err) {
			if (/ENOENT/.test(err.message)) {
				return [];
			}

			throw err;
		}
	}
2068
}