export async function createGithubPermalink()

in src/issues/util.ts [426:510]


export async function createGithubPermalink(
	gitAPI: GitApiImpl,
	positionInfo?: NewIssue,
	fileUri?: vscode.Uri
): Promise<{ permalink: string | undefined; error: string | undefined, originalFile: vscode.Uri | undefined }> {
	let uri: vscode.Uri;
	let range: vscode.Range | undefined;
	if (fileUri) {
		uri = fileUri;
		if (vscode.window.activeTextEditor?.document.uri.fsPath === uri.fsPath) {
			range = vscode.window.activeTextEditor.selection;
		}
	} else if (!positionInfo && vscode.window.activeTextEditor) {
		uri = vscode.window.activeTextEditor.document.uri;
		range = vscode.window.activeTextEditor.selection;
	} else if (positionInfo) {
		uri = positionInfo.document.uri;
		range = positionInfo.range;
	} else {
		return { permalink: undefined, error: 'No active text editor position to create permalink from.', originalFile: undefined };
	}

	const repository = getRepositoryForFile(gitAPI, uri);
	if (!repository) {
		return { permalink: undefined, error: "The current file isn't part of repository.", originalFile: uri };
	}

	let commit: Commit | undefined;
	let commitHash: string | undefined;
	try {
		const log = await repository.log({ maxEntries: 1, path: uri.fsPath });
		if (log.length === 0) {
			return { permalink: undefined, error: 'No branch on a remote contains the most recent commit for the file.', originalFile: uri };
		}
		commit = log[0];
		commitHash = log[0].hash;
	} catch (e) {
		commitHash = repository.state.HEAD?.commit;
	}

	const fallbackUpstream = new Promise<Remote | undefined>(resolve => {
		if (repository.state.HEAD?.upstream) {
			for (const remote of repository.state.remotes) {
				if (repository.state.HEAD.upstream.remote === remote.name) {
					resolve(remote);
				}
			}
		}
		resolve(undefined);
	});

	let upstream: Remote | undefined = commit ? await Promise.race([
		getUpstream(repository, commit),
		new Promise<Remote | undefined>(resolve => {
			setTimeout(() => {
				resolve(fallbackUpstream);
			}, 1500);
		}),
	]) : await fallbackUpstream;

	if (!upstream || !upstream.fetchUrl) {
		// Check fallback
		upstream = await fallbackUpstream;
		if (!upstream || !upstream.fetchUrl) {
			return { permalink: undefined, error: 'The selection may not exist on any remote.', originalFile: uri };
		}
	}
	const pathSegment = uri.path.substring(repository.rootUri.path.length);
	const rangeString = () => {
		if (!range) {
			return '';
		}
		let hash = `#L${range.start.line + 1}`;
		if (range.start.line !== range.end.line) {
			hash += `-L${range.end.line + 1}`;
		}
		return hash;
	};
	return {
		permalink: `https://github.com/${new Protocol(upstream.fetchUrl).nameWithOwner}/blob/${commitHash
			}${pathSegment}${rangeString()}`,
		error: undefined,
		originalFile: uri
	};
}