Example #1
0
    public constructor(workspaceInfo: protocol.WorkspaceInformationResponse, workspaceFolder: vscode.WorkspaceFolder = undefined) {
        if (workspaceFolder) {
            this.workspaceFolder = workspaceFolder;
        }
        else {
            let resourcePath: string = undefined;

            if (!resourcePath && workspaceInfo.Cake) {
                resourcePath = workspaceInfo.Cake.Path;
            }

            if (!resourcePath && workspaceInfo.ScriptCs) {
                resourcePath = workspaceInfo.ScriptCs.Path;
            }

            if (!resourcePath && workspaceInfo.DotNet && workspaceInfo.DotNet.Projects.length > 0) {
                resourcePath = workspaceInfo.DotNet.Projects[0].Path;
            }

            if (!resourcePath && workspaceInfo.MsBuild) {
                resourcePath = workspaceInfo.MsBuild.SolutionPath;
            }

            this.workspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(resourcePath));
        }

        this.vscodeFolder = path.join(this.workspaceFolder.uri.fsPath, '.vscode');
        this.tasksJsonPath = path.join(this.vscodeFolder, 'tasks.json');
        this.launchJsonPath = path.join(this.vscodeFolder, 'launch.json');

        this.initializeProjectData(workspaceInfo);
    }
Example #2
0
function runTest(sourceUri: string, className: string, methodName: string): Thenable<TaskExecution> {
    let file = Uri.parse(sourceUri).fsPath;
    file = Path.relative(workspace.rootPath, file);
	let kind: JavaTestTask = {
		type: 'java.task.test',
        className: className,
        methodName: methodName,
    }
    var shell;
    let config = workspace.getConfiguration('java')
    // Run method or class
    if (methodName != null) {
        let command = config.get('testMethod') as string[]
        if (command.length == 0) {
            window.showErrorMessage('Set "java.testMethod" in .vscode/settings.json')
            shell = new ShellExecution('echo', ['Set "java.testMethod" in .vscode/settings.json, for example ["mvn", "test", "-Dtest=${class}#${method}"]'])
        } else {
            shell = templateCommand(command, file, className, methodName)
        }
    } else {
        let command = config.get('testClass') as string[]
        if (command.length == 0) {
            window.showErrorMessage('Set "java.testClass" in .vscode/settings.json')
            shell = new ShellExecution('echo', ['Set "java.testClass" in .vscode/settings.json, for example ["mvn", "test", "-Dtest=${class}"]'])
        } else {
            shell = templateCommand(command, file, className, methodName)
        }
    }
	let workspaceFolder = workspace.getWorkspaceFolder(Uri.parse(sourceUri))
	let task = new Task(kind, workspaceFolder, 'Java Test', 'Java Language Server', shell)
	return tasks.executeTask(task)
}
Example #3
0
    return compilerPaths.map<vscode.Task>(compilerPath => {
        // Handle compiler args in compilerPath.
        let compilerPathAndArgs: util.CompilerPathAndArgs = util.extractCompilerPathAndArgs(compilerPath);
        compilerPath = compilerPathAndArgs.compilerPath;
        const filePath: string = path.join('${fileDirname}', '${fileBasenameNoExtension}');
        const compilerPathBase: string = path.basename(compilerPath);
        const taskName: string = compilerPathBase + " build active file";
        const isCl: boolean = taskName.startsWith("cl.exe");
        let args: string[] = isCl ? [ '/Zi', '/EHsc', '/Fe:', filePath + '.exe', '${file}'  ] : ['-g', '${file}', '-o', filePath + (isWindows ? '.exe' : '')];
        if (compilerPathAndArgs.additionalArgs) {
            args = args.concat(compilerPathAndArgs.additionalArgs);
        }
        const cwd: string = isCl ? "" : path.dirname(compilerPath);
        const kind: BuildTaskDefinition = {
            type: 'shell',
            label: taskName,
            command: isCl ? compilerPathBase : compilerPath,
            args: args,
            options: isCl ? undefined : {"cwd": cwd},
            compilerPath: isCl ? compilerPathBase : compilerPath
        };

        const command: vscode.ShellExecution = new vscode.ShellExecution(compilerPath, [...args], { cwd: cwd });
        const target: vscode.WorkspaceFolder = vscode.workspace.getWorkspaceFolder(clients.ActiveClient.RootUri);
        let task: vscode.Task = new vscode.Task(kind, target, taskName, taskSourceStr, command, '$gcc');
        task.definition = kind; // The constructor for vscode.Task will eat the definition. Reset it by reassigning.
        task.group = vscode.TaskGroup.Build;

        if (!returnComplerPath) {
            delete task.definition.compilerPath;
        }

        return task;
    });
