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

'use strict';

import * as fs from 'fs';
import * as path from 'path';
J
Joao Moreno 已提交
10
import * as os from 'os';
J
Joao Moreno 已提交
11
import * as cp from 'child_process';
12
import { EventEmitter } from 'events';
13
import iconv = require('iconv-lite');
J
Joao Moreno 已提交
14
import * as filetype from 'file-type';
J
Joao Moreno 已提交
15 16
import { assign, uniqBy, groupBy, denodeify, IDisposable, toDisposable, dispose, mkdirp, readBytes, detectUnicodeEncoding, Encoding, onceEvent } from './util';
import { CancellationToken } from 'vscode';
J
Joao Moreno 已提交
17

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

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

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

J
Joao Moreno 已提交
32
export interface Remote {
J
Joao Moreno 已提交
33 34 35 36
	name: string;
	url: string;
}

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

J
Joao Moreno 已提交
42 43 44 45 46 47
export enum RefType {
	Head,
	RemoteHead,
	Tag
}

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

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

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

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

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

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

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

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

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

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

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

J
Joao Moreno 已提交
127 128 129 130
function findGitWin32(onLookup: (path: string) => void): Promise<IGit> {
	return findSystemGitWin32(process.env['ProgramW6432'] as string, onLookup)
		.then(void 0, () => findSystemGitWin32(process.env['ProgramFiles(x86)'] as string, onLookup))
		.then(void 0, () => findSystemGitWin32(process.env['ProgramFiles'] as string, onLookup));
J
Joao Moreno 已提交
131 132
}

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

J
Joao Moreno 已提交
136 137 138
	return first
		.then(void 0, () => {
			switch (process.platform) {
J
Joao Moreno 已提交
139 140 141
				case 'darwin': return findGitDarwin(onLookup);
				case 'win32': return findGitWin32(onLookup);
				default: return findSpecificGit('git', onLookup);
J
Joao Moreno 已提交
142 143 144
			}
		})
		.then(null, () => Promise.reject(new Error('Git installation not found.')));
J
Joao Moreno 已提交
145 146
}

J
Joao Moreno 已提交
147
export interface IExecutionResult<T extends string | Buffer> {
J
Joao Moreno 已提交
148
	exitCode: number;
J
Joao Moreno 已提交
149
	stdout: T;
J
Joao Moreno 已提交
150 151 152
	stderr: string;
}

J
Joao Moreno 已提交
153 154 155 156 157 158 159 160 161 162 163 164 165 166
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 已提交
167
export interface SpawnOptions extends cp.SpawnOptions {
J
Joao Moreno 已提交
168 169 170
	input?: string;
	encoding?: string;
	log?: boolean;
J
Joao Moreno 已提交
171
	cancellationToken?: CancellationToken;
J
Joao Moreno 已提交
172 173
}

J
Joao Moreno 已提交
174
async function exec(child: cp.ChildProcess, cancellationToken?: CancellationToken): Promise<IExecutionResult<Buffer>> {
J
Joao Moreno 已提交
175
	if (!child.stdout || !child.stderr) {
J
Joao Moreno 已提交
176 177 178 179 180
		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 已提交
181 182
	}

J
Joao Moreno 已提交
183 184
	const disposables: IDisposable[] = [];

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

M
Matt Bierner 已提交
190
	const on = (ee: NodeJS.EventEmitter, name: string, fn: (...args: any[]) => void) => {
J
Joao Moreno 已提交
191 192 193 194
		ee.on(name, fn);
		disposables.push(toDisposable(() => ee.removeListener(name, fn)));
	};

J
Joao Moreno 已提交
195
	let result = Promise.all<any>([
J
Joao Moreno 已提交
196
		new Promise<number>((c, e) => {
J
Joao Moreno 已提交
197
			once(child, 'error', cpErrorHandler(e));
J
Joao Moreno 已提交
198 199
			once(child, 'exit', c);
		}),
J
Joao Moreno 已提交
200
		new Promise<Buffer>(c => {
201
			const buffers: Buffer[] = [];
M
Matt Bierner 已提交
202
			on(child.stdout, 'data', (b: Buffer) => buffers.push(b));
J
Joao Moreno 已提交
203
			once(child.stdout, 'close', () => c(Buffer.concat(buffers)));
J
Joao Moreno 已提交
204 205
		}),
		new Promise<string>(c => {
206
			const buffers: Buffer[] = [];
M
Matt Bierner 已提交
207
			on(child.stderr, 'data', (b: Buffer) => buffers.push(b));
J
Joao Moreno 已提交
208
			once(child.stderr, 'close', () => c(Buffer.concat(buffers).toString('utf8')));
J
Joao Moreno 已提交
209
		})
J
Joao Moreno 已提交
210 211 212 213 214 215 216 217 218 219
	]) 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 已提交
220

J
Joao Moreno 已提交
221 222 223 224 225 226
				e(new GitError({ message: 'Cancelled' }));
			});
		});

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

