All files / providers resource-reference-provider.ts

100% Statements 21/21
100% Branches 12/12
100% Functions 4/4
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71              63x     6x   6x 2x     4x   4x 2x   2x                       5x   5x     6x 5x       5x                 8x   8x     10x 3x     7x 6x   6x       8x    
import * as vscode from 'vscode';
import { IDocumentContextService } from '@src/services/document';
 
/**
 * A provider that retrieves the locations of resource references in a document.
 */
export class ResourceReferenceProvider implements vscode.ReferenceProvider {
	constructor(private readonly _contextService: IDocumentContextService) { }
 
	provideReferences(document: vscode.TextDocument, position: vscode.Position): vscode.ProviderResult<vscode.Location[]> {
		const context = this._contextService.contexts[document.uri.toString()];
 
		if (!context) {
			return null;
		}
 
		const iri = context.getIriAtPosition(position);
 
		if (iri) {
			return this.provideReferencesForIri(iri);
		} else {
			return null;
		}
	}
 
	/**
	 * Counts the references to a given resource across all indexed documents
	 * without allocating `Location` objects — use this when only the number is
	 * needed (e.g. the usage CodeLens), not the locations.
	 * @param iri The IRI of the resource.
	 * @returns The number of references.
	 */
	countReferencesForIri(iri: string): number {
		let count = 0;
 
		for (const context of Object.values(this._contextService.contexts)) {
			// Do not count references in temporary, non-persisted git diff views or other in-memory documents,
			// nor in the sources of the preset graphs, which are not part of the workspace.
			if (!context.isTemporary && !context.isPreset) {
				count += context.references.count(iri);
			}
		}
 
		return count;
	}
 
	/**
	 * Get the locations of references for a given resource.
	 * @param iri The IRI of the resource.
	 * @returns The locations of the references.
	 */
	provideReferencesForIri(iri: string): vscode.Location[] {
		let result: vscode.Location[] = [];
 
		for (const context of Object.values(this._contextService.contexts)) {
			// Do not provide references for temporary, non-persisted git diff views or other in-memory documents,
			// nor for the sources of the preset graphs, which are not part of the workspace.
			if (context.isTemporary || context.isPreset) {
				continue;
			}
 
			for (const range of context.references.getRanges(iri)) {
				const r = new vscode.Range(range.start.line, range.start.character, range.end.line, range.end.character);
 
				result.push(new vscode.Location(context.uri, r));
			}
		}
 
		return result;
	}
}