Example #4
0
async function provideNpmScriptsForFolder(packageJsonUri: Uri): Promise<Task[]> {
	let emptyTasks: Task[] = [];

	let folder = workspace.getWorkspaceFolder(packageJsonUri);
	if (!folder) {
		return emptyTasks;
	}
	let scripts = await getScripts(packageJsonUri);
	if (!scripts) {
		return emptyTasks;
	}

	const result: Task[] = [];

	const prePostScripts = getPrePostScripts(scripts);
	Object.keys(scripts).forEach(each => {
		const task = createTask(each, `run ${each}`, folder!, packageJsonUri);
		const lowerCaseTaskName = each.toLowerCase();
		if (isBuildTask(lowerCaseTaskName)) {
			task.group = TaskGroup.Build;
		} else if (isTestTask(lowerCaseTaskName)) {
			task.group = TaskGroup.Test;
		}
		if (prePostScripts.has(each)) {
			task.group = TaskGroup.Clean; // hack: use Clean group to tag pre/post scripts
		}
		if (isDebugScript(scripts![each])) {
			task.group = TaskGroup.Rebuild; // hack: use Rebuild group to tag debug scripts
		}
		result.push(task);
	});
	// always add npm install (without a problem matcher)
	result.push(createTask('install', 'install', folder, packageJsonUri, []));
	return result;
}
	private createDisplayPath(inputPath: string): string {
		// HACK: The AS returns paths to the PUB_CACHE folder, which Code can't
		// convert to relative paths (so they look terrible). If the file exists in
		// workspace.rootPath we rewrite the path to there which gives us a nice
		// relative path.

		// Currently I only do this for "hosted\pub.dartlang.org" as I'm not sure of the
		// rules for these paths!

		const pubCachePath = "hosted" + path.sep + "pub.dartlang.org";
		const pubCachePathIndex = inputPath.indexOf(pubCachePath);
		if (pubCachePathIndex > -1) {
			const relativePath = inputPath.substring(pubCachePathIndex + pubCachePath.length + 1);

			// Packages in pubcache are versioned so trim the "-x.x.x" off the end of the foldername.
			const pathComponents = relativePath.split(path.sep);
			pathComponents[0] = pathComponents[0].split("-")[0];

			// Symlink goes into the lib folder, so strip that out of the path.
			if (pathComponents[1] === "lib")
				pathComponents.splice(1, 1);

			// Return 'package:foo/bar.dart'.
			inputPath = `package:${pathComponents[0]}/${pathComponents.slice(1).join("/")}`;
		} else {
			const root = workspace.getWorkspaceFolder(Uri.file(inputPath));
			inputPath = root && path.relative(fsPath(root.uri), inputPath);
		}

		return inputPath;
	}
Example #6
0
                configuration: (params, token, next) => {
                    if (!params.items) {
                        return [];
                    }

                    const result = next(params, token);
                    let scopeUri = "";

                    for (const item of params.items) {
                        if (!item.scopeUri) {
                            continue;
                        } else {
                            scopeUri = item.scopeUri;
                        }
                    }

                    const resource = client.protocol2CodeConverter.asUri(scopeUri);
                    const workspaceFolder = workspace.getWorkspaceFolder(resource);

                    if (workspaceFolder) {
                        convertToAbsolutePaths(result[0], workspaceFolder);

                        if (workspaceFolder.uri.scheme === "file") {
                            result[0].workspaceFolderPath = workspaceFolder.uri.fsPath;
                        }
                    }

                    return result;
                }