J
Joao Moreno 已提交
228 229 230 231 232 233
	try {
		const [exitCode, stdout, stderr] = await result;
		return { exitCode, stdout, stderr };
	} finally {
		dispose(disposables);
	}
J
Joao Moreno 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247
}

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

export class GitError {

J
Joao Moreno 已提交
248
	error?: Error;
J
Joao Moreno 已提交
249
	message: string;
J
Joao Moreno 已提交
250 251 252 253 254
	stdout?: string;
	stderr?: string;
	exitCode?: number;
	gitErrorCode?: string;
	gitCommand?: string;
J
Joao Moreno 已提交
255 256 257 258 259 260

	constructor(data: IGitErrorData) {
		if (data.error) {
			this.error = data.error;
			this.message = data.error.message;
		} else {
J
Joao Moreno 已提交
261
			this.error = void 0;
J
Joao Moreno 已提交
262 263 264
		}

		this.message = this.message || data.message || 'Git error';
J
Joao Moreno 已提交
265 266 267 268 269
		this.stdout = data.stdout;
		this.stderr = data.stderr;
		this.exitCode = data.exitCode;
		this.gitErrorCode = data.gitErrorCode;
		this.gitCommand = data.gitCommand;
J
Joao Moreno 已提交
270 271 272 273 274 275 276 277 278
	}

	toString(): string {
		let result = this.message + ' ' + JSON.stringify({
			exitCode: this.exitCode,
			gitErrorCode: this.gitErrorCode,
			gitCommand: this.gitCommand,
			stdout: this.stdout,
			stderr: this.stderr
279
		}, null, 2);
J
Joao Moreno 已提交
280 281 282 283 284 285 286 287 288 289 290 291

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

		return result;
	}
}

export interface IGitOptions {
	gitPath: string;
	version: string;
292
	env?: any;
J
Joao Moreno 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
}

export const GitErrorCodes = {
	BadConfigFile: 'BadConfigFile',
	AuthenticationFailed: 'AuthenticationFailed',
	NoUserNameConfigured: 'NoUserNameConfigured',
	NoUserEmailConfigured: 'NoUserEmailConfigured',
	NoRemoteRepositorySpecified: 'NoRemoteRepositorySpecified',
	NotAGitRepository: 'NotAGitRepository',
	NotAtRepositoryRoot: 'NotAtRepositoryRoot',
	Conflict: 'Conflict',
	UnmergedChanges: 'UnmergedChanges',
	PushRejected: 'PushRejected',
	RemoteConnectionError: 'RemoteConnectionError',
	DirtyWorkTree: 'DirtyWorkTree',
	CantOpenResource: 'CantOpenResource',
	GitNotFound: 'GitNotFound',
	CantCreatePipe: 'CantCreatePipe',
	CantAccessRemote: 'CantAccessRemote',
312
	RepositoryNotFound: 'RepositoryNotFound',
313
	RepositoryIsLocked: 'RepositoryIsLocked',
314
	BranchNotFullyMerged: 'BranchNotFullyMerged',
315
	NoRemoteReference: 'NoRemoteReference',
316
	InvalidBranchName: 'InvalidBranchName',
317
	BranchAlreadyExists: 'BranchAlreadyExists',
318 319 320
	NoLocalChanges: 'NoLocalChanges',
	NoStashFound: 'NoStashFound',
	LocalChangesOverwritten: 'LocalChangesOverwritten'
J
Joao Moreno 已提交
321 322
};

