remote.ts 1.2 KB
Newer Older
M
Matt Bierner 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
import { GitProcess } from 'dugite';
import { IGitRemoteURL } from './models/remote';

export async function getRemotes(
	path: string
) {
	const result = await GitProcess.exec(['remote', '-v'], path);
	const output = result.stdout;
	const lines = output.split('\n');
	const remotes = lines
		.filter(x => x.endsWith('(fetch)'))
		.map(x => x.split(/\s+/))
		.map(x => ({ name: x[0], url: x[1] }));

	return remotes;
}

/** Parse the remote information from URL. */
export function parseRemote(url: string): IGitRemoteURL | null {
	// Examples:
	// https://github.com/octocat/Hello-World.git
	// https://github.com/octocat/Hello-World.git/
	// git@github.com:octocat/Hello-World.git
	// git:github.com/octocat/Hello-World.git
	const regexes = [
		new RegExp('^https?://(?:.+@)?(.+)/(.+)/(.+?)(?:/|.git/?)?$'),
		new RegExp('^git@(.+):(.+)/(.+?)(?:/|.git)?$'),
		new RegExp('^git:(.+)/(.+)/(.+?)(?:/|.git)?$'),
		new RegExp('^ssh://git@(.+)/(.+)/(.+?)(?:/|.git)?$')
	];

	for (const regex of regexes) {
		const result = url.match(regex);
		if (!result) {
			continue;
		}

		const hostname = result[1];
		const owner = result[2];
		const name = result[3];
		if (hostname) {
			return { hostname, owner, name };
		}
	}

	return null;
}