export function findSettingsFiles(uri?: Uri): Thenable<Uri[]> {
    const { workspaceFolders } = workspace;
    if (!workspaceFolders || !hasWorkspaceLocation()) {
        return Promise.resolve([]);
    }

    const folders = uri
        ? [workspace.getWorkspaceFolder(uri)!].filter(a => !!a)
        : workspaceFolders;

    const possibleLocations = folders
        .map(folder => folder.uri.fsPath)
        .map(root => configFileLocations.map(rel => path.join(root, rel)))
        .reduce((a, b) => a.concat(b));

    const found = possibleLocations
        .map(filename => fs.pathExists(filename)
        .then(exists => ({ filename, exists })));

    return Promise.all(found).then(found => found
        .filter(found => found.exists)
        .map(found => found.filename)
        .map(filename => Uri.file(filename))
    );
}
	private fixHref(resource: vscode.Uri, href: string): string {
		if (!href) {
			return href;
		}

		// Use href if it is already an URL
		const hrefUri = vscode.Uri.parse(href);
		if (['http', 'https'].indexOf(hrefUri.scheme) >= 0) {
			return hrefUri.toString();
		}

		// Use href as file URI if it is absolute
		if (path.isAbsolute(href) || hrefUri.scheme === 'file') {
			return vscode.Uri.file(href)
				.with({ scheme: 'vscode-resource' })
				.toString();
		}

		// Use a workspace relative path if there is a workspace
		let root = vscode.workspace.getWorkspaceFolder(resource);
		if (root) {
			return vscode.Uri.file(path.join(root.uri.fsPath, href))
				.with({ scheme: 'vscode-resource' })
				.toString();
		}

		// Otherwise look relative to the markdown file
		return vscode.Uri.file(path.join(path.dirname(resource.fsPath), href))
			.with({ scheme: 'vscode-resource' })
			.toString();
	}
function getEditorInfo(): { text: string; tooltip: string; color: string; } {
    const editor = window.activeTextEditor;

    // If no workspace is opened or just a single folder, we return without any status label
    // because our extension only works when more than one folder is opened in a workspace.
    if (!editor || !workspace.workspaceFolders || workspace.workspaceFolders.length < 2) {
        return null;
    }

    let text: string;
    let tooltip: string;
    let color: string;

    // If we have a file:// resource we resolve the WorkspaceFolder this file is from and update
    // the status accordingly.
    const resource = editor.document.uri;
    if (resource.scheme === 'file') {
        const folder = workspace.getWorkspaceFolder(resource);
        if (!folder) {
            text = `$(alert) <outside workspace> → ${basename(resource.fsPath)}`;
        } else {
            text = `$(file-submodule) ${basename(folder.uri.fsPath)} (${folder.index + 1} of ${workspace.workspaceFolders.length}) → $(file-code) ${basename(resource.fsPath)}`;
            tooltip = resource.fsPath;

            const multiRootConfigForResource = workspace.getConfiguration('multiRootSample', resource);
            color = multiRootConfigForResource.get('statusColor');
        }
    }

    return { text, tooltip, color };
}
Example #10
0
	private fixHref(resource: vscode.Uri, href: string): string {
		if (!href) {
			return href;
		}

		if (href.startsWith('http:') || href.startsWith('https:') || href.startsWith('file:')) {
			return href;
		}

		// Assume it must be a local file
		if (path.isAbsolute(href)) {
			return vscode.Uri.file(href)
				.with({ scheme: 'vscode-resource' })
				.toString();
		}

		// Use a workspace relative path if there is a workspace
		const root = vscode.workspace.getWorkspaceFolder(resource);
		if (root) {
			return vscode.Uri.file(path.join(root.uri.fsPath, href))
				.with({ scheme: 'vscode-resource' })
				.toString();
		}

		// Otherwise look relative to the markdown file
		return vscode.Uri.file(path.join(path.dirname(resource.fsPath), href))
			.with({ scheme: 'vscode-resource' })
			.toString();
	}