323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
function getGitErrorCode(stderr: string): string | undefined {
	if (/Another git process seems to be running in this repository|If no other git process is currently running/.test(stderr)) {
		return GitErrorCodes.RepositoryIsLocked;
	} else if (/Authentication failed/.test(stderr)) {
		return GitErrorCodes.AuthenticationFailed;
	} else if (/Not a git repository/.test(stderr)) {
		return GitErrorCodes.NotAGitRepository;
	} else if (/bad config file/.test(stderr)) {
		return GitErrorCodes.BadConfigFile;
	} else if (/cannot make pipe for command substitution|cannot create standard input pipe/.test(stderr)) {
		return GitErrorCodes.CantCreatePipe;
	} else if (/Repository not found/.test(stderr)) {
		return GitErrorCodes.RepositoryNotFound;
	} else if (/unable to access/.test(stderr)) {
		return GitErrorCodes.CantAccessRemote;
338 339
	} else if (/branch '.+' is not fully merged/.test(stderr)) {
		return GitErrorCodes.BranchNotFullyMerged;
340 341
	} else if (/Couldn\'t find remote ref/.test(stderr)) {
		return GitErrorCodes.NoRemoteReference;
342 343 344 345
	} 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;
346 347 348 349 350
	}

	return void 0;
}

J
Joao Moreno 已提交
351 352
export class Git {

J
Joao Moreno 已提交
353 354
	private gitPath: string;
	private version: string;
355
	private env: any;
J
Joao Moreno 已提交
356

357 358
	private _onOutput = new EventEmitter();
	get onOutput(): EventEmitter { return this._onOutput; }
J
Joao Moreno 已提交
359

J
Joao Moreno 已提交
360 361 362
	constructor(options: IGitOptions) {
		this.gitPath = options.gitPath;
		this.version = options.version;
363
		this.env = options.env || {};
J
Joao Moreno 已提交
364 365
	}

366 367
	open(repository: string): Repository {
		return new Repository(this, repository);
J
Joao Moreno 已提交
368 369
	}

J
Joao Moreno 已提交
370 371 372 373 374
	async init(repository: string): Promise<void> {
		await this.exec(repository, ['init']);
		return;
	}

J
Joao Moreno 已提交
375
	async clone(url: string, parentPath: string, cancellationToken?: CancellationToken): Promise<string> {
J
Joao Moreno 已提交
376
		const folderName = decodeURI(url).replace(/^.*\//, '').replace(/\.git$/, '') || 'repository';
J
Joao Moreno 已提交
377 378
		const folderPath = path.join(parentPath, folderName);

J
Joao Moreno 已提交
379
		await mkdirp(parentPath);
J
Joao Moreno 已提交
380
		await this.exec(parentPath, ['clone', url, folderPath], { cancellationToken });
J
Joao Moreno 已提交
381 382 383
		return folderPath;
	}

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

J
Joao Moreno 已提交
389
	async exec(cwd: string, args: string[], options: SpawnOptions = {}): Promise<IExecutionResult<string>> {
J
Joao Moreno 已提交
390
		options = assign({ cwd }, options || {});
J
Joao Moreno 已提交
391
		return await this._exec(args, options);
J
Joao Moreno 已提交
392 393
	}

J
Joao Moreno 已提交
394
	stream(cwd: string, args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
395
		options = assign({ cwd }, options || {});
J
Joao Moreno 已提交
396
		return this.spawn(args, options);
J
Joao Moreno 已提交
397 398
	}

J
Joao Moreno 已提交
399
	private async _exec(args: string[], options: SpawnOptions = {}): Promise<IExecutionResult<string>> {
J
Joao Moreno 已提交
400
		const child = this.spawn(args, options);
J
Joao Moreno 已提交
401 402 403 404 405

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

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

J
Joao Moreno 已提交
408 409
		if (options.log !== false && bufferResult.stderr.length > 0) {
			this.log(`${bufferResult.stderr}\n`);
J
Joao Moreno 已提交
410 411
		}

J
Joao Moreno 已提交
412 413 414 415 416 417 418 419 420 421 422
		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 已提交
423 424 425 426
				message: 'Failed to execute git',
				stdout: result.stdout,
				stderr: result.stderr,
				exitCode: result.exitCode,
427
				gitErrorCode: getGitErrorCode(result.stderr),
J
Joao Moreno 已提交
428 429 430 431 432
				gitCommand: args[0]
			}));
		}

		return result;
