labels.ts 2.2 KB
Newer Older
E
Erich Gamma 已提交
1 2 3 4 5 6
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/
'use strict';

7
import URI from 'vs/base/common/uri';
E
Erich Gamma 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
import platform = require('vs/base/common/platform');
import types = require('vs/base/common/types');
import strings = require('vs/base/common/strings');
import paths = require('vs/base/common/paths');

export interface ILabelProvider {

	/**
	 * Given an element returns a label for it to display in the UI.
	 */
	getLabel(element: any): string;
}

export interface IWorkspaceProvider {
	getWorkspace(): {
23
		resource: URI;
B
Benjamin Pasero 已提交
24
	};
E
Erich Gamma 已提交
25 26 27 28 29
}

export class PathLabelProvider implements ILabelProvider {
	private root: string;

30
	constructor(arg1?: URI | string | IWorkspaceProvider) {
E
Erich Gamma 已提交
31 32 33
		this.root = arg1 && getPath(arg1);
	}

34
	public getLabel(arg1: URI | string | IWorkspaceProvider): string {
E
Erich Gamma 已提交
35 36 37 38
		return getPathLabel(getPath(arg1), this.root);
	}
}

39 40 41 42 43 44 45
export function getPathLabel(resource: URI | string, basePathProvider?: URI | string | IWorkspaceProvider): string {
	const absolutePath = getPath(resource);
	if (!absolutePath) {
		return null;
	}

	const basepath = basePathProvider && getPath(basePathProvider);
E
Erich Gamma 已提交
46 47

	if (basepath && paths.isEqualOrParent(absolutePath, basepath)) {
48 49 50 51
		if (basepath === absolutePath) {
			return ''; // no label if pathes are identical
		}

52
		return paths.normalize(strings.ltrim(absolutePath.substr(basepath.length), paths.nativeSep), true);
E
Erich Gamma 已提交
53 54
	}

55
	if (platform.isWindows && absolutePath && absolutePath[1] === ':') {
56
		return paths.normalize(absolutePath.charAt(0).toUpperCase() + absolutePath.slice(1), true); // convert c:\something => C:\something
E
Erich Gamma 已提交
57 58
	}

59
	return paths.normalize(absolutePath, true);
E
Erich Gamma 已提交
60 61
}

62
function getPath(arg1: URI | string | IWorkspaceProvider): string {
E
Erich Gamma 已提交
63 64 65 66 67 68 69 70 71
	if (!arg1) {
		return null;
	}

	if (typeof arg1 === 'string') {
		return arg1;
	}

	if (types.isFunction((<IWorkspaceProvider>arg1).getWorkspace)) {
72
		const ws = (<IWorkspaceProvider>arg1).getWorkspace();
E
Erich Gamma 已提交
73 74 75
		return ws ? ws.resource.fsPath : void 0;
	}

76
	return (<URI>arg1).fsPath;
E
Erich Gamma 已提交
77
}