Example #11
0
function normalizeResourceUri(uri: Uri | null | undefined): Uri | null {
    if (uri) {
        const folder = workspace.getWorkspaceFolder(uri);
        return folder && folder.uri || null;
    }
    return null;
}
Example #12
0
		md.normalizeLink = (link: string) => {
			try {
				let uri = vscode.Uri.parse(link);
				if (!uri.scheme && uri.path) {
					// Assume it must be a file
					const fragment = uri.fragment;
					if (uri.path[0] === '/') {
						const root = vscode.workspace.getWorkspaceFolder(this.currentDocument!);
						if (root) {
							uri = vscode.Uri.file(path.join(root.uri.fsPath, uri.path));
						}
					} else {
						uri = vscode.Uri.file(path.join(path.dirname(this.currentDocument!.path), uri.path));
					}

					if (fragment) {
						uri = uri.with({
							fragment: Slug.fromHeading(fragment).value
						});
					}
					return normalizeLink(uri.with({ scheme: 'vscode-resource' }).toString(true));
				} else if (!uri.scheme && !uri.path && uri.fragment) {
					return normalizeLink(uri.with({
						fragment: Slug.fromHeading(uri.fragment).value
					}).toString(true));
				}
			} catch (e) {
				// noop
			}
			return normalizeLink(link);
		};
Example #13
0
async function provideNpmScriptsForFolder(packageJsonUri: Uri): Promise<Task[]> {
	let emptyTasks: Task[] = [];

	let folder = workspace.getWorkspaceFolder(packageJsonUri);
	if (!folder) {
		return emptyTasks;
	}
	let scripts = await getScripts(packageJsonUri);
	if (!scripts) {
		return emptyTasks;
	}

	const result: Task[] = [];
	Object.keys(scripts).filter(isNotPreOrPostScript).forEach(each => {
		const task = createTask(each, `run ${each}`, folder!, packageJsonUri);
		const lowerCaseTaskName = each.toLowerCase();
		if (isBuildTask(lowerCaseTaskName)) {
			task.group = TaskGroup.Build;
		} else if (isTestTask(lowerCaseTaskName)) {
			task.group = TaskGroup.Test;
		}
		result.push(task);
	});
	// always add npm install (without a problem matcher)
	result.push(createTask('install', 'install', folder, packageJsonUri, []));
	return result;
}
Example #14
0
	test('getWorkspaceFolder', () => {
		const folder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(join(__dirname, '../../testWorkspace2/far.js')));
		assert.ok(!!folder);

		if (folder) {
			assert.ok(pathEquals(folder.uri.fsPath, join(__dirname, '../../testWorkspace2')));
		}
	});
Example #15
0
export function runScript(script: string, document: TextDocument) {
	let uri = document.uri;
	let folder = workspace.getWorkspaceFolder(uri);
	if (folder) {
		let task = createTask(script, `run ${script}`, folder, uri);
		tasks.executeTask(task);
	}
}
Example #16
0
export function getTasksJsonPath(): string {
    const editor: vscode.TextEditor = vscode.window.activeTextEditor;
    const folder: vscode.WorkspaceFolder = vscode.workspace.getWorkspaceFolder(editor.document.uri);
    if (!folder) {
        return undefined;
    }
    return path.join(folder.uri.fsPath, ".vscode", "tasks.json");
}
Example #17
0
	public runScriptFromHover(args: any) {
		let script = args.script;
		let documentUri = args.documentUri;
		let folder = workspace.getWorkspaceFolder(documentUri);
		if (folder) {
			let task = createTask(script, `run ${script}`, folder, documentUri);
			tasks.executeTask(task);
		}
	}
    private async selectWorkspaceFolder(): Promise<WorkspaceFolder | undefined> {
        if (workspace.workspaceFolders.length === 1) {
            return workspace.workspaceFolders[0];
        }

        const sourcePath = await this.getSourcePath();
        const uri = Uri.file(sourcePath);
        return workspace.getWorkspaceFolder(uri) || window.showWorkspaceFolderPick();
    }