J
Joao Moreno 已提交
433 434
	}

J
Joao Moreno 已提交
435
	spawn(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
436 437 438 439 440 441 442 443 444 445 446 447
		if (!this.gitPath) {
			throw new Error('git could not be found in the system.');
		}

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

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

448
		options.env = assign({}, process.env, this.env, options.env || {}, {
J
Joao Moreno 已提交
449
			VSCODE_GIT_COMMAND: args[0],
450
			LC_ALL: 'en_US.UTF-8',
J
Joao Moreno 已提交
451 452
			LANG: 'en_US.UTF-8'
		});
J
Joao Moreno 已提交
453 454

		if (options.log !== false) {
J
Joao Moreno 已提交
455
			this.log(`git ${args.join(' ')}\n`);
J
Joao Moreno 已提交
456 457 458 459 460 461
		}

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

	private log(output: string): void {
462
		this._onOutput.emit('log', output);
J
Joao Moreno 已提交
463
	}
J
Joao Moreno 已提交
464 465
}

J
Joao Moreno 已提交
466
export interface Commit {
J
Joao Moreno 已提交
467 468 469 470
	hash: string;
	message: string;
}

471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
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 已提交
509
		if (entry.x === 'R' || entry.x === 'C') {
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
			lastIndex = raw.indexOf('\0', i);

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

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

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

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

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

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

		return lastIndex + 1;
	}
}

J
Joao Moreno 已提交
537 538 539 540
export class Repository {

	constructor(
		private _git: Git,
541
		private repositoryRoot: string
J
Joao Moreno 已提交
542 543 544 545 546 547
	) { }

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

J
Joao Moreno 已提交
548 549
	get root(): string {
		return this.repositoryRoot;
J
Joao Moreno 已提交
550 551 552
	}

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

J
Joao Moreno 已提交
557
	stream(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
558
		return this.git.stream(this.repositoryRoot, args, options);
J
Joao Moreno 已提交
559 560
	}

J
Joao Moreno 已提交
561
	spawn(args: string[], options: SpawnOptions = {}): cp.ChildProcess {
J
Joao Moreno 已提交
562 563 564
		return this.git.spawn(args, options);
	}

J
Joao Moreno 已提交
565
	async config(scope: string, key: string, value: any, options: SpawnOptions): Promise<string> {
J
Joao Moreno 已提交
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
		const args = ['config'];

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

		args.push(key);

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

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

J
Joao Moreno 已提交
582 583 584 585 586 587
	async bufferString(object: string, encoding: string = 'utf8'): Promise<string> {
		const stdout = await this.buffer(object);
		return iconv.decode(stdout, iconv.encodingExists(encoding) ? encoding : 'utf8');
	}

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

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

J
Joao Moreno 已提交
594
		const { exitCode, stdout } = await exec(child);
J
Joao Moreno 已提交
595 596

		if (exitCode) {
J
Joao Moreno 已提交
597
			return Promise.reject<Buffer>(new GitError({
J
Joao Moreno 已提交
598 599 600 601 602 603
				message: 'Could not show object.',
				exitCode
			}));
		}

		return stdout;
J
Joao Moreno 已提交
604 605
	}

J
Joao Moreno 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
	async lstree(treeish: string, path: string): Promise<{ mode: number, object: string, size: number }> {
		if (!treeish) { // index
			const { stdout } = await this.run(['ls-files', '--stage', '--', path]);

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

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

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

			return { mode: parseInt(mode), object, size };
		}

J
Joao Moreno 已提交
623 624 625 626 627 628 629 630
		const { stdout } = await this.run(['ls-tree', '-l', treeish, '--', path]);

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

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

J
Joao Moreno 已提交
631 632
		const [, mode, , object, size] = match;
		return { mode: parseInt(mode), object, size: parseInt(size) };
J
Joao Moreno 已提交
633 634 635 636 637 638 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 673 674
	}

