vscode#Uri TypeScript Examples
The following examples show how to use
vscode#Uri.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From dendron with GNU Affero General Public License v3.0 | 7 votes |
export async function showDocAndHidePicker(
uris: Uri[],
picker: DendronQuickPickerV2
) {
const ctx = "showDocAndHidePicker";
const maybeSplitSelection = _.find(picker.buttons, (ent: DendronBtn) => {
return getButtonCategory(ent) === "split" && ent.pressed;
});
let viewColumn = ViewColumn.Active;
if (maybeSplitSelection) {
const splitType = (maybeSplitSelection as DendronBtn).type;
if (splitType === "horizontal") {
viewColumn = ViewColumn.Beside;
} else {
// TODO: close current button
// await commands.executeCommand("workbench.action.splitEditorDown");
}
}
await Promise.all(
uris.map(async (uri) => {
return window.showTextDocument(uri, { viewColumn }).then(
() => {
Logger.info({ ctx, msg: "showTextDocument", fsPath: uri.fsPath });
picker.hide();
return;
},
(err) => {
Logger.error({ ctx, error: err, msg: "exit" });
throw err;
}
);
})
);
return uris;
}
Example #2
Source File: webview-utils.ts From plugin-vscode with Apache License 2.0 | 7 votes |
export function getCommonWebViewOptions(): Partial<WebviewOptions & WebviewPanelOptions> {
return {
enableScripts: true,
retainContextWhenHidden: true,
localResourceRoots: [
Uri.file(join((ballerinaExtInstance.context as ExtensionContext).extensionPath, 'resources', 'jslibs')),
Uri.file(getWebViewResourceRoot()),
Uri.file(getNodeModulesRoot())
],
};
}
Example #3
Source File: ALLangServerProxy.ts From vscode-alxmldocumentation with MIT License | 6 votes |
/**
* Retrieve first launch configuration to retrieve symbols from.
*/
async GetFirstLaunchConfiguration() : Promise<any|undefined> {
if ((!workspace.workspaceFolders) || (workspace.workspaceFolders.length === 0)) {
return undefined;
}
let launchFilePath = path.join(workspace.workspaceFolders[0].uri.fsPath, '.vscode/launch.json');
let config = workspace.getConfiguration('launch', Uri.file(launchFilePath));
let allConfigList : any[] | undefined = config.get('configurations');
if (!allConfigList) {
return undefined;
}
let configList = allConfigList.filter(p => p.type === 'al');
if ((!configList) || (configList.length === 0)) {
return undefined;
}
if (configList.length > 0) {
return configList[0];
}
return undefined;
}
Example #4
Source File: dafnyInstallation.ts From ide-vscode with MIT License | 6 votes |
private async extractArchive(archivePath: Uri): Promise<void> {
const dirPath = this.getInstallationPath();
this.writeStatus(`extracting Dafny to ${dirPath.fsPath}`);
const progressReporter = new ProgressReporter(this.statusOutput);
await extract(
archivePath.fsPath,
{
dir: dirPath.fsPath,
onEntry: (_, archive) => progressReporter.update(archive.entriesRead / archive.entryCount)
}
);
}
Example #5
Source File: ALObjectDocumentationExport.ts From vscode-alxmldocumentation with MIT License | 6 votes |
/**
* Read app.json file from workspace.
* @returns app.json
*/
private static ReadAppJson(): any {
let appJsonPath : Uri | null = Configuration.GetWorkspaceRootFolder();
if (appJsonPath === null) {
this.WriteOutput('Unable to determine current workspace. Please report this issue to https://github.com/365businessdev/vscode-alxmldocumentation/issues/ for further investigation.');
throw new Error('Unable to determine current workspace.');
}
if (!fs.existsSync(path.join(appJsonPath.fsPath, 'app.json'))) {
this.WriteOutput('Unable to find app.json for current workspace. Please report this issue to https://github.com/365businessdev/vscode-alxmldocumentation/issues/ for further investigation.');
throw new Error('Unable to find app.json for current workspace.');
}
return ALAppJsonReader.ReadManifest(path.join(appJsonPath.fsPath, 'app.json'));
}
Example #6
Source File: plugin.ts From vs-code-conan with MIT License | 6 votes |
private getWorkspaceUri(): Uri{
if (workspace.workspaceFolders !== undefined) {
if (workspace.workspaceFolders.length === 1) {
return workspace.workspaceFolders[0].uri;
}
else {
throw new Error("Multiple workspaces are not supported");
}
}
throw new Error("No workspace folders");
}
Example #7
Source File: Configuration.ts From vscode-alxmldocumentation with MIT License | 6 votes |
/**
* Return Documentation Export Path, if specified
* @returns Documentation Export Path
*/
public static DocumentationExportPath(): string {
var path = require('path');
var documentationPath = this.GetConfigurationValue('DocumentationExportPath');
let workspaceRoot : Uri | null = this.GetWorkspaceRootFolder();
if (workspaceRoot === null) {
window.showErrorMessage('Please setup \'DocumentationExportPath\' in workspace settings to define the export directory.');
return '';
}
if (documentationPath === undefined || documentationPath === null || documentationPath === '') {
// fallback scenario
documentationPath = path.join(workspaceRoot.fsPath, 'doc');
} else {
if ((documentationPath.includes('${workspaceFolder}')) && (workspace.workspaceFolders)) {
documentationPath = documentationPath.replace('${workspaceFolder}', path.dirname(workspace.workspaceFolders[0].uri.fsPath));
} else {
documentationPath = path.join(workspaceRoot.fsPath, documentationPath);
}
}
return documentationPath;
}
Example #8
Source File: dafnyLanguageClient.ts From ide-vscode with MIT License | 6 votes |
public static async create(context: ExtensionContext, statusOutput: OutputChannel): Promise<DafnyLanguageClient> {
const { path: dotnetExecutable } = await getDotnetExecutablePath();
const launchArguments = [ getLanguageServerRuntimePath(context), ...getLanguageServerLaunchArgs() ];
statusOutput.appendLine(`Language server arguments: ${DafnyLanguageClient.argumentsToCommandLine(launchArguments)}`);
const serverOptions: ServerOptions = {
run: { command: dotnetExecutable, args: launchArguments },
debug: { command: dotnetExecutable, args: launchArguments }
};
const diagnosticsListeners: ((uri: Uri, diagnostics: Diagnostic[]) => void)[] = [];
const clientOptions: LanguageClientOptions = {
documentSelector: [ DafnyDocumentFilter ],
diagnosticCollectionName: LanguageServerId,
middleware: {
handleDiagnostics: (uri: Uri, diagnostics: Diagnostic[], next: HandleDiagnosticsSignature) => {
for(const handler of diagnosticsListeners) {
handler(uri, diagnostics);
}
next(uri, diagnostics);
}
}
};
return new DafnyLanguageClient(LanguageServerId, LanguageServerName, serverOptions, clientOptions, diagnosticsListeners);
}
Example #9
Source File: workspace.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
/**
* Workspace settings file
*/
static workspaceFile(): vscode.Uri {
if (!vscode.workspace.workspaceFile) {
throw Error("no workspace file");
}
return vscode.workspace.workspaceFile;
}
Example #10
Source File: Configuration.ts From vscode-alxmldocumentation with MIT License | 6 votes |
/**
* Returns DiagnosticSeverity for objects as configured.
* @param fileUri
*/
public static GetObjectDocumentationCheckInformationLevel(fileUri: Uri | undefined = undefined): DiagnosticSeverity {
switch (this.GetConfigurationValue('CheckObjectDocumentationInformationLevel', fileUri)) {
case 'Information':
return DiagnosticSeverity.Information;
case 'Warning':
return DiagnosticSeverity.Warning;
case 'Error':
return DiagnosticSeverity.Error;
}
return DiagnosticSeverity.Information;
}
Example #11
Source File: startupCheck.ts From ide-vscode with MIT License | 6 votes |
async function checkDotnetInstallation(): Promise<boolean> {
const answer = await checkSupportedDotnetVersion();
if(answer !== undefined) {
const selection = await window.showErrorMessage(
answer,
Messages.Dotnet.ChangeConfiguration,
Messages.Dotnet.VisitDownload
);
switch(selection) {
case Messages.Dotnet.ChangeConfiguration:
commands.executeCommand(VSCodeCommands.ConfigureLanguageSettings);
break;
case Messages.Dotnet.VisitDownload:
commands.executeCommand(VSCodeCommands.Open, Uri.parse(Messages.Dotnet.DownloadUri));
break;
}
return false;
}
return true;
}
Example #12
Source File: Configuration.ts From vscode-alxmldocumentation with MIT License | 6 votes |
/**
* Returns DiagnosticSeverity for procedures as configured.
* @param fileUri
*/
public static GetProcedureDocumentationCheckInformationLevel(fileUri: Uri | undefined = undefined): DiagnosticSeverity {
switch (this.GetConfigurationValue('CheckProcedureDocumentationInformationLevel', fileUri)) {
case 'Information':
return DiagnosticSeverity.Information;
case 'Warning':
return DiagnosticSeverity.Warning;
case 'Error':
return DiagnosticSeverity.Error;
}
return DiagnosticSeverity.Information;
}
Example #13
Source File: webview.ts From vscode-code-review with MIT License | 6 votes |
getWebviewContent(fileName: string): string {
let selectListString = this.categories.reduce((current, category) => {
return current + `<option value="${category}">${category}</option>`;
}, '');
const uri = Uri.joinPath(this.context.extensionUri, 'dist', 'webview.html');
const pathUri = uri.with({ scheme: 'vscode-resource' });
return fs
.readFileSync(pathUri.fsPath, 'utf8')
.replace('SELECT_LIST_STRING', selectListString)
.replace('FILENAME', path.basename(fileName));
}
Example #14
Source File: testUtilsv2.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
stubWorkspaceFolders = (wsRoot: string, vaults: DVault[]) => {
const folders = vaults
.map((v) => ({
name: VaultUtils.getName(v),
index: 1,
uri: Uri.file(path.join(wsRoot, VaultUtils.getRelPath(v))),
}))
.concat([
{
name: "root",
index: 0,
uri: Uri.parse(wsRoot),
},
]);
sinon.stub(workspace, "workspaceFolders").value(folders);
DendronExtension.workspaceFolders = () => folders;
}
Example #15
Source File: driveFileSystemProvider.ts From google-drive-vscode with MIT License | 6 votes |
stat(uri: Uri): FileStat | Thenable<FileStat> {
return new Promise((resolve, reject) => {
const fileId = uri.fragment;
const driveFile = this.model.getDriveFile(fileId);
if (driveFile) {
const fileStat = this.buildFileStat(driveFile);
resolve(fileStat);
} else {
reject('File not found');
}
});
}
Example #16
Source File: testUtilsv2.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
/**
* Used for setup workspace test
*/
export async function setupCodeWorkspaceV3(
opts: SetupCodeWorkspaceMultiVaultV2Opts
) {
const copts = _.defaults(opts, {
setupWsOverride: {
skipConfirmation: true,
emptyWs: true,
},
preSetupHook: async () => {},
postSetupHook: async () => {},
});
const wsContainer = tmpDir().name;
// .code-workspace dendron settings
setupCodeConfiguration(opts);
const wsRoot = path.join(wsContainer, "dendron");
fs.ensureDirSync(wsRoot);
DendronExtension.workspaceFile = () => {
return Uri.file(path.join(wsRoot, "dendron.code-workspace"));
};
const workspaceFile = DendronExtension.workspaceFile();
const workspaceFolders = DendronExtension.workspaceFolders();
const vaults = await new SetupWorkspaceCommand().execute({
rootDirRaw: wsRoot,
skipOpenWs: true,
...copts.setupWsOverride,
});
DendronExtension.workspaceFolders = () => {
return vaults.map((v) => ({
name: v.name || path.basename(v.fsPath),
index: 1,
uri: Uri.file(v.fsPath),
}));
};
return { wsRoot, vaults, workspaceFile, workspaceFolders };
}
Example #17
Source File: driveFileSystemProvider.ts From google-drive-vscode with MIT License | 6 votes |
readFile(uri: Uri): Thenable<Uint8Array> {
return new Promise((resolve, reject) => {
const fileId = uri.fragment;
this.model.retrieveFileContentStream(fileId)
.then(contentStream => {
const byteArray: any[] = [];
contentStream.on('data', d => byteArray.push(d));
contentStream.on('end', () => {
const result = Buffer.concat(byteArray);
resolve(result);
});
}).catch(err => reject(err));
});
}
Example #18
Source File: export-factory.ts From vscode-code-review with MIT License | 6 votes |
/**
* generic export method
* @param format the format that's exported
*/
exportForFormat(format: ExportFormat, template?: Uri) {
const exporter = this.exportHandlerMap.get(format);
const outputFile = `${this.absoluteFilePath}.${exporter?.fileExtension}`;
exporter?.writeFileHeader(outputFile);
const data: CsvEntry[] = [];
parseFile(this.absoluteFilePath, { delimiter: ',', ignoreEmpty: true, headers: true })
.on('error', this.handleError)
.on('data', (comment: CsvEntry) => {
comment = CsvStructure.finalizeParse(comment);
if (this.isCommentEligible(comment)) {
if (this.includePrivateComments || comment.private === 0) {
if (exporter?.storeOutside) {
const tmp = exporter.handleData(outputFile, comment);
data.push(tmp);
}
exporter?.handleData(outputFile, comment);
}
}
})
.on('end', (_rows: number) => {
return exporter?.handleEnd(outputFile, exporter?.storeOutside ? data : [], template);
});
}
Example #19
Source File: relatedErrorView.ts From ide-vscode with MIT License | 6 votes |
public static createAndRegister(context: ExtensionContext, languageClient: DafnyLanguageClient): RelatedErrorView {
RelatedErrorView.instance = new RelatedErrorView();
context.subscriptions.push(
workspace.onDidCloseTextDocument(document => RelatedErrorView.instance.clearRelatedErrors(document.uri.toString())),
window.onDidChangeActiveTextEditor(editor => RelatedErrorView.instance.refreshRelatedErrors(editor)),
RelatedErrorView.instance
);
languageClient.onPublishDiagnostics((uri: Uri, diagnostics: Diagnostic[]) => {
RelatedErrorView.instance.updateRelatedErrors(uri, diagnostics);
});
return RelatedErrorView.instance;
}
Example #20
Source File: driveTreeDataProvider.ts From google-drive-vscode with MIT License | 6 votes |
private buildItemFromDriveFile(currentFile: DriveFile): TreeItem {
const iconUri = Uri.parse(currentFile.iconLink);
const collapsible = this.detectCollapsibleState(currentFile);
const contextValue = DriveFileUtils.extractTextFromType(currentFile.type);
return {
iconPath: iconUri,
label: currentFile.name,
collapsibleState: collapsible,
contextValue: contextValue
};
}
Example #21
Source File: NativeTreeView.test.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
async function runRenameNote(opts: { noteId: string; newName: string }) {
const engine = ExtensionProvider.getEngine();
const { wsRoot } = engine;
const { noteId, newName } = opts;
const noteToRename = engine.notes[noteId];
const noteToRenameVaultPath = vault2Path({
wsRoot,
vault: noteToRename.vault,
});
const rootUri = Uri.file(noteToRenameVaultPath);
const oldUri = getNoteUri({ note: noteToRename, wsRoot });
const newUri = VSCodeUtils.joinPath(rootUri, `${newName}.md`);
const renameCmd = new RenameNoteV2aCommand();
const renameOpts = {
files: [
{
oldUri,
newUri,
},
],
silent: true,
closeCurrentFile: false,
openNewFile: true,
noModifyWatcher: true,
};
await renameCmd.execute(renameOpts);
}
Example #22
Source File: relatedErrorView.ts From ide-vscode with MIT License | 6 votes |
public updateRelatedErrors(uri: Uri, diagnostics: Diagnostic[]): void {
const documentPath = getVsDocumentPath({ uri: uri.toString() });
const relatedErrorView: IRelatedErrorView = {
ranges: diagnostics.flatMap(diagnostic =>
diagnostic.relatedInformation == null || diagnostic.relatedInformation.length === 0
|| !diagnostic.message.startsWith('A postcondition might not hold')
? []
: [ diagnostic.relatedInformation[0].location.range ])
};
this.relatedViewByDocument.set(documentPath, relatedErrorView);
this.refreshRelatedErrors(window.activeTextEditor);
}
Example #23
Source File: export.service.ts From visualization with MIT License | 6 votes |
exportService = async (fileName: string, data: {
chart: string;
mermaid: string;
}, fileFormat: string) => {
const uri = await vscode.window.showSaveDialog({
defaultUri: Uri.file(fileName),
filters: {
fileFormat: [fileFormat],
}
});
if (uri) {
const path = uri.fsPath;
const onDone = (error: Error) => error ?
vscode.window.showErrorMessage(`Could not saved to file: ${path}, Error: ${error.message}`) :
vscode.window.showInformationMessage(`Chart successfully saved to file ${path}.`);
if (fileFormat === 'svg') {
fs.writeFile(path, data.chart, onDone);
}
if (fileFormat === 'md') {
fs.writeFile(path, data.mermaid, onDone);
}
if (fileFormat === 'pdf') {
saveToPdf(path, data.chart)
.then(() => onDone(null))
.catch((error) => onDone(error));
}
}
}
Example #24
Source File: BacklinksTreeDataProvider.test.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
async function checkNoteBacklinks({
wsRoot,
vaults,
noteWithTarget,
}: {
wsRoot: string;
vaults: DVault[];
noteWithTarget?: NoteProps;
}): Promise<boolean> {
expect(noteWithTarget).toBeTruthy();
await ExtensionProvider.getWSUtils().openNote(noteWithTarget!);
const { out } = await getRootChildrenBacklinksAsPlainObject();
const expectedPath = vscode.Uri.file(
path.join(wsRoot, vaults[0].fsPath, "gamma.md")
).path;
expect(out[0].command.arguments[0].path.toLowerCase() as string).toEqual(
expectedPath.toLowerCase()
);
const ref = out[0].refs[0];
expect(ref.isCandidate).toBeTruthy();
expect(ref.matchText as string).toEqual("alpha");
return true;
}
Example #25
Source File: config.ts From format-imports-vscode with MIT License | 6 votes |
export function resolveConfig(fileUri: Uri, languageId: string, eol: EndOfLine, force?: boolean) {
const log = logger('vscode.resolveConfig');
const { fsPath: fileName } = fileUri;
log.info('Resolving config for fileName:', fileName, 'languageId:', languageId);
const c = CACHE.get(fileName);
if (c && typeof c === 'object') {
log.debug('Resolved config in cache:', c);
return c as Configuration;
}
const { config: vscConfig, codeAction } = loadVscConfig(fileUri, languageId);
const c1 = mergeConfig(vscConfig, {
eol: eol === EndOfLine.CRLF ? 'CRLF' : 'LF',
force,
});
log.debug('Loaded codeAction:', codeAction, 'and VSCode config:', c1);
const c2 = resolveConfigForFile(fileName, c1);
const r = codeAction ? mergeConfig(c2, { autoFormat: 'off' }) : c2;
CACHE.set(fileName, r);
return r;
}
Example #26
Source File: logger.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
openFileInEditor = async (
fileItemOrURI: FileItem | vscode.Uri,
opts?: Partial<{
column: vscode.ViewColumn;
}>
): Promise<vscode.TextEditor | undefined> => {
let textDocument;
if (fileItemOrURI instanceof FileItem) {
if (fileItemOrURI.isDir) {
return;
}
textDocument = await vscode.workspace.openTextDocument(fileItemOrURI.path);
} else {
textDocument = await vscode.workspace.openTextDocument(fileItemOrURI);
}
if (!textDocument) {
throw new Error("Could not open file!");
}
const col = opts?.column || vscode.ViewColumn.Active;
const editor = await vscode.window.showTextDocument(textDocument, col);
if (!editor) {
throw new Error("Could not show document!");
}
return editor;
}
Example #27
Source File: utopia-fs.ts From utopia with MIT License | 6 votes |
// FileSearchProvider
async provideFileSearchResults(
query: FileSearchQuery,
options: FileSearchOptions,
_token: CancellationToken,
): Promise<Uri[]> {
// TODO Support all search options
const { result: foundPaths } = await this.filterFilePaths(query.pattern, options.maxResults)
return foundPaths.map((p) => toUtopiaURI(this.projectID, p))
}
Example #28
Source File: webview.ts From cloudmusic-vscode with MIT License | 6 votes |
private static _getPanel(title: string, type: WebviewType) {
const panel = window.createWebviewPanel(
"Cloudmusic",
title,
ViewColumn.One,
{ enableScripts: true, retainContextWhenHidden: true }
);
panel.iconPath = Uri.joinPath(this.extUri, "media", "icon.ico");
const css = panel.webview
.asWebviewUri(Uri.joinPath(this.extUri, "dist", "style.css"))
.toString();
const js = panel.webview
.asWebviewUri(Uri.joinPath(this.extUri, "dist", `${type}.js`))
.toString();
return {
panel,
setHtml: () => (panel.webview.html = this._layout(title, css, js)),
};
}
Example #29
Source File: utopia-fs.ts From utopia with MIT License | 6 votes |
async copy(source: Uri, destination: Uri, options: { overwrite: boolean }): Promise<void> {
// It's not clear where this will ever be called from, but it seems to be from the side bar
// that isn't available in Utopia, so this implementation is "just in case"
const sourcePath = fromUtopiaURI(source)
const destinationPath = fromUtopiaURI(destination)
const destinationParentDir = dirname(destinationPath)
const destinationParentDirExists = await exists(destinationParentDir)
if (!destinationParentDirExists) {
throw FileSystemError.FileNotFound(toUtopiaURI(this.projectID, destinationParentDir))
}
if (!options.overwrite) {
const destinationExists = await exists(destinationPath)
if (destinationExists && !options.overwrite) {
throw FileSystemError.FileExists(destination)
}
}
const { content, unsavedContent } = await readFile(sourcePath)
await writeFile(destinationPath, content, unsavedContent)
}