export function getWorkspaceRootPath(): string {
    const document = getCurrentTextDocument();
    if (document) {
        let fileUri = document.uri;
        let workspaceFolder = workspace.getWorkspaceFolder(fileUri);
        if (workspaceFolder) {
            return workspaceFolder.uri.toString();
        }
    }
}
Example #20
0
        client.onRequest(NoSassLintLibraryRequest.type, (params) => {
            const uri: Uri = Uri.parse(params.source.uri);

            const workspaceFolder = workspace.getWorkspaceFolder(uri);
            const packageManager = workspace.getConfiguration("sasslint", uri).get("packageManager", "npm");

            client.info(getInstallFailureMessage(uri, workspaceFolder, packageManager));

            return {};
        });
Example #21
0
export function isInsideFlutterProject(uri?: Uri): boolean {
	if (!uri)
		return false;

	const projectRoot = locateBestProjectRoot(fsPath(uri));
	if (projectRoot)
		return isFlutterProjectFolder(projectRoot);
	else
		return isFlutterWorkspaceFolder(workspace.getWorkspaceFolder(uri));
}
Example #22
0
	public debugScriptFromHover(args: any) {
		let script = args.script;
		let documentUri = args.documentUri;
		let protocol = args.protocol;
		let port = args.port;
		let folder = workspace.getWorkspaceFolder(documentUri);
		if (folder) {
			startDebugging(script, protocol, port, folder);
		}
	}
	function didOpenTextDocument(document: TextDocument): void {
		// We are only interested in language mode text
		if (document.languageId !== 'plaintext' || (document.uri.scheme !== 'file' && document.uri.scheme !== 'untitled')) {
			return;
		}

		let uri = document.uri;
		// Untitled files go to a default client.
		if (uri.scheme === 'untitled' && !defaultClient) {
			let debugOptions = { execArgv: ["--nolazy", "--inspect=6010"] };
			let serverOptions = {
				run: { module, transport: TransportKind.ipc },
				debug: { module, transport: TransportKind.ipc, options: debugOptions}
			};
			let clientOptions: LanguageClientOptions = {
				documentSelector: [
					{ scheme: 'untitled', language: 'plaintext' }
				],
				diagnosticCollectionName: 'lsp-multi-server-example',
				outputChannel: outputChannel
			}
			defaultClient = new LanguageClient('lsp-multi-server-example', 'LSP Multi Server Example', serverOptions, clientOptions);
			defaultClient.start();
			return;
		}
		let folder = Workspace.getWorkspaceFolder(uri);
		// Files outside a folder can't be handled. This might depend on the language.
		// Single file languages like JSON might handle files outside the workspace folders.
		if (!folder) {
			return;
		}
		// If we have nested workspace folders we only start a server on the outer most workspace folder.
		folder = getOuterMostWorkspaceFolder(folder);

		if (!clients.has(folder.uri.toString())) {
			let debugOptions = { execArgv: ["--nolazy", `--inspect=${6011 + clients.size}`] };
			let serverOptions = {
				run: { module, transport: TransportKind.ipc },
				debug: { module, transport: TransportKind.ipc, options: debugOptions}
			};
			let clientOptions: LanguageClientOptions = {
				documentSelector: [
					{ scheme: 'file', language: 'plaintext', pattern: `${folder.uri.fsPath}/**/*` }
				],
				diagnosticCollectionName: 'lsp-multi-server-example',
				workspaceFolder: folder,
				outputChannel: outputChannel
			}
			let client = new LanguageClient('lsp-multi-server-example', 'LSP Multi Server Example', serverOptions, clientOptions);
			client.start();
			clients.set(folder.uri.toString(), client);
		}
	}
function getConfigForFile(document: vscode.TextDocument, config: object | string): Promise<{}> {
	const workspaceFolder = vscode.workspace.getWorkspaceFolder(document.uri);
	const filepath = document.uri.fsPath;

	// Use workspace directory or filepath of current file as workspace folder
	const workspace = workspaceFolder ? workspaceFolder.uri.fsPath : filepath;

	// Set current workspace
	configProfiler.setWorkspace(workspace);

	return configProfiler.getConfig(filepath, { settings: config });
}
			async (params: WorkspaceRubyEnvironmentParams): Promise<WorkspaceRubyEnvironmentResult> => {
				const environments: WorkspaceRubyEnvironmentResult = {};

				for (const uri of params.folders) {
					const workspaceFolder: WorkspaceFolder = workspace.getWorkspaceFolder(Uri.parse(uri));

					if (workspaceFolder && workspaceFolder.uri.fsPath) {
						environments[uri] = await loadEnv(workspaceFolder.uri.fsPath);
					}
				}

				return environments;
			}