	async detectObjectType(object: string): Promise<{ mimetype: string, encoding?: string }> {
		const child = await this.stream(['show', object]);
		const buffer = await readBytes(child.stdout, 4100);

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

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

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

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

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

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

J
Joao Moreno 已提交
675 676 677 678 679 680 681 682 683 684 685 686 687
	async add(paths: string[]): Promise<void> {
		const args = ['add', '-A', '--'];

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

		await this.run(args);
	}

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

		const { exitCode, stdout } = await exec(child);
J
Joao Moreno 已提交
692
		const hash = stdout.toString('utf8');
J
Joao Moreno 已提交
693 694 695 696 697 698 699 700

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

J
Joao Moreno 已提交
701
		await this.run(['update-index', '--cacheinfo', '100644', hash, path]);
J
Joao Moreno 已提交
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
	}

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

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

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

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

			throw err;
		}
	}

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

J
Joao Moreno 已提交
730
		if (opts.all) {
J
Joao Moreno 已提交
731 732 733
			args.push('--all');
		}

J
Joao Moreno 已提交
734
		if (opts.amend) {
J
Joao Moreno 已提交
735 736 737
			args.push('--amend');
		}

J
Joao Moreno 已提交
738
		if (opts.signoff) {
J
Joao Moreno 已提交
739 740 741
			args.push('--signoff');
		}

742 743 744 745
		if (opts.signCommit) {
			args.push('-S');
		}

J
Joao Moreno 已提交
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
		try {
			await this.run(args, { input: message || '' });
		} catch (commitErr) {
			if (/not possible because you have unmerged files/.test(commitErr.stderr || '')) {
				commitErr.gitErrorCode = GitErrorCodes.UnmergedChanges;
				throw commitErr;
			}

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

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

			throw commitErr;
		}
	}

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

777 778
	async deleteBranch(name: string, force?: boolean): Promise<void> {
		const args = ['branch', force ? '-D' : '-d', name];
M
Maik Riechert 已提交
779 780 781
		await this.run(args);
	}

782 783 784 785 786
	async renameBranch(name: string): Promise<void> {
		const args = ['branch', '-m', name];
		await this.run(args);
	}

J
Joao Moreno 已提交
787 788 789 790 791 792 793 794 795 796 797 798
	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;
		}
799 800
	}

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

J
Joao Moreno 已提交
804 805
		if (message) {
			args = [...args, '-a', name, '-m', message];
806
		} else {
J
Joao Moreno 已提交
807
			args = [...args, name];
808 809 810 811 812
		}

		await this.run(args);
	}

J
Joao Moreno 已提交
813
	async clean(paths: string[]): Promise<void> {
J
Joao Moreno 已提交
814 815 816
		const pathsByGroup = groupBy(paths, p => path.dirname(p));
		const groups = Object.keys(pathsByGroup).map(k => pathsByGroup[k]);
		const tasks = groups.map(paths => () => this.run(['clean', '-f', '-q', '--'].concat(paths)));
J
Joao Moreno 已提交
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848

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

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

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

			throw err;
		}
	}

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

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

		args.push(treeish);

		await this.run(args);
	}

