git.ts 51.8 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 iconv = require('iconv-lite');
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 } from 'vscode';
J
Joao Moreno 已提交
16
import { URI } from 'vscode-uri';
J
Joao Moreno 已提交
17
import { detectEncoding } from './encoding';
18
import { Ref, RefType, Branch, Remote, GitErrorCodes, LogOptions, Change, Status, CommitOptions } from './api/git';
J
Joao Moreno 已提交
19 20
import * as byline from 'byline';
import { StringDecoder } from 'string_decoder';
J
Joao Moreno 已提交
21

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

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

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

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

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

49
// TODO@eamodio: Move to git.d.ts once we are good with the api
E
Eric Amodio 已提交
50 51 52 53
/**
 * Log file options.
 */
export interface LogFileOptions {
54 55 56 57 58 59 60
	/** 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 已提交
61 62
}

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

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

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

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

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

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

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

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

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

129 130 131 132 133
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 已提交
134 135
function findGitWin32(onLookup: (path: string) => void): Promise<IGit> {
	return findSystemGitWin32(process.env['ProgramW6432'] as string, onLookup)
R
Rob Lourens 已提交
136 137 138 139
		.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 已提交
140 141
}

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

J
Joao Moreno 已提交
145
	return first
R
Rob Lourens 已提交
146
		.then(undefined, () => {
J
Joao Moreno 已提交
147
			switch (process.platform) {
J
Joao Moreno 已提交
148 149 150
				case 'darwin': return findGitDarwin(onLookup);
				case 'win32': return findGitWin32(onLookup);
				default: return findSpecificGit('git', onLookup);
J
Joao Moreno 已提交
151 152 153
			}
		})
		.then(null, () => Promise.reject(new Error('Git installation not found.')));
J
Joao Moreno 已提交
154 155
}

J
Joao Moreno 已提交
156
export interface IExecutionResult<T extends string | Buffer> {
J
Joao Moreno 已提交
157
	exitCode: number;
J
Joao Moreno 已提交
158
	stdout: T;
J
Joao Moreno 已提交
159 160 161
	stderr: string;
}

J
Joao Moreno 已提交
162 163 164 165 166 167 168 169 170 171 172 173 174 175
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 已提交
176
export interface SpawnOptions extends cp.SpawnOptions {
J
Joao Moreno 已提交
177 178 179
	input?: string;
	encoding?: string;
	log?: boolean;
J
Joao Moreno 已提交
180
	cancellationToken?: CancellationToken;
J
Joao Moreno 已提交
181
	onSpawn?: (childProcess: cp.ChildProcess) => void;
J
Joao Moreno 已提交
182 183
}

J
Joao Moreno 已提交
184
async function exec(child: cp.ChildProcess, cancellationToken?: CancellationToken): Promise<IExecutionResult<Buffer>> {
J
Joao Moreno 已提交
185
	if (!child.stdout || !child.stderr) {
J
Joao Moreno 已提交
186 187 188 189 190
		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 已提交
191 192
	}

J
Joao Moreno 已提交
193 194
	const disposables: IDisposable[] = [];

M
Matt Bierner 已提交
195
	const once = (ee: NodeJS.EventEmitter, name: string, fn: (...args: any[]) => void) => {
J
Joao Moreno 已提交
196 197 198 199
		ee.once(name, fn);
		disposables.push(toDisposable(() => ee.removeListener(name, fn)));
	};

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

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

J
Joao Moreno 已提交
231 232 233 234 235 236
				e(new GitError({ message: 'Cancelled' }));
			});
		});

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

J
Joao Moreno 已提交
238 239 240 241 242 243
	try {
		const [exitCode, stdout, stderr] = await result;
		return { exitCode, stdout, stderr };
	} finally {
		dispose(disposables);
	}
J
Joao Moreno 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257
}

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

export class GitError {

J
Joao Moreno 已提交
258
	error?: Error;
J
Joao Moreno 已提交
259
	message: string;
J
Joao Moreno 已提交
260 261 262 263 264
	stdout?: string;
	stderr?: string;
	exitCode?: number;
	gitErrorCode?: string;
	gitCommand?: string;
J
Joao Moreno 已提交
265 266 267 268 269 270

	constructor(data: IGitErrorData) {
		if (data.error) {
			this.error = data.error;
			this.message = data.error.message;
		} else {
R
Rob Lourens 已提交
271
			this.error = undefined;
M
Matt Bierner 已提交
272
			this.message = '';
J
Joao Moreno 已提交
273 274 275
		}

		this.message = this.message || data.message || 'Git error';
J
Joao Moreno 已提交
276 277 278 279 280
		this.stdout = data.stdout;
		this.stderr = data.stderr;
		this.exitCode = data.exitCode;
		this.gitErrorCode = data.gitErrorCode;
		this.gitCommand = data.gitCommand;
J
Joao Moreno 已提交
281 282 283 284 285 286 287 288 289
	}

	toString(): string {
		let result = this.message + ' ' + JSON.stringify({
			exitCode: this.exitCode,
			gitErrorCode: this.gitErrorCode,
			gitCommand: this.gitCommand,
			stdout: this.stdout,
			stderr: this.stderr
290
		}, null, 2);
J
Joao Moreno 已提交
291 292 293 294 295 296 297 298 299 300 301 302

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

		return result;
	}
}

export interface IGitOptions {
	gitPath: string;
	version: string;
303
	env?: any;
J
Joao Moreno 已提交
304 305
}

306 307 308 309 310
function getGitErrorCode(stderr: string): string | undefined {
	if (/Another git process seems to be running in this repository|If no other git process is currently running/.test(stderr)) {
		return GitErrorCodes.RepositoryIsLocked;
	} else if (/Authentication failed/.test(stderr)) {
		return GitErrorCodes.AuthenticationFailed;
J
Joao Moreno 已提交
311
	} else if (/Not a git repository/i.test(stderr)) {
312 313 314 315 316 317 318 319 320
		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;
321 322
	} else if (/branch '.+' is not fully merged/.test(stderr)) {
		return GitErrorCodes.BranchNotFullyMerged;
323 324
	} else if (/Couldn\'t find remote ref/.test(stderr)) {
		return GitErrorCodes.NoRemoteReference;
325 326 327 328
	} 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;
329 330
	} else if (/Please,? commit your changes or stash them/.test(stderr)) {
		return GitErrorCodes.DirtyWorkTree;
331 332
	}

R
Rob Lourens 已提交
333
	return undefined;
334 335
}

J
Joao Moreno 已提交
336 337 338 339 340 341
// 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()}:\\`);
}

342
const COMMIT_FORMAT = '%H%n%aN%n%aE%n%at%n%ct%n%P%n%B';
343

J
Joao Moreno 已提交
344 345
export class Git {

J
Joao Moreno 已提交
346
	readonly path: string;
347
	private env: any;
J
Joao Moreno 已提交
348

349 350
	private _onOutput = new EventEmitter();
	get onOutput(): EventEmitter { return this._onOutput; }
J
Joao Moreno 已提交
351

J
Joao Moreno 已提交
352
	constructor(options: IGitOptions) {
J
Joao Moreno 已提交
353
		this.path = options.gitPath;
354
		this.env = options.env || {};
J
Joao Moreno 已提交
355 356
	}

J
Joao Moreno 已提交
357 358
	open(repository: string, dotGit: string): Repository {
		return new Repository(this, repository, dotGit);
J
Joao Moreno 已提交
359 360
	}

J
Joao Moreno 已提交
361 362 363 364 365
	async init(repository: string): Promise<void> {
		await this.exec(repository, ['init']);
		return;
	}

J
Joao Moreno 已提交
366
	async clone(url: string, parentPath: string, progress: Progress<{ increment: number }>, cancellationToken?: CancellationToken): Promise<string> {
367
		let baseFolderName = decodeURI(url).replace(/[\/]+$/, '').replace(/^.*[\/\\]/, '').replace(/\.git$/, '') || 'repository';
368 369 370 371
		let folderName = baseFolderName;
		let folderPath = path.join(parentPath, folderName);
		let count = 1;

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

J
Joao Moreno 已提交
377
		await mkdirp(parentPath);
J
Joao Moreno 已提交
378

J
Joao Moreno 已提交
379 380 381
		const onSpawn = (child: cp.ChildProcess) => {
			const decoder = new StringDecoder('utf8');
			const lineStream = new byline.LineStream({ encoding: 'utf8' });
382
			child.stderr!.on('data', (buffer: Buffer) => lineStream.write(decoder.write(buffer)));
J
Joao Moreno 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406

			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) {
					progress.report({ increment: totalProgress - previousProgress });
					previousProgress = totalProgress;
				}
			});
		};

J
Joao Moreno 已提交
407
		try {
J
Joao Moreno 已提交
408
			await this.exec(parentPath, ['clone', url.includes(' ') ? encodeURI(url) : url, folderPath, '--progress'], { cancellationToken, onSpawn });
J
Joao Moreno 已提交
409 410 411 412 413 414 415 416 417
		} 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 已提交
418 419 420
		return folderPath;
	}

J
Joao Moreno 已提交
421 422
	async getRepositoryRoot(repositoryPath: string): Promise<string> {
		const result = await this.exec(repositoryPath, ['rev-parse', '--show-toplevel']);
423

J
jeanp413 已提交
424
		// Keep trailing spaces which are part of the directory name
425 426 427 428 429 430 431 432 433 434 435 436 437
		const repoPath = path.normalize(result.stdout.trimLeft().replace(/(\r\n|\r|\n)+$/, ''));

		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 {
E
Eric Amodio 已提交
438
						const networkPath = await new Promise<string>(resolve =>
439 440 441 442 443 444
							realpath.native(`${letter}:`, { encoding: 'utf8' }, (err, resolvedPath) =>
								// eslint-disable-next-line eqeqeq
								resolve(err != null ? undefined : resolvedPath),
							),
						);
						if (networkPath !== undefined) {
445
							return path.normalize(
446 447 448 449
								repoUri.fsPath.replace(
									networkPath,
									`${letter.toLowerCase()}:${networkPath.endsWith('\\') ? '\\' : ''}`
								),
450 451 452 453 454 455 456 457 458 459
							);
						}
					} catch { }
				}

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

		return repoPath;
J
Joao Moreno 已提交
460 461
	}

J
Joao Moreno 已提交
462
	async getRepositoryDotGit(repositoryPath: string): Promise<string> {
463 464 465 466 467 468 469 470
		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 已提交
471 472
	}

J
Joao Moreno 已提交
473
	async exec(cwd: string, args: string[], options: SpawnOptions = {}): Promise<IExecutionResult<string>> {
J
Joao Moreno 已提交
474
		options = assign({ cwd }, options || {});
J
Joao Moreno 已提交
475
		return await this._exec(args, options);
J
Joao Moreno 已提交
476 477
	}

J
Joao Moreno 已提交
478 479 480 481
	async exec2(args: string[], options: SpawnOptions = {}): Promise<IExecutionResult<string>> {
		return await this._exec(args, options);
	}

J
Joao Moreno 已提交
482
	stream(cwd: string, args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
483
		options = assign({ cwd }, options || {});
J
Joao Moreno 已提交
484
		return this.spawn(args, options);
J
Joao Moreno 已提交
485 486
	}

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

J
Joao Moreno 已提交
490 491 492 493
		if (options.onSpawn) {
			options.onSpawn(child);
		}

J
Joao Moreno 已提交
494
		if (options.input) {
495
			child.stdin!.end(options.input, 'utf8');
J
Joao Moreno 已提交
496 497
		}

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

J
Joao Moreno 已提交
500 501
		if (options.log !== false && bufferResult.stderr.length > 0) {
			this.log(`${bufferResult.stderr}\n`);
J
Joao Moreno 已提交
502 503
		}

J
Joao Moreno 已提交
504 505 506 507 508 509 510 511 512 513 514
		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 已提交
515 516 517 518
				message: 'Failed to execute git',
				stdout: result.stdout,
				stderr: result.stderr,
				exitCode: result.exitCode,
519
				gitErrorCode: getGitErrorCode(result.stderr),
J
Joao Moreno 已提交
520 521 522 523 524
				gitCommand: args[0]
			}));
		}

		return result;
J
Joao Moreno 已提交
525 526
	}

J
Joao Moreno 已提交
527
	spawn(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
528
		if (!this.path) {
J
Joao Moreno 已提交
529 530 531 532 533 534 535 536 537 538 539
			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
		}

540
		options.env = assign({}, process.env, this.env, options.env || {}, {
J
Joao Moreno 已提交
541
			VSCODE_GIT_COMMAND: args[0],
542
			LC_ALL: 'en_US.UTF-8',
543
			LANG: 'en_US.UTF-8',
544
			GIT_PAGER: 'cat'
J
Joao Moreno 已提交
545
		});
J
Joao Moreno 已提交
546

J
Joao Moreno 已提交
547 548 549 550
		if (options.cwd) {
			options.cwd = sanitizePath(options.cwd);
		}

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

J
Joao Moreno 已提交
555
		return cp.spawn(this.path, args, options);
J
Joao Moreno 已提交
556 557 558
	}

	private log(output: string): void {
559
		this._onOutput.emit('log', output);
J
Joao Moreno 已提交
560
	}
J
Joao Moreno 已提交
561 562
}

J
Joao Moreno 已提交
563
export interface Commit {
J
Joao Moreno 已提交
564 565
	hash: string;
	message: string;
J
Joao Moreno 已提交
566
	parents: string[];
567 568 569
	authorDate?: Date;
	authorName?: string;
	authorEmail?: string;
570
	commitDate?: Date;
J
Joao Moreno 已提交
571 572
}

573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
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 已提交
611
		if (entry.x === 'R' || entry.x === 'C') {
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
			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;
	}
}

639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672
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
Joao Moreno 已提交
673
		const propertyMatch = /^\s*(\w+)\s+=\s+(.*)$/.exec(line);
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700

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

701
const commitRegex = /([0-9a-f]{40})\n(.*)\n(.*)\n(.*)\n(.*)\n(.*)(?:\n([^]*?))?(?:\x00)/gm;
702 703 704 705 706

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

	let ref;
707 708 709 710
	let authorName;
	let authorEmail;
	let authorDate;
	let commitDate;
711 712 713 714 715 716 717 718 719 720
	let parents;
	let message;
	let match;

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

721
		[, ref, authorName, authorEmail, authorDate, commitDate, parents, message] = match;
722

723 724 725 726 727 728 729 730 731
		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(' ') : [],
732 733 734 735
			authorDate: new Date(Number(authorDate) * 1000),
			authorName: ` ${authorName}`.substr(1),
			authorEmail: ` ${authorEmail}`.substr(1),
			commitDate: new Date(Number(commitDate) * 1000),
736 737 738 739
		});
	} while (true);

	return commits;
740 741
}

742 743 744 745
interface LsTreeElement {
	mode: string;
	type: string;
	object: string;
J
Joao Moreno 已提交
746
	size: string;
747 748 749 750 751 752
	file: string;
}

export function parseLsTree(raw: string): LsTreeElement[] {
	return raw.split('\n')
		.filter(l => !!l)
J
Joao Moreno 已提交
753
		.map(line => /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(.*)$/.exec(line)!)
754
		.filter(m => !!m)
J
Joao Moreno 已提交
755
		.map(([, mode, type, object, size, file]) => ({ mode, type, object, size, file }));
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
}

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

773 774
export interface PullOptions {
	unshallow?: boolean;
J
Joao Moreno 已提交
775
	tags?: boolean;
776
	readonly cancellationToken?: CancellationToken;
777 778
}

J
Joao Moreno 已提交
779 780
export enum ForcePushMode {
	Force,
J
Joao Moreno 已提交
781
	ForceWithLease
J
Joao Moreno 已提交
782 783
}

J
Joao Moreno 已提交
784 785 786 787
export class Repository {

	constructor(
		private _git: Git,
J
Joao Moreno 已提交
788 789
		private repositoryRoot: string,
		readonly dotGit: string
J
Joao Moreno 已提交
790 791 792 793 794 795
	) { }

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

J
Joao Moreno 已提交
796 797
	get root(): string {
		return this.repositoryRoot;
J
Joao Moreno 已提交
798 799 800
	}

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

J
Joao Moreno 已提交
805
	stream(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
806
		return this.git.stream(this.repositoryRoot, args, options);
J
Joao Moreno 已提交
807 808
	}

J
Joao Moreno 已提交
809
	spawn(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
810 811 812
		return this.git.spawn(args, options);
	}

J
Joao Moreno 已提交
813
	async config(scope: string, key: string, value: any = null, options: SpawnOptions = {}): Promise<string> {
J
Joao Moreno 已提交
814 815 816 817 818 819 820 821 822 823 824 825 826
		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 已提交
827
		return result.stdout.trim();
J
Joao Moreno 已提交
828 829
	}

J
Joao Moreno 已提交
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
	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) };
		});
	}

848
	async log(options?: LogOptions): Promise<Commit[]> {
E
Eric Amodio 已提交
849 850
		const maxEntries = options?.maxEntries ?? 32;
		const args = ['log', `-n${maxEntries}`, `--format=${COMMIT_FORMAT}`, '-z', '--'];
851

852 853
		const result = await this.run(args);
		if (result.exitCode) {
854
			// An empty repo
855 856 857
			return [];
		}

858 859
		return parseGitCommits(result.stdout);
	}
860

861
	async logFile(uri: Uri, options?: LogFileOptions): Promise<Commit[]> {
862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881
		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);
882

883 884 885 886
		const result = await this.run(args);
		if (result.exitCode) {
			// No file history, e.g. a new file or untracked
			return [];
887 888
		}

889
		return parseGitCommits(result.stdout);
890 891
	}

892
	async bufferString(object: string, encoding: string = 'utf8', autoGuessEncoding = false): Promise<string> {
J
Joao Moreno 已提交
893
		const stdout = await this.buffer(object);
894 895 896 897 898

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

J
Joao Moreno 已提交
899 900 901
		encoding = iconv.encodingExists(encoding) ? encoding : 'utf8';

		return iconv.decode(stdout, encoding);
J
Joao Moreno 已提交
902 903 904
	}

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

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

911
		const { exitCode, stdout, stderr } = await exec(child);
J
Joao Moreno 已提交
912 913

		if (exitCode) {
914
			const err = new GitError({
J
Joao Moreno 已提交
915 916
				message: 'Could not show object.',
				exitCode
917 918 919 920 921 922 923
			});

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

			return Promise.reject<Buffer>(err);
J
Joao Moreno 已提交
924 925 926
		}

		return stdout;
J
Joao Moreno 已提交
927 928
	}

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

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

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

J
Joao Moreno 已提交
941
			return { mode, object, size };
J
Joao Moreno 已提交
942 943
		}

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

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

J
Joao Moreno 已提交
950
		const { mode, object, size } = elements[0];
J
Joao Moreno 已提交
951
		return { mode, object, size: parseInt(size) };
J
Joao Moreno 已提交
952 953
	}

J
Joao Moreno 已提交
954
	async lstree(treeish: string, path: string): Promise<LsTreeElement[]> {
J
Joao Moreno 已提交
955
		const { stdout } = await this.run(['ls-tree', '-l', treeish, '--', sanitizePath(path)]);
956 957
		return parseLsTree(stdout);
	}
958

959
	async lsfiles(path: string): Promise<LsFilesElement[]> {
J
Joao Moreno 已提交
960
		const { stdout } = await this.run(['ls-files', '--stage', '--', sanitizePath(path)]);
961
		return parseLsFiles(stdout);
962 963
	}

J
Joao Moreno 已提交
964
	async getGitRelativePath(ref: string, relativePath: string): Promise<string> {
965 966
		const relativePathLowercase = relativePath.toLowerCase();
		const dirname = path.posix.dirname(relativePath) + '/';
J
Joao Moreno 已提交
967
		const elements: { file: string; }[] = ref ? await this.lstree(ref, dirname) : await this.lsfiles(dirname);
968 969 970 971
		const element = elements.filter(file => file.file.toLowerCase() === relativePathLowercase)[0];

		if (!element) {
			throw new GitError({ message: 'Git relative path not found.' });
972
		}
973 974

		return element.file;
975 976
	}

J
Joao Moreno 已提交
977 978
	async detectObjectType(object: string): Promise<{ mimetype: string, encoding?: string }> {
		const child = await this.stream(['show', object]);
979
		const buffer = await readBytes(child.stdout!, 4100);
J
Joao Moreno 已提交
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 1009 1010 1011 1012 1013 1014 1015 1016

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

1017 1018 1019 1020 1021 1022 1023
	async apply(patch: string, reverse?: boolean): Promise<void> {
		const args = ['apply', patch];

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

1024 1025 1026 1027 1028 1029 1030 1031 1032
		try {
			await this.run(args);
		} catch (err) {
			if (/patch does not apply/.test(err.stderr)) {
				err.gitErrorCode = GitErrorCodes.PatchDoesNotApply;
			}

			throw err;
		}
1033 1034 1035
	}

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

J
Joao Moreno 已提交
1038
		if (cached) {
1039 1040 1041 1042 1043 1044 1045
			args.push('--cached');
		}

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

1046 1047 1048 1049
	diffWithHEAD(): Promise<Change[]>;
	diffWithHEAD(path: string): Promise<string>;
	diffWithHEAD(path?: string | undefined): Promise<string | Change[]>;
	async diffWithHEAD(path?: string | undefined): Promise<string | Change[]> {
1050 1051 1052 1053
		if (!path) {
			return await this.diffFiles(false);
		}

J
Joao Moreno 已提交
1054
		const args = ['diff', '--', sanitizePath(path)];
J
Joao Moreno 已提交
1055 1056 1057 1058
		const result = await this.run(args);
		return result.stdout;
	}

1059 1060 1061
	diffWith(ref: string): Promise<Change[]>;
	diffWith(ref: string, path: string): Promise<string>;
	diffWith(ref: string, path?: string | undefined): Promise<string | Change[]>;
1062 1063 1064 1065 1066
	async diffWith(ref: string, path?: string): Promise<string | Change[]> {
		if (!path) {
			return await this.diffFiles(false, ref);
		}

J
Joao Moreno 已提交
1067
		const args = ['diff', ref, '--', sanitizePath(path)];
J
Joao Moreno 已提交
1068 1069 1070 1071
		const result = await this.run(args);
		return result.stdout;
	}

1072 1073 1074
	diffIndexWithHEAD(): Promise<Change[]>;
	diffIndexWithHEAD(path: string): Promise<string>;
	diffIndexWithHEAD(path?: string | undefined): Promise<string | Change[]>;
1075 1076 1077 1078 1079
	async diffIndexWithHEAD(path?: string): Promise<string | Change[]> {
		if (!path) {
			return await this.diffFiles(true);
		}

J
Joao Moreno 已提交
1080
		const args = ['diff', '--cached', '--', sanitizePath(path)];
J
Joao Moreno 已提交
1081 1082 1083 1084
		const result = await this.run(args);
		return result.stdout;
	}

1085 1086 1087
	diffIndexWith(ref: string): Promise<Change[]>;
	diffIndexWith(ref: string, path: string): Promise<string>;
	diffIndexWith(ref: string, path?: string | undefined): Promise<string | Change[]>;
1088 1089 1090 1091 1092
	async diffIndexWith(ref: string, path?: string): Promise<string | Change[]> {
		if (!path) {
			return await this.diffFiles(true, ref);
		}

J
Joao Moreno 已提交
1093
		const args = ['diff', '--cached', ref, '--', sanitizePath(path)];
J
Joao Moreno 已提交
1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
		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;
	}

1104 1105 1106
	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[]>;
1107 1108 1109 1110 1111 1112
	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 已提交
1113
		const args = ['diff', range, '--', sanitizePath(path)];
J
Joao Moreno 已提交
1114 1115 1116 1117 1118
		const result = await this.run(args);

		return result.stdout.trim();
	}

1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145
	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;
			}

J
Joao Moreno 已提交
1146
			const originalUri = URI.file(path.isAbsolute(resourcePath) ? resourcePath : path.join(this.repositoryRoot, resourcePath));
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
			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;
					}

J
Joao Moreno 已提交
1174
					const uri = URI.file(path.isAbsolute(newPath) ? newPath : path.join(this.repositoryRoot, newPath));
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
					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 已提交
1200 1201 1202 1203 1204 1205 1206
	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 已提交
1207 1208 1209 1210 1211 1212 1213
	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 已提交
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
	async add(paths: string[], opts?: { update?: boolean }): Promise<void> {
		const args = ['add'];

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

		args.push('--');
J
Joao Moreno 已提交
1224 1225

		if (paths && paths.length) {
J
Joao Moreno 已提交
1226
			args.push.apply(args, paths.map(sanitizePath));
J
Joao Moreno 已提交
1227 1228 1229 1230 1231 1232 1233
		} else {
			args.push('.');
		}

		await this.run(args);
	}

J
Joao Moreno 已提交
1234 1235 1236 1237 1238 1239 1240
	async rm(paths: string[]): Promise<void> {
		const args = ['rm', '--'];

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

J
Joao Moreno 已提交
1241
		args.push(...paths.map(sanitizePath));
J
Joao Moreno 已提交
1242 1243 1244 1245

		await this.run(args);
	}

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

		const { exitCode, stdout } = await exec(child);
J
Joao Moreno 已提交
1251
		const hash = stdout.toString('utf8');
J
Joao Moreno 已提交
1252 1253 1254 1255 1256 1257 1258 1259

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

J
Joao Moreno 已提交
1260
		const treeish = await this.getCommit('HEAD').then(() => 'HEAD', () => '');
J
Joao Moreno 已提交
1261
		let mode: string;
D
Darrien Singleton 已提交
1262
		let add: string = '';
J
Joao Moreno 已提交
1263 1264

		try {
1265
			const details = await this.getObjectDetails(treeish, path);
J
Joao Moreno 已提交
1266 1267
			mode = details.mode;
		} catch (err) {
J
Joao Moreno 已提交
1268 1269 1270 1271
			if (err.gitErrorCode !== GitErrorCodes.UnknownPath) {
				throw err;
			}

J
Joao Moreno 已提交
1272
			mode = '100644';
D
Darrien Singleton 已提交
1273
			add = '--add';
J
Joao Moreno 已提交
1274 1275
		}

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

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

1282 1283 1284 1285
		if (opts.track) {
			args.push('--track');
		}

J
Joao Moreno 已提交
1286 1287 1288 1289 1290
		if (treeish) {
			args.push(treeish);
		}

		try {
J
Joao Moreno 已提交
1291
			if (paths && paths.length > 0) {
J
Joao Moreno 已提交
1292
				for (const chunk of splitInChunks(paths.map(sanitizePath), MAX_CLI_LENGTH)) {
J
Joao Moreno 已提交
1293 1294 1295 1296 1297
					await this.run([...args, '--', ...chunk]);
				}
			} else {
				await this.run(args);
			}
J
Joao Moreno 已提交
1298
		} catch (err) {
J
Joao Moreno 已提交
1299
			if (/Please,? commit your changes or stash them/.test(err.stderr || '')) {
J
Joao Moreno 已提交
1300 1301 1302 1303 1304 1305 1306
				err.gitErrorCode = GitErrorCodes.DirtyWorkTree;
			}

			throw err;
		}
	}

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

J
Joao Moreno 已提交
1310
		if (opts.all) {
J
Joao Moreno 已提交
1311 1312 1313
			args.push('--all');
		}

J
Joao Moreno 已提交
1314
		if (opts.amend) {
J
Joao Moreno 已提交
1315 1316 1317
			args.push('--amend');
		}

J
Joao Moreno 已提交
1318
		if (opts.signoff) {
J
Joao Moreno 已提交
1319 1320 1321
			args.push('--signoff');
		}

1322 1323 1324
		if (opts.signCommit) {
			args.push('-S');
		}
T
Tom Basche 已提交
1325 1326 1327
		if (opts.empty) {
			args.push('--allow-empty');
		}
1328

J
Joao Moreno 已提交
1329 1330 1331
		try {
			await this.run(args, { input: message || '' });
		} catch (commitErr) {
1332 1333 1334
			await this.handleCommitError(commitErr);
		}
	}
J
Joao Moreno 已提交
1335

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

1339 1340 1341 1342 1343 1344
		try {
			await this.run(args);
		} catch (commitErr) {
			await this.handleCommitError(commitErr);
		}
	}
J
Joao Moreno 已提交
1345

1346 1347 1348
	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 已提交
1349 1350
			throw commitErr;
		}
1351 1352

		try {
J
Joao Moreno 已提交
1353 1354 1355 1356 1357
			await this.run(['config', '--get-all', 'user.name']);
		} catch (err) {
			err.gitErrorCode = GitErrorCodes.NoUserNameConfigured;
			throw err;
		}
1358 1359

		try {
J
Joao Moreno 已提交
1360 1361 1362 1363
			await this.run(['config', '--get-all', 'user.email']);
		} catch (err) {
			err.gitErrorCode = GitErrorCodes.NoUserEmailConfigured;
			throw err;
1364 1365 1366
		}

		throw commitErr;
J
Joao Moreno 已提交
1367 1368
	}

J
Joao Moreno 已提交
1369
	async branch(name: string, checkout: boolean, ref?: string): Promise<void> {
J
Joao Moreno 已提交
1370
		const args = checkout ? ['checkout', '-q', '-b', name, '--no-track'] : ['branch', '-q', name];
J
Joao Moreno 已提交
1371 1372 1373 1374 1375

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

J
Joao Moreno 已提交
1376 1377 1378
		await this.run(args);
	}

1379 1380
	async deleteBranch(name: string, force?: boolean): Promise<void> {
		const args = ['branch', force ? '-D' : '-d', name];
M
Maik Riechert 已提交
1381 1382 1383
		await this.run(args);
	}

1384 1385 1386 1387 1388
	async renameBranch(name: string): Promise<void> {
		const args = ['branch', '-m', name];
		await this.run(args);
	}

J
Joao Moreno 已提交
1389 1390 1391 1392 1393
	async setBranchUpstream(name: string, upstream: string): Promise<void> {
		const args = ['branch', '--set-upstream-to', upstream, name];
		await this.run(args);
	}

1394 1395 1396 1397 1398
	async deleteRef(ref: string): Promise<void> {
		const args = ['update-ref', '-d', ref];
		await this.run(args);
	}

J
Joao Moreno 已提交
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
	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;
		}
1411 1412
	}

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

J
Joao Moreno 已提交
1416 1417
		if (message) {
			args = [...args, '-a', name, '-m', message];
1418
		} else {
J
Joao Moreno 已提交
1419
			args = [...args, name];
1420 1421 1422 1423 1424
		}

		await this.run(args);
	}

X
Xhulio Hasani 已提交
1425 1426 1427 1428 1429
	async deleteTag(name: string): Promise<void> {
		let args = ['tag', '-d', name];
		await this.run(args);
	}

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

J
Joao Moreno 已提交
1434 1435 1436 1437 1438 1439 1440
		const limiter = new Limiter(5);
		const promises: Promise<any>[] = [];

		for (const paths of groups) {
			for (const chunk of splitInChunks(paths, MAX_CLI_LENGTH)) {
				promises.push(limiter.queue(() => this.run(['clean', '-f', '-q', '--', ...chunk])));
			}
J
Joao Moreno 已提交
1441
		}
J
Joao Moreno 已提交
1442 1443

		await Promise.all(promises);
J
Joao Moreno 已提交
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
	}

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

J
Joao Moreno 已提交
1465
	async revert(treeish: string, paths: string[]): Promise<void> {
J
Joao Moreno 已提交
1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
		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) {
J
Joao Moreno 已提交
1477
			args.push.apply(args, paths.map(sanitizePath));
J
Joao Moreno 已提交
1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
		} else {
			args.push('.');
		}

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

			throw err;
		}
	}

J
Joao Moreno 已提交
1495 1496 1497 1498 1499
	async addRemote(name: string, url: string): Promise<void> {
		const args = ['remote', 'add', name, url];
		await this.run(args);
	}

J
Joao Moreno 已提交
1500
	async removeRemote(name: string): Promise<void> {
J
João Moreno 已提交
1501 1502 1503 1504 1505 1506
		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 已提交
1507 1508 1509
		await this.run(args);
	}

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

J
Joao Moreno 已提交
1514 1515
		if (options.remote) {
			args.push(options.remote);
J
Joao Moreno 已提交
1516

J
Joao Moreno 已提交
1517 1518
			if (options.ref) {
				args.push(options.ref);
J
Joao Moreno 已提交
1519
			}
J
Joao Moreno 已提交
1520 1521
		} else if (options.all) {
			args.push('--all');
J
Joao Moreno 已提交
1522 1523
		}

R
Ryan Scott 已提交
1524
		if (options.prune) {
R
Ryan Scott 已提交
1525
			args.push('--prune');
R
Ryan Scott 已提交
1526 1527
		}

1528
		if (typeof options.depth === 'number') {
1529 1530
			args.push(`--depth=${options.depth}`);
		}
R
Ryan Scott 已提交
1531

J
Joao Moreno 已提交
1532 1533 1534 1535
		if (options.silent) {
			spawnOptions.env = { 'VSCODE_GIT_FETCH_SILENT': 'true' };
		}

J
Joao Moreno 已提交
1536
		try {
J
Joao Moreno 已提交
1537
			await this.run(args, spawnOptions);
J
Joao Moreno 已提交
1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
		} 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;
		}
	}

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

J
Joao Moreno 已提交
1552
		if (options.tags) {
H
Hao Hu 已提交
1553 1554
			args.push('--tags');
		}
1555 1556 1557 1558

		if (options.unshallow) {
			args.push('--unshallow');
		}
J
Joao Moreno 已提交
1559 1560 1561 1562 1563

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

M
Matt Shirley 已提交
1564
		if (remote && branch) {
1565
			args.push(remote);
M
Matt Shirley 已提交
1566
			args.push(branch);
1567 1568
		}

J
Joao Moreno 已提交
1569
		try {
1570
			await this.run(args, options);
J
Joao Moreno 已提交
1571 1572 1573 1574 1575 1576 1577
		} 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 已提交
1578 1579
			} 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 已提交
1580
				err.gitErrorCode = GitErrorCodes.DirtyWorkTree;
J
Joao Moreno 已提交
1581 1582 1583 1584
			} 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 已提交
1585 1586 1587 1588 1589 1590
			}

			throw err;
		}
	}

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

J
Joao Moreno 已提交
1594 1595 1596 1597
		if (forcePushMode === ForcePushMode.ForceWithLease) {
			args.push('--force-with-lease');
		} else if (forcePushMode === ForcePushMode.Force) {
			args.push('--force');
1598 1599
		}

J
Joao Moreno 已提交
1600
		if (setUpstream) {
J
Joao Moreno 已提交
1601 1602 1603
			args.push('-u');
		}

1604
		if (tags) {
1605
			args.push('--follow-tags');
J
Joao Moreno 已提交
1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
		}

		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;
1623 1624
			} else if (/^fatal: The current branch .* has no upstream branch/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoUpstreamBranch;
J
Joao Moreno 已提交
1625 1626 1627 1628 1629 1630
			}

			throw err;
		}
	}

R
rebornix 已提交
1631 1632
	async blame(path: string): Promise<string> {
		try {
J
Joao Moreno 已提交
1633 1634
			const args = ['blame', sanitizePath(path)];
			const result = await this.run(args);
R
rebornix 已提交
1635 1636
			return result.stdout.trim();
		} catch (err) {
R
rebornix 已提交
1637 1638 1639 1640
			if (/^fatal: no such path/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoPathFound;
			}

R
rebornix 已提交
1641 1642 1643 1644
			throw err;
		}
	}

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

1649 1650 1651 1652
			if (includeUntracked) {
				args.push('-u');
			}

J
Joao Moreno 已提交
1653
			if (message) {
J
Joao Moreno 已提交
1654
				args.push('-m', message);
1655 1656 1657 1658 1659 1660 1661
			}

			await this.run(args);
		} catch (err) {
			if (/No local changes to save/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoLocalChanges;
			}
J
Joao Moreno 已提交
1662 1663 1664 1665 1666 1667

			throw err;
		}
	}

	async popStash(index?: number): Promise<void> {
1668
		const args = ['stash', 'pop'];
J
Joao Moreno 已提交
1669
		await this.popOrApplyStash(args, index);
1670 1671 1672 1673
	}

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

1677 1678
	private async popOrApplyStash(args: string[], index?: number): Promise<void> {
		try {
1679
			if (typeof index === 'number') {
J
Joao Moreno 已提交
1680
				args.push(`stash@{${index}}`);
1681
			}
J
Joao Moreno 已提交
1682 1683 1684 1685 1686 1687

			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 || '')) {
1688
				err.gitErrorCode = GitErrorCodes.LocalChangesOverwritten;
J
Joao Moreno 已提交
1689 1690
			} else if (/^CONFLICT/m.test(err.stdout || '')) {
				err.gitErrorCode = GitErrorCodes.StashConflict;
1691
			}
J
Joao Moreno 已提交
1692

1693 1694 1695 1696
			throw err;
		}
	}

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

D
Drew Cross 已提交
1700 1701
		if (typeof index === 'number') {
			args.push(`stash@{${index}}`);
J
Joao Moreno 已提交
1702
		}
1703

J
Joao Moreno 已提交
1704 1705
		try {
			await this.run(args);
1706 1707 1708 1709 1710 1711 1712 1713 1714
		} catch (err) {
			if (/No stash found/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoStashFound;
			}

			throw err;
		}
	}

1715 1716
	getStatus(limit = 5000): Promise<{ status: IFileStatus[]; didHitLimit: boolean; }> {
		return new Promise<{ status: IFileStatus[]; didHitLimit: boolean; }>((c, e) => {
1717
			const parser = new GitStatusParser();
J
Joao Moreno 已提交
1718 1719
			const env = { GIT_OPTIONAL_LOCKS: '0' };
			const child = this.stream(['status', '-z', '-u'], { env });
1720

M
Matt Bierner 已提交
1721
			const onExit = (exitCode: number) => {
1722
				if (exitCode !== 0) {
1723 1724 1725 1726 1727 1728 1729 1730
					const stderr = stderrData.join('');
					return e(new GitError({
						message: 'Failed to execute git',
						stderr,
						exitCode,
						gitErrorCode: getGitErrorCode(stderr),
						gitCommand: 'status'
					}));
1731
				}
J
Joao Moreno 已提交
1732

1733 1734 1735
				c({ status: parser.status, didHitLimit: false });
			};

1736
			const onStdoutData = (raw: string) => {
1737 1738
				parser.update(raw);

J
Joao Moreno 已提交
1739
				if (parser.status.length > limit) {
1740
					child.removeListener('exit', onExit);
1741
					child.stdout!.removeListener('data', onStdoutData);
1742 1743
					child.kill();

J
Joao Moreno 已提交
1744
					c({ status: parser.status.slice(0, limit), didHitLimit: true });
1745 1746 1747
				}
			};

1748 1749
			child.stdout!.setEncoding('utf8');
			child.stdout!.on('data', onStdoutData);
1750 1751

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

J
Joao Moreno 已提交
1755
			child.on('error', cpErrorHandler(e));
1756
			child.on('exit', onExit);
1757
		});
J
Joao Moreno 已提交
1758 1759
	}

J
Joao Moreno 已提交
1760
	async getHEAD(): Promise<Ref> {
J
Joao Moreno 已提交
1761
		try {
J
Joao Moreno 已提交
1762
			const result = await this.run(['symbolic-ref', '--short', 'HEAD']);
J
Joao Moreno 已提交
1763 1764 1765 1766 1767

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

R
Rob Lourens 已提交
1768
			return { name: result.stdout.trim(), commit: undefined, type: RefType.Head };
J
Joao Moreno 已提交
1769
		} catch (err) {
J
Joao Moreno 已提交
1770
			const result = await this.run(['rev-parse', 'HEAD']);
J
Joao Moreno 已提交
1771 1772 1773 1774 1775

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

R
Rob Lourens 已提交
1776
			return { name: undefined, commit: result.stdout.trim(), type: RefType.Head };
J
Joao Moreno 已提交
1777 1778 1779
		}
	}

J
Joao Moreno 已提交
1780 1781
	async findTrackingBranches(upstreamBranch: string): Promise<Branch[]> {
		const result = await this.run(['for-each-ref', '--format', '%(refname:short)%00%(upstream:short)', 'refs/heads']);
1782
		return result.stdout.trim().split('\n')
J
Joao Moreno 已提交
1783 1784 1785
			.map(line => line.trim().split('\0'))
			.filter(([_, upstream]) => upstream === upstreamBranch)
			.map(([ref]) => ({ name: ref, type: RefType.Head } as Branch));
1786 1787
	}

J
Joao Moreno 已提交
1788
	async getRefs(opts?: { sort?: 'alphabetically' | 'committerdate' }): Promise<Ref[]> {
S
skprabhanjan 已提交
1789 1790
		const args = ['for-each-ref', '--format', '%(refname) %(objectname)'];

J
Joao Moreno 已提交
1791
		if (opts && opts.sort && opts.sort !== 'alphabetically') {
1792
			args.push('--sort', `-${opts.sort}`);
S
skprabhanjan 已提交
1793 1794 1795
		}

		const result = await this.run(args);
J
Joao Moreno 已提交
1796

M
Matt Bierner 已提交
1797
		const fn = (line: string): Ref | null => {
J
Joao Moreno 已提交
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
			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 已提交
1814
			.filter(ref => !!ref) as Ref[];
J
Joao Moreno 已提交
1815 1816
	}

1817 1818
	async getStashes(): Promise<Stash[]> {
		const result = await this.run(['stash', 'list']);
J
Joao Moreno 已提交
1819
		const regex = /^stash@{(\d+)}:(.+)$/;
1820 1821
		const rawStashes = result.stdout.trim().split('\n')
			.filter(b => !!b)
M
Matt Bierner 已提交
1822
			.map(line => regex.exec(line) as RegExpExecArray)
1823
			.filter(g => !!g)
J
Joao Moreno 已提交
1824
			.map(([, index, description]: RegExpExecArray) => ({ index: parseInt(index), description }));
1825

J
Joao Moreno 已提交
1826 1827
		return rawStashes;
	}
1828

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

1834 1835
		for (const line of lines) {
			const parts = line.split(/\s/);
J
Joao Moreno 已提交
1836 1837 1838 1839
			const [name, url, type] = parts;

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

1840
			if (!remote) {
J
Joao Moreno 已提交
1841
				remote = { name, isReadOnly: false };
1842 1843 1844
				remotes.push(remote);
			}

J
Joao Moreno 已提交
1845 1846 1847 1848 1849 1850 1851
			if (/fetch/i.test(type)) {
				remote.fetchUrl = url;
			} else if (/push/i.test(type)) {
				remote.pushUrl = url;
			} else {
				remote.fetchUrl = url;
				remote.pushUrl = url;
1852 1853 1854
			}

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

1858
		return remotes;
J
Joao Moreno 已提交
1859 1860
	}

J
Joao Moreno 已提交
1861
	async getBranch(name: string): Promise<Branch> {
J
Joao Moreno 已提交
1862 1863 1864 1865
		if (name === 'HEAD') {
			return this.getHEAD();
		}

1866 1867 1868 1869 1870 1871 1872 1873
		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 已提交
1874 1875

		if (!result.stdout) {
J
Joao Moreno 已提交
1876
			return Promise.reject<Branch>(new Error('No such branch'));
J
Joao Moreno 已提交
1877 1878 1879 1880 1881
		}

		const commit = result.stdout.trim();

		try {
J
Joao Moreno 已提交
1882 1883 1884 1885 1886 1887 1888
			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 已提交
1889

J
Joao Moreno 已提交
1890 1891
			const upstream = { remote: match[1], name: match[2] };
			const res3 = await this.run(['rev-list', '--left-right', name + '...' + fullUpstream]);
J
Joao Moreno 已提交
1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911

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

1912 1913 1914
	// TODO: Support core.commentChar
	stripCommitMessageComments(message: string): string {
		return message.replace(/^\s*#.*$\n?/gm, '').trim();
1915 1916 1917 1918
	}

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

1920
		try {
J
Joao Moreno 已提交
1921
			const raw = await fs.readFile(mergeMsgPath, 'utf8');
1922
			return this.stripCommitMessageComments(raw);
J
Joao Moreno 已提交
1923
		} catch {
1924 1925 1926 1927
			return undefined;
		}
	}

J
Joao Moreno 已提交
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
	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 已提交
1942
				templatePath = path.join(this.repositoryRoot, templatePath);
J
Joao Moreno 已提交
1943 1944
			}

J
Joao Moreno 已提交
1945
			const raw = await fs.readFile(templatePath, 'utf8');
1946
			return this.stripCommitMessageComments(raw);
J
Joao Moreno 已提交
1947 1948 1949 1950 1951
		} catch (err) {
			return '';
		}
	}

J
Joao Moreno 已提交
1952
	async getCommit(ref: string): Promise<Commit> {
1953 1954 1955 1956 1957 1958
		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 已提交
1959
	}
1960 1961

	async updateSubmodules(paths: string[]): Promise<void> {
J
Joao Moreno 已提交
1962 1963
		const args = ['submodule', 'update', '--'];

J
Joao Moreno 已提交
1964
		for (const chunk of splitInChunks(paths.map(sanitizePath), MAX_CLI_LENGTH)) {
J
Joao Moreno 已提交
1965 1966
			await this.run([...args, ...chunk]);
		}
1967 1968 1969 1970 1971 1972
	}

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

		try {
J
Joao Moreno 已提交
1973
			const gitmodulesRaw = await fs.readFile(gitmodulesPath, 'utf8');
1974 1975 1976 1977 1978 1979 1980 1981 1982
			return parseGitmodules(gitmodulesRaw);
		} catch (err) {
			if (/ENOENT/.test(err.message)) {
				return [];
			}

			throw err;
		}
	}
1983
}