All files / services/validation shacl-settings-sync-service.ts

86.9% Statements 73/84
72.41% Branches 42/58
93.75% Functions 15/16
86.58% Lines 71/82

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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246                                                  63x     63x 63x 63x 63x 63x                             6x   6x   6x 6x   6x   6x                                                                                       2x   2x 2x   2x   1x     1x   1x                       2x 1x     1x 1x     1x                               6x 6x   6x 6x   6x 5x 5x       6x 1x       5x 4x   5x 8x   8x 6x         5x 10x 4x     8x   6x       5x 5x 5x   5x 5x 5x   5x 1x     4x   4x 4x 2x   2x       4x 1x     1x       4x 4x     5x       5x 5x 1x   6x 4x     1x         1x 1x          
import * as vscode from 'vscode';
import { Store } from '@faubulous/mentor-rdf';
import { getConfig } from '@src/utilities/vscode/config';
import { toUniqueStringArray } from '@src/utilities/array';
import { getGlobPatternBase } from '@src/utilities/glob';
import { WorkspaceUri } from '@src/providers/workspace-uri';
import {
	findBrokenReferences,
	getAllReferencedShapeUris,
	migrateShaclValidationConfig,
	ShaclBrokenReferences,
	ShaclDocumentRename,
} from './shacl-validation-configuration';
import { ShaclProfileSettingsService } from './shacl-profile-settings-service';
 
/**
 * Keeps the `mentor.shacl.validation` settings in sync with the workspace:
 * follows file/folder renames and deletions in the profiles' shape references
 * and include/exclude entries, and runs the startup health check for broken
 * references.
 */
export class ShaclSettingsSyncService {
	/**
	 * Ensures the startup profile health check runs at most once per session.
	 */
	private _startupProfileCheckDone = false;
 
	constructor(
		private readonly _store: Store,
		private readonly _profileSettings: ShaclProfileSettingsService,
		private readonly _onHealthChecked?: (broken: ShaclBrokenReferences) => void,
		private readonly _ensureShapesLoaded?: (uris: string[]) => Promise<void>,
		private readonly _shapeSourceExists?: (uri: string) => boolean
	) { }
 
	/**
	 * Checks all validation profiles for broken references: shape graphs whose
	 * source is missing. A reference is broken only when neither the store holds
	 * the graph nor its backing shape file exists. An existing-but-empty shape
	 * file (no triples) is treated as valid — validating against it is a harmless
	 * no-op, and the profile picker offers such files, so flagging them would be
	 * inconsistent. Referenced workspace shape graphs are loaded on demand first,
	 * so the check does not depend on startup ordering. Every check also reports
	 * its outcome through the `onHealthChecked` callback, so the validation status
	 * bar item can surface (and clear) a configuration error.
	 */
	async checkShaclProfiles(): Promise<ShaclBrokenReferences> {
		const settings = this._profileSettings.getMergedSettings();
 
		await this._ensureShapesLoaded?.(getAllReferencedShapeUris(settings));
 
		const broken = findBrokenReferences(settings, uri =>
			this._store.hasGraph(uri) || (this._shapeSourceExists?.(uri) ?? false));
 
		this._onHealthChecked?.(broken);
 
		return broken;
	}
 
	/**
	 * Runs the startup health check once per session: if any profile references
	 * missing shape files, shows a warning with an action to open the validation
	 * settings.
	 */
	async runStartupProfileCheck(): Promise<void> {
		if (this._startupProfileCheckDone || !getConfig('shacl').get<boolean>('enabled', false)) {
			return;
		}
 
		this._startupProfileCheckDone = true;
 
		const broken = await this.checkShaclProfiles();
		const brokenProfiles = Object.keys(broken.profiles);
 
		if (brokenProfiles.length === 0) {
			return;
		}
 
		const action = await vscode.window.showWarningMessage(
			`Some SHACL validation profiles reference missing shape graphs. Affected profiles: ${brokenProfiles.join(', ')}`,
			'Manage Profiles'
		);
 
		if (action === 'Manage Profiles') {
			await vscode.commands.executeCommand('mentor.command.openSettings', 'validation.profiles');
		}
	}
 