J
Joao Moreno 已提交
849
	async revert(treeish: string, paths: string[]): Promise<void> {
J
Joao Moreno 已提交
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
		const result = await this.run(['branch']);
		let args: string[];

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

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

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

			throw err;
		}
	}

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

			throw err;
		}
	}

M
Matt Shirley 已提交
893
	async pull(rebase?: boolean, remote?: string, branch?: string): Promise<void> {
J
Joao Moreno 已提交
894 895 896 897 898 899
		const args = ['pull'];

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

M
Matt Shirley 已提交
900
		if (remote && branch) {
901
			args.push(remote);
M
Matt Shirley 已提交
902
			args.push(branch);
903 904
		}

J
Joao Moreno 已提交
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921
		try {
			await this.run(args);
		} catch (err) {
			if (/^CONFLICT \([^)]+\): \b/m.test(err.stdout || '')) {
				err.gitErrorCode = GitErrorCodes.Conflict;
			} else if (/Please tell me who you are\./.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoUserNameConfigured;
			} else if (/Could not read from remote repository/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.RemoteConnectionError;
			} else if (/Pull is not possible because you have unmerged files|Cannot pull with rebase: You have unstaged changes|Your local changes to the following files would be overwritten|Please, commit your changes before you can merge/.test(err.stderr)) {
				err.gitErrorCode = GitErrorCodes.DirtyWorkTree;
			}

			throw err;
		}
	}

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

J
Joao Moreno 已提交
925
		if (setUpstream) {
J
Joao Moreno 已提交
926 927 928
			args.push('-u');
		}

929 930
		if (tags) {
			args.push('--tags');
J
Joao Moreno 已提交
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953
		}

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

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

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

			throw err;
		}
	}

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

958 959 960 961
			if (includeUntracked) {
				args.push('-u');
			}

J
Joao Moreno 已提交
962 963
			if (message) {
				args.push('--', message);
964 965 966 967 968 969 970
			}

			await this.run(args);
		} catch (err) {
			if (/No local changes to save/.test(err.stderr || '')) {
				err.gitErrorCode = GitErrorCodes.NoLocalChanges;
			}
J
Joao Moreno 已提交
971 972 973 974 975 976 977 978 979 980 981

			throw err;
		}
	}

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

			if (typeof index === 'string') {
				args.push(`stash@{${index}}`);
982
			}
J
Joao Moreno 已提交
983 984 985 986 987 988

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

992 993 994 995
			throw err;
		}
	}

996 997
	getStatus(limit = 5000): Promise<{ status: IFileStatus[]; didHitLimit: boolean; }> {
		return new Promise<{ status: IFileStatus[]; didHitLimit: boolean; }>((c, e) => {
998
			const parser = new GitStatusParser();
J
Joao Moreno 已提交
999 1000
			const env = { GIT_OPTIONAL_LOCKS: '0' };
			const child = this.stream(['status', '-z', '-u'], { env });
1001

M
Matt Bierner 已提交
1002
			const onExit = (exitCode: number) => {
1003
				if (exitCode !== 0) {
1004 1005 1006 1007 1008 1009 1010 1011
					const stderr = stderrData.join('');
					return e(new GitError({
						message: 'Failed to execute git',
						stderr,
						exitCode,
						gitErrorCode: getGitErrorCode(stderr),
						gitCommand: 'status'
					}));
1012
				}
J
Joao Moreno 已提交
1013

1014 1015 1016
				c({ status: parser.status, didHitLimit: false });
			};

1017
			const onStdoutData = (raw: string) => {
1018 1019
				parser.update(raw);

J
Joao Moreno 已提交
1020
				if (parser.status.length > limit) {
1021
					child.removeListener('exit', onExit);
1022
					child.stdout.removeListener('data', onStdoutData);
1023 1024
					child.kill();

J
Joao Moreno 已提交
1025
					c({ status: parser.status.slice(0, limit), didHitLimit: true });
1026 1027 1028 1029
				}
			};

			child.stdout.setEncoding('utf8');
1030 1031 1032 1033 1034 1035
			child.stdout.on('data', onStdoutData);

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

J
Joao Moreno 已提交
1036
			child.on('error', cpErrorHandler(e));
1037
			child.on('exit', onExit);
1038
		});
J
Joao Moreno 已提交
1039 1040
	}