Example #26
0
export function isInsideFolderNamed(file: string, folderName: string): boolean {
	if (!file)
		return false;

	const ws = workspace.getWorkspaceFolder(Uri.file(file));

	if (!ws)
		return false;

	const relPath = path.relative(fsPath(ws.uri), file).toLowerCase();

	return relPath === folderName || relPath.startsWith(`${folderName}${path.sep}`);
}
function getOuterMostWorkspaceFolder(folder: WorkspaceFolder): WorkspaceFolder {
	let sorted = sortedWorkspaceFolders();
	for (let element of sorted) {
		let uri = folder.uri.toString();
		if (uri.charAt(uri.length - 1) !== '/') {
			uri = uri + '/';
		}
		if (uri.startsWith(element)) {
			return Workspace.getWorkspaceFolder(Uri.parse(element));
		}
	}
	return folder;
}
Example #28
0
	public async getConfigsForWorkspace(): Promise<Iterable<TSConfig>> {
		if (!vscode.workspace.workspaceFolders) {
			return [];
		}
		const configs = new Map<string, TSConfig>();
		for (const config of await vscode.workspace.findFiles('**/tsconfig*.json', '**/node_modules/**')) {
			const root = vscode.workspace.getWorkspaceFolder(config);
			if (root) {
				configs.set(config.fsPath, {
					path: config.fsPath,
					workspaceFolder: root
				});
			}
		}
		return configs.values();
	}
Example #29
0
 public async loadConfig(
   configFile: string | undefined,
   resource: vscode.Uri
 ): Promise<IArgdownRequest> {
   if (!configFile) {
     return {};
   }
   const workspaceFolder = vscode.workspace.getWorkspaceFolder(resource);
   let configPath = configFile;
   if (workspaceFolder) {
     let rootPath = workspaceFolder.uri.fsPath;
     configPath = path.resolve(rootPath, configFile);
   } else if (!path.isAbsolute(configPath)) {
     return {};
   }
   return await argdown.loadConfig(configPath);
 }
function findReadme(moduleName : string, textEditor ?: vscode.TextEditor) {
    textEditor = textEditor || vscode.window.activeTextEditor

    if (!textEditor.document) {
        throw new Error('No open document')
    }

    const workspaceFolder = vscode.workspace.getWorkspaceFolder(textEditor.document.uri)
    let readmeLocation = vscode.Uri.parse(`https://npmjs.org/package/${moduleName}`)

    if (workspaceFolder) {
        const fsLocation = workspaceFolder.uri.with({path: path.join(workspaceFolder.uri.fsPath, "node_modules", moduleName, "README.md")})

        if (fs.existsSync(fsLocation.fsPath)) {
            readmeLocation = fsLocation.with({
                scheme: 'file'
            })
        }
    }

    // see if we have an override for it
    const overrides = vscode.workspace.getConfiguration(overrideConfigurationSection)

    if (overrides[moduleName]) {
        // if we do, use that
        readmeLocation = vscode.Uri.parse(overrides[moduleName])
    }

    // map schemes to our scheme types
    if (readmeLocation.scheme === 'file') {
        readmeLocation = readmeLocation.with({
            scheme: LocalProvider.SchemaType
        })
    } else if (readmeLocation.authority === 'npmjs.org') {
        readmeLocation = readmeLocation.with({
            scheme: NpmProvider.SchemaType
        })
    } else {
        readmeLocation = readmeLocation.with({
            scheme: RemoteProvider.SchemaType,
            fragment: `${readmeLocation.scheme}.${readmeLocation.fragment}`
        })
    }

    return vscode.commands.executeCommand('markdown.showPreviewToSide', ReadmeUri.from(readmeLocation, moduleName).toEncodedUri())
}