	/**
	 * Migrates SHACL validation settings for renamed/moved files or folders.
	 *
	 * Shape entries in `mentor.shacl.validation` are canonical
	 * `workspace:///...` URIs while include/exclude entries are bare
	 * workspace-relative paths, so each rename carries both forms. Only renames
	 * for files whose old URI can be resolved to a workspace-relative URI are
	 * migrated. Profiles in both the user and the workspace scope are covered;
	 * user-scope entries belonging to other workspaces never match the renamed
	 * paths and stay untouched.
	 */
	async migrateShaclSettings(files: ReadonlyArray<{ oldUri: vscode.Uri; newUri: vscode.Uri }>): Promise<void> {
		const renames: ShaclDocumentRename[] = [];
 
		for (const { oldUri, newUri } of files) {
			const oldWorkspaceUri = WorkspaceUri.toWorkspaceUri(oldUri);
 
			if (!oldWorkspaceUri) {
				// File is outside the current workspace root — skip.
				continue;
			}
 
			const newWorkspaceUri = WorkspaceUri.toWorkspaceUri(newUri);
 
			renames.push({
				oldUri: WorkspaceUri.toCanonicalString(oldWorkspaceUri),
				newUri: newWorkspaceUri
					? WorkspaceUri.toCanonicalString(newWorkspaceUri)
					: newUri.toString(),
				oldPath: oldWorkspaceUri.relativePath,
				newPath: newWorkspaceUri
					? newWorkspaceUri.relativePath
					: newUri.toString(),
			});
		}
 
		if (renames.length === 0) {
			return;
		}
 
		await this._profileSettings.updateEachScope(current => {
			const migrated = migrateShaclValidationConfig(current, renames);
 
			// Only persist scopes the renames actually touched.
			return JSON.stringify(migrated) !== JSON.stringify(current) ? migrated : undefined;
		});
	}
 
	/**
	 * Handles file/folder deletions:
	 * - Prunes include/exclude entries whose literal path or fixed pattern prefix lies
	 *   inside a deleted path (they can never match anything again). Root-anchored
	 *   patterns are left untouched. Profiles in both the user and the workspace
	 *   scope are covered.
	 * - Warns — without modifying shape lists — when a deleted file is still
	 *   referenced as a shape file by a profile.
	 */
	async handleFileDeletes(files: ReadonlyArray<vscode.Uri>): Promise<void> {
		// Shape entries are canonical workspace:/// URIs, include/exclude entries are
		// bare relative paths — collect the deletions in both forms.
		const deletedUris: string[] = [];
		const deletedPaths: string[] = [];
 
		for (const uri of files) {
			const wsUri = WorkspaceUri.toWorkspaceUri(uri);
 
			if (wsUri) {
				deletedUris.push(WorkspaceUri.toCanonicalString(wsUri));
				deletedPaths.push(wsUri.relativePath);
			}
		}
 
		if (deletedPaths.length === 0) {
			return;
		}
 
		// Deletions may be folders; match by key or path prefix with boundary guards.
		const isDeletedUri = (uri: string) =>
			deletedUris.some(key => uri === key || uri.startsWith(key + '/'));
 
		const isDeletedPathEntry = (entry: string) => {
			const base = getGlobPatternBase(entry);
 
			return base.length > 0 && deletedPaths.some(path =>
				base === path || base.startsWith(path + '/') || base.startsWith(path + '#'));
		};
 
		// Prunes deleted entries from one of a profile's path arrays; returns the
		// kept entries when any were removed, or undefined when nothing changed.
		const pruneEntries = (entries: string[] | undefined): string[] | undefined => {
			if (!entries?.length) {
				return undefined;
			}
 
			const kept = entries.filter(entry => !isDeletedPathEntry(entry));
 
			return kept.length !== entries.length ? kept : undefined;
		};
 
		// Prune matching entries from the profiles of every scope that stores any.
		await this._profileSettings.updateEachScope(settings => {
			let changed = false;
			const profiles = { ...(settings.profiles ?? {}) };
 
			for (const [id, profile] of Object.entries(profiles)) {
				const keptInclude = pruneEntries(profile?.includeFiles);
				const keptExclude = pruneEntries(profile?.excludeFiles);
 
				if (!keptInclude && !keptExclude) {
					continue;
				}
 
				const next = { ...profile };
 
				Eif (keptInclude) {
					if (keptInclude.length > 0) {
						next.includeFiles = keptInclude;
					} else {
						delete next.includeFiles;
					}
				}
 
				if (keptExclude) {
					Iif (keptExclude.length > 0) {
						next.excludeFiles = keptExclude;
					} else {
						delete next.excludeFiles;
					}
				}
 
				profiles[id] = next;
				changed = true;
			}
 
			return changed ? { ...settings, profiles } : undefined;
		});
 
		// Warn about profiles that reference deleted shape files, across the merged view.
		const affectedProfiles = Object.entries(this._profileSettings.getMergedSettings().profiles ?? {})
			.filter(([, profile]) => toUniqueStringArray(profile?.shapes).some(isDeletedUri))
			.map(([id]) => id);
 
		if (affectedProfiles.length === 0) {
			return;
		}
 
		const action = await vscode.window.showWarningMessage(
			`Deleted files are still referenced as shape graphs by SHACL validation profiles. Affected profiles: ${affectedProfiles.join(', ')}`,
			'Manage Profiles'
		);
 
		Eif (action === 'Manage Profiles') {
			await vscode.commands.executeCommand('mentor.command.openSettings', 'validation.profiles');
		}
	}
 
}