J
Joao Moreno 已提交
1041
	async getHEAD(): Promise<Ref> {
J
Joao Moreno 已提交
1042
		try {
J
Joao Moreno 已提交
1043
			const result = await this.run(['symbolic-ref', '--short', 'HEAD']);
J
Joao Moreno 已提交
1044 1045 1046 1047 1048 1049 1050

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

			return { name: result.stdout.trim(), commit: void 0, type: RefType.Head };
		} catch (err) {
J
Joao Moreno 已提交
1051
			const result = await this.run(['rev-parse', 'HEAD']);
J
Joao Moreno 已提交
1052 1053 1054 1055 1056 1057 1058 1059 1060

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

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

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

M
Matt Bierner 已提交
1064
		const fn = (line: string): Ref | null => {
J
Joao Moreno 已提交
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
			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 已提交
1081
			.filter(ref => !!ref) as Ref[];
J
Joao Moreno 已提交
1082 1083
	}

1084 1085
	async getStashes(): Promise<Stash[]> {
		const result = await this.run(['stash', 'list']);
J
Joao Moreno 已提交
1086
		const regex = /^stash@{(\d+)}:(.+)$/;
1087 1088
		const rawStashes = result.stdout.trim().split('\n')
			.filter(b => !!b)
M
Matt Bierner 已提交
1089
			.map(line => regex.exec(line) as RegExpExecArray)
1090
			.filter(g => !!g)
J
Joao Moreno 已提交
1091
			.map(([, index, description]: RegExpExecArray) => ({ index: parseInt(index), description }));
1092

J
Joao Moreno 已提交
1093 1094
		return rawStashes;
	}
1095

J
Joao Moreno 已提交
1096
	async getRemotes(): Promise<Remote[]> {
J
Joao Moreno 已提交
1097
		const result = await this.run(['remote', '--verbose']);
J
Joao Moreno 已提交
1098
		const regex = /^([^\s]+)\s+([^\s]+)\s/;
J
Joao Moreno 已提交
1099
		const rawRemotes = result.stdout.trim().split('\n')
J
Joao Moreno 已提交
1100
			.filter(b => !!b)
M
Matt Bierner 已提交
1101
			.map(line => regex.exec(line) as RegExpExecArray)
J
Joao Moreno 已提交
1102
			.filter(g => !!g)
J
Joao Moreno 已提交
1103 1104 1105
			.map((groups: RegExpExecArray) => ({ name: groups[1], url: groups[2] }));

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

J
Joao Moreno 已提交
1108
	async getBranch(name: string): Promise<Branch> {
J
Joao Moreno 已提交
1109 1110 1111 1112
		if (name === 'HEAD') {
			return this.getHEAD();
		}

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

		if (!result.stdout) {
J
Joao Moreno 已提交
1116
			return Promise.reject<Branch>(new Error('No such branch'));
J
Joao Moreno 已提交
1117 1118 1119 1120 1121
		}

		const commit = result.stdout.trim();

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

J
Joao Moreno 已提交
1125
			const res3 = await this.run(['rev-list', '--left-right', name + '...' + upstream]);
J
Joao Moreno 已提交
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159

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

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

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

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

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

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

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

			if (!path.isAbsolute(templatePath)) {
J
Joao Moreno 已提交
1160
				templatePath = path.join(this.repositoryRoot, templatePath);
J
Joao Moreno 已提交
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
			}

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

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

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

		if (!match) {
J
Joao Moreno 已提交
1176
			return Promise.reject<Commit>('bad commit format');
J
Joao Moreno 已提交
1177 1178 1179 1180
		}

		return { hash: match[1], message: match[2] };
	}
1181
}