vscode-uri#URI TypeScript Examples
The following examples show how to use
vscode-uri#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 |
findUriByRef = (uris: URI[], ref: string): URI | undefined => {
return uris.find((uri) => {
// const relativeFsPath =
// path.sep + path.relative(getWorkspaceFolder()!.toLowerCase(), uri.fsPath.toLowerCase());
// if (containsImageExt(ref) || containsOtherKnownExts(ref) || containsUnknownExt(ref)) {
// if (isLongRef(ref)) {
// return normalizeSlashes(relativeFsPath).endsWith(ref.toLowerCase());
// }
// const basenameLowerCased = path.basename(uri.fsPath).toLowerCase();
// return (
// basenameLowerCased === ref.toLowerCase() || basenameLowerCased === `${ref.toLowerCase()}.md`
// );
// }
// if (isLongRef(ref)) {
// return normalizeSlashes(relativeFsPath).endsWith(`${ref.toLowerCase()}.md`);
// }
const name = path.parse(uri.fsPath).name.toLowerCase();
return (
containsMarkdownExt(path.basename(uri.fsPath)) &&
name === ref.toLowerCase()
);
});
}
Example #2
Source File: genutils.ts From svlangserver with MIT License | 7 votes |
export function uriToPath(uri: string): string {
try {
let fsPath: string = URI.parse(uri).fsPath;
try {
return fs.realpathSync(fsPath);
} catch(error) {
ConnectionLogger.error(error);
return fsPath;
}
} catch (error) {
ConnectionLogger.error(error);
return undefined;
}
}
Example #3
Source File: manifest-handling.ts From ui5-language-assistant with Apache License 2.0 | 6 votes |
export async function updateManifestData(
manifestUri: string,
changeType: FileChangeType
): Promise<void> {
getLogger().debug("`updateManifestData` function called", {
manifestUri,
changeType,
});
const manifestPath = URI.parse(manifestUri).fsPath;
switch (changeType) {
case 1: //created
case 2: {
//changed
const isFlexEnabled = await readFlexEnabledFlagFromManifestFile(
manifestUri
);
// Parsing of manifest.json failed because the file is invalid
// We want to keep last successfully read state - manifset.json file may be actively edited
if (isFlexEnabled !== "INVALID") {
manifestData[manifestPath] = { flexEnabled: isFlexEnabled };
}
return;
}
case 3: //deleted
delete manifestData[manifestPath];
return;
}
}
Example #4
Source File: spFileHandlers.ts From sourcepawn-vscode with MIT License | 6 votes |
/**
* Recursively read the unparsed includes from a array of Include objects.
* @param {ItemsRepository} itemsRepo The itemsRepository object constructed in the activation event.
* @param {Include[]} includes The array of Include objects to parse.
* @returns void
*/
function readUnscannedImports(
itemsRepo: ItemsRepository,
includes: Include[]
): void {
const debug = ["messages", "verbose"].includes(
Workspace.getConfiguration("sourcepawn").get("trace.server")
);
includes.forEach((include) => {
if (debug) console.log("reading", include.uri.toString());
const filePath = URI.parse(include.uri).fsPath;
if (itemsRepo.fileItems.has(include.uri) || !existsSync(filePath)) {
return;
}
if (debug) console.log("found", include.uri.toString());
let fileItems: FileItems = new FileItems(include.uri);
try {
parseFile(filePath, fileItems, itemsRepo, false, include.IsBuiltIn);
} catch (err) {
console.error(err, include.uri.toString());
}
if (debug) console.log("parsed", include.uri.toString());
itemsRepo.fileItems.set(include.uri, fileItems);
if (debug) console.log("added", include.uri.toString());
readUnscannedImports(itemsRepo, fileItems.includes);
});
}
Example #5
Source File: utils.ts From dendron with GNU Affero General Public License v3.0 | 6 votes |
getFileUrlForMarkdownPreview = (filePath: string): string =>
URI.file(filePath).toString().replace("file://", "")
Example #6
Source File: generator.ts From vs-code-conan with MIT License | 6 votes |
private createProfileJsonTemplate(profile: string, conanfile: URI):ProfileJson{
var parentDirectory=path.basename(path.dirname(conanfile.path));
if (parentDirectory === "") {
parentDirectory = "root";
}
var name = parentDirectory;
if(conanfile.path.endsWith("txt")){
name += `-txt`;
}
if (profile !== "default") {
name += `-${profile}`;
}
let conanfilePath = conanfile.path.replace(`${this.system.getWorkspaceRootPath()}`,"${workspaceFolder}");
return {
name: name,
conanFile: conanfilePath,
profile: profile,
installArg: "",
buildArg: "",
createUser: "disroop",
createChannel: "development",
createArg: ""
};
}
Example #7
Source File: fileProvider.ts From macro-executor with MIT License | 6 votes |
public get(file: string): MacroFileType | undefined {
let uri = this.resolveReference(file);
if (uri) {
let doc = getParsedDocument(this.documents, uri, (document => {
let parser = new Parser(this);
return parser.parseMacroFile(document);
}));
if (!doc) {
try {
const file = readFileSync(URI.parse(uri).fsPath, 'utf-8');
let document = TextDocument.create(uri!, 'macro', 1, file.toString());
try {
let macrofile = new Parser(this).parseMacroFile(document);
doc = {
macrofile: macrofile,
document: document,
version: 1
};
parsedDocuments.set(uri, doc);
}
catch (err){
this.connection?.console.log(err);
}
}
catch (err) {
this.connection?.console.log(err);
return undefined;
}
}
return doc;
}
return undefined;
}
Example #8
Source File: genutils.ts From svlangserver with MIT License | 6 votes |
export function pathToUri(path: string): string {
try {
return(URI.file(path).toString());
} catch (error) {
ConnectionLogger.error(error);
return undefined;
}
}
Example #9
Source File: lang-server.ts From vscode-q with MIT License | 6 votes |
private async onDidChangeWatchedFiles(change: DidChangeWatchedFilesParams) {
this.connection.console.info('Received file change event(s)');
const changedFiles: string[] = [];
change.changes.forEach(event => {
switch (event.type) {
case FileChangeType.Deleted:
this.connection.console.info(`Removing ${event.uri} from cache`);
this.analyzer.remove(event.uri);
break;
default:
changedFiles.push(event.uri);
}
});
changedFiles.forEach(file => {
const filepath = URI.parse(file).fsPath;
if (!Analyzer.matchFile(filepath))
return;
try {
this.analyzer.analyzeDoc(file, TextDocument.create(file, 'q', 1, fs.readFileSync(filepath, 'utf8')));
this.analyzer.analyzeLoadFiles(file);
} catch (error) {
this.connection.console.warn(`Cannot analyze ${file}`);
}
});
}
Example #10
Source File: DocumentsManager.ts From vscode-groovy-lint with GNU General Public License v3.0 | 6 votes |
// Set current workspace folder
async setCurrentWorkspaceFolder(textDocumentUri: string) {
const workspaceFolders: WorkspaceFolder[] = await this.connection.workspace.getWorkspaceFolders() || [];
const uriCompare = path.resolve(URI.parse(textDocumentUri).fsPath);
for (const wsFolder of workspaceFolders) {
if (uriCompare.includes(path.resolve(URI.parse(wsFolder.uri).fsPath))) {
this.currentWorkspaceFolder = path.resolve(URI.parse(wsFolder.uri).fsPath);
break;
}
}
}
Example #11
Source File: javascript.ts From coffeesense with MIT License | 6 votes |
function createUriMappingForEdits(changes: ts.FileTextChanges[], service: ts.LanguageService) {
const program = service.getProgram()!;
const result: Record<string, TextEdit[]> = {};
for (const { fileName, textChanges } of changes) {
const targetDoc = getSourceDoc(fileName, program);
const edits = textChanges.map(({ newText, span }) => ({
newText,
range: convertRange(targetDoc, span)
}));
const uri = URI.file(fileName).toString();
if (result[uri]) {
result[uri]!.push(...edits);
} else {
result[uri] = edits;
}
}
return result;
}
Example #12
Source File: graph.ts From lsif-node with MIT License | 6 votes |
public document(path: string, contents?: string): Document {
let result: Document = {
id: this.nextId(),
type: ElementTypes.vertex,
label: VertexLabels.document,
uri: URI.file(makeAbsolute(path)).toString(true),
languageId: 'typescript',
}
if (contents) {
result.contents = this.encodeString(contents)
}
return result
}
Example #13
Source File: FindFileReferencesProvider.ts From language-tools with MIT License | 6 votes |
async fileReferences(uri: string): Promise<Location[] | null> {
const u = URI.parse(uri);
const fileName = u.fsPath;
const lang = await this.getLSForPath(fileName);
const tsDoc = await this.getSnapshotForPath(fileName);
const fragment = tsDoc.getFragment();
const references = lang.getFileReferences(fileName);
if (!references) {
return null;
}
const docs = new SnapshotFragmentMap(this.lsAndTsDocResolver);
docs.set(tsDoc.filePath, { fragment, snapshot: tsDoc });
const locations = await Promise.all(
references.map(async (ref) => {
const defDoc = await docs.retrieveFragment(ref.fileName);
return Location.create(
pathToUrl(ref.fileName),
convertToLocationRange(defDoc, ref.textSpan)
);
})
);
// Some references are in generated code but not wrapped with explicit ignore comments.
// These show up as zero-length ranges, so filter them out.
return locations.filter(hasNonZeroRange);
}
Example #14
Source File: protocol.ts From vscode-css-variables with MIT License | 6 votes |
/**
* Normalizes the file system path.
*
* On systems other than Windows it should be an no-op.
*
* On Windows, an input path in a format like "C:/path/file.ts"
* will be normalized to "c:/path/file.ts".
*/
export function normalizePath(filePath: string): string {
const fsPath = URI.file(filePath).fsPath;
return normalizeFsPath(fsPath);
}
Example #15
Source File: server.ts From ui5-language-assistant with Apache License 2.0 | 5 votes |
connection.onInitialize((params: InitializeParams) => {
getLogger().info("`onInitialize` event", params);
if (params?.initializationOptions?.logLevel) {
setLogLevel(params?.initializationOptions?.logLevel);
}
initSwa(params);
const capabilities = params.capabilities;
const workspaceFolderUri = params.rootUri;
if (workspaceFolderUri !== null) {
const workspaceFolderAbsPath = URI.parse(workspaceFolderUri).fsPath;
manifestStateInitialized = initializeManifestData(workspaceFolderAbsPath);
}
// Does the client support the `workspace/configuration` request?
// If not, we will fall back using global settings
hasConfigurationCapability =
capabilities.workspace !== undefined &&
(capabilities.workspace.configuration ?? false);
// These options are passed from the client extension in clientOptions.initializationOptions
initializationOptions = params.initializationOptions;
return {
capabilities: {
textDocumentSync: TextDocumentSyncKind.Full,
completionProvider: {
resolveProvider: true,
// TODO: can the trigger characters be more contextual?
// e.g: "<" of open tag only, not else where
triggerCharacters: ['"', "'", ":", "<"],
},
hoverProvider: true,
codeActionProvider: true,
// Each command executes a different code action scenario
executeCommandProvider: {
commands: [
commands.QUICK_FIX_STABLE_ID_ERROR.name,
commands.QUICK_FIX_STABLE_ID_FILE_ERRORS.name,
],
},
},
};
});
Example #16
Source File: spDefineItem.ts From sourcepawn-vscode with MIT License | 5 votes |
toDefinitionItem(): LocationLink {
return {
targetRange: this.range,
targetUri: URI.file(this.filePath),
};
}
Example #17
Source File: dnode.ts From dendron with GNU Affero General Public License v3.0 | 5 votes |
static getURI({ note, wsRoot }: { note: NoteProps; wsRoot: string }): URI {
return URI.file(this.getFullPath({ note, wsRoot }));
}
Example #18
Source File: path.ts From volar with MIT License | 5 votes |
export function uriToFsPath(uri: DocumentUri) {
return upath.toUnix(URI.parse(uri).fsPath);
}
Example #19
Source File: analyser.ts From vscode-q with MIT License | 5 votes |
public constructor(parser: Parser, connection: Connection, workspaceFolder: string) {
this.parser = parser;
this.connection = connection;
this.workspaceFolder = URI.parse(workspaceFolder);
this.rootPath = this.workspaceFolder.fsPath;
this.reservedWord = buildInFs.map(item => item.label);
this.buildInFsSigSrc = buildInFsSigs;
}
Example #20
Source File: DocumentsManager.ts From vscode-groovy-lint with GNU General Public License v3.0 | 5 votes |
// Commands execution
async executeCommand(params: any) {
debug(`Request execute command ${JSON.stringify(params)}`);
// Set current document URI if sent as parameter
if (params.arguments && params.arguments[0] && URI.isUri(params.arguments[0])) {
this.setCurrentDocumentUri(params.arguments[0].toString());
}
// Command: Lint
if (params.command === COMMAND_LINT.command) {
const document: TextDocument = this.getDocumentFromUri(this.currentTextDocumentUri)!;
await this.validateTextDocument(document, { force: true });
}
// Command: Fix
else if (params.command === COMMAND_LINT_FIX.command) {
let document: TextDocument = this.getDocumentFromUri(this.currentTextDocumentUri)!;
await this.validateTextDocument(document, { fix: true });
setTimeout(() => { // Wait 500ms so we are more sure that the textDocument is already updated
// Then lint again
const newDoc = this.getUpToDateTextDocument(document);
this.validateTextDocument(newDoc, { force: true }); // After fix, lint again
}, 500);
}
// Command: Apply quick fix
else if (params.command === COMMAND_LINT_QUICKFIX.command) {
const [textDocumentUri, diagnostic] = params.arguments!;
await applyQuickFixes([diagnostic], textDocumentUri, this);
}
// Command: Apply quick fix in all file
else if (params.command === COMMAND_LINT_QUICKFIX_FILE.command) {
const [textDocumentUri, diagnostic] = params.arguments!;
await applyQuickFixesInFile([diagnostic], textDocumentUri, this);
}
// Ignore error
else if (params.command === COMMAND_DISABLE_ERROR_FOR_LINE.command) {
const [textDocumentUri, diagnostic] = params.arguments!;
await disableErrorWithComment(diagnostic, textDocumentUri, 'line', this);
}
// Ignore error in entire file
else if (params.command === COMMAND_DISABLE_ERROR_FOR_FILE.command) {
const [textDocumentUri, diagnostic] = params.arguments!;
await disableErrorWithComment(diagnostic, textDocumentUri, 'file', this);
}
// Command: Update .groovylintrc.json to ignore error in the future
else if (params.command === COMMAND_DISABLE_ERROR_FOR_PROJECT.command) {
const [textDocumentUri, diagnostic] = params.arguments!;
await disableErrorForProject(diagnostic, textDocumentUri, this);
}
// Show rule documentation
else if (params.command === COMMAND_SHOW_RULE_DOCUMENTATION.command) {
const [ruleCode] = params.arguments!;
await showRuleDocumentation(ruleCode, this);
}
// Command: Lint folder
else if (params.command === COMMAND_LINT_FOLDER.command) {
const folders: Array<any> = params.arguments[1];
await lintFolder(folders, this);
}
}
Example #21
Source File: lsp.ts From coffeesense with MIT License | 5 votes |
/**
* Custom Notifications
*/
openWebsite(url: string): void {
this.lspConnection.window.showDocument({ uri: URI.parse(url).toString(), external: true });
}
Example #22
Source File: index.ts From language-tools with MIT License | 5 votes |
private async updateDocument(path: string, isNew: boolean) {
const text = fs.readFileSync(path, 'utf-8');
await this.svelteCheck.upsertDocument({ text, uri: URI.file(path).toString() }, isNew);
this.scheduleDiagnostics();
}
Example #23
Source File: server.ts From vscode-teal with MIT License | 5 votes |
export function getDocumentUri(textDocument: TreeSitterDocument, pathToCheck: string): string {
if (path.basename(pathToCheck).startsWith(Teal.TmpBufferPrefix)) {
return textDocument.uri
}
return URI.file(pathToCheck).toString();
}
Example #24
Source File: protocol.ts From vscode-css-variables with MIT License | 5 votes |
export function uriToPath(stringUri: string): string | undefined {
const uri = URI.parse(stringUri);
if (uri.scheme !== 'file') {
return undefined;
}
return normalizeFsPath(uri.fsPath);
}
Example #25
Source File: compileSM.ts From sourcepawn-vscode with MIT License | 4 votes |
/**
* Callback for the Compile file command.
* @param {URI} args URI of the document to be compiled. This will be overrided if MainPathCompilation is set to true.
* @returns Promise
*/
export async function run(args: URI): Promise<void> {
const uri = args === undefined ? window.activeTextEditor.document.uri : args;
const workspaceFolder = Workspace.getWorkspaceFolder(uri);
const mainPath = findMainPath(uri);
const alwaysCompileMainPath: boolean = Workspace.getConfiguration(
"sourcepawn",
workspaceFolder
).get<boolean>("MainPathCompilation");
// Decide which file to compile here.
let fileToCompilePath: string;
if (alwaysCompileMainPath && mainPath !== undefined && mainPath !== "") {
fileToCompilePath = mainPath;
} else {
fileToCompilePath = uri.fsPath;
}
const scriptingFolderPath = dirname(fileToCompilePath);
// Don't compile if it's not a .sp file.
if (extname(fileToCompilePath) !== ".sp") {
window.showErrorMessage("Not a .sp file, aborting");
return;
}
// Invoke the compiler.
const spcomp =
Workspace.getConfiguration("sourcepawn", workspaceFolder).get<string>(
"SpcompPath"
) || "";
if (!spcomp) {
window
.showErrorMessage(
"SourceMod compiler not found in the project. You need to set the spCompPath setting to be able to compile a plugin.",
"Open Settings"
)
.then((choice) => {
if (choice === "Open Settings") {
commands.executeCommand(
"workbench.action.openSettings",
"@ext:sarrus.sourcepawn-vscode"
);
}
});
return;
}
// Decide where to output the compiled file.
const pluginsFolderPath = join(scriptingFolderPath, "../", "plugins/");
let outputDir: string =
Workspace.getConfiguration("sourcepawn", workspaceFolder).get(
"outputDirectoryPath"
) || pluginsFolderPath;
if (outputDir === pluginsFolderPath) {
if (!existsSync(outputDir)) {
mkdirSync(outputDir);
}
} else {
// If the outputDirectoryPath setting is not empty, make sure it exists before trying to write to it.
if (!existsSync(outputDir)) {
let workspaceFolder = Workspace.workspaceFolders[0];
outputDir = join(workspaceFolder.uri.fsPath, outputDir);
if (!existsSync(outputDir)) {
window
.showErrorMessage(
"The output directory does not exist.",
"Open Settings"
)
.then((choice) => {
if (choice === "Open Settings") {
commands.executeCommand(
"workbench.action.openSettings",
"@ext:sarrus.sourcepawn-vscode"
);
}
});
return;
}
}
}
outputDir += basename(fileToCompilePath, ".sp") + ".smx";
// Add the compiler options from the settings.
const compilerOptions: string[] = Workspace.getConfiguration(
"sourcepawn",
workspaceFolder
).get("compilerOptions");
let includePaths: string[] = [
Workspace.getConfiguration("sourcepawn", workspaceFolder).get(
"SourcemodHome"
),
join(scriptingFolderPath, "include"),
scriptingFolderPath,
];
// Add the optional includes folders.
getAllPossibleIncludeFolderPaths(
URI.file(fileToCompilePath),
true
).forEach((e) => includePaths.push(e));
let compilerArgs = [fileToCompilePath, `-o${outputDir}`];
// Add include paths and compiler options to compiler args.
includePaths.forEach((path) => compilerArgs.push(`-i${path}`));
compilerArgs = compilerArgs.concat(compilerOptions);
// Create Output Channel if it does not exist.
if (!output) {
output = window.createOutputChannel("SourcePawn Compiler");
}
// Clear previous data in Output Channel and show it.
output.clear();
output.show();
try {
// Compile in child process.
let command = spcomp + "\n";
compilerArgs.forEach((e) => {
command += e + " ";
if (e.length > 10) {
command += "\n";
}
});
output.appendLine(`${command}\n`);
execFile(spcomp, compilerArgs, async (error, stdout) => {
output.append(stdout.toString().trim());
parseSPCompErrors(stdout.toString().trim(), compilerDiagnostics);
if (
Workspace.getConfiguration("sourcepawn", workspaceFolder).get(
"uploadAfterSuccessfulCompile"
)
) {
await uploadToServerCommand(URI.file(fileToCompilePath));
}
if (
Workspace.getConfiguration("sourcepawn", workspaceFolder).get<string>(
"refreshServerPlugins"
) === "afterCompile"
) {
refreshPluginsCommand(undefined);
}
});
} catch (error) {
console.log(error);
}
}