Skip to main content

Mountain/ExtensionManagement/
Scanner.rs

1//! # Extension Scanner (ExtensionManagement)
2//!
3//! Contains the logic for scanning directories on the filesystem to discover
4//! installed extensions by reading their `package.json` manifests, and for
5//! collecting default configuration values from all discovered extensions.
6//!
7//! ## RESPONSIBILITIES
8//!
9//! ### 1. Extension Discovery
10//! - Scan registered extension paths for valid extensions
11//! - Read and parse `package.json` manifest files
12//! - Validate extension metadata and structure
13//! - Build `ExtensionDescriptionStateDTO` for each discovered extension
14//!
15//! ### 2. Configuration Collection
16//! - Extract default configuration values from extension
17//!   `contributes.configuration`
18//! - Merge configuration properties from all extensions
19//! - Handle nested configuration objects recursively
20//! - Detect and prevent circular references
21//!
22//! ### 3. Error Handling
23//! - Gracefully handle unreadable directories
24//! - Skip extensions with invalid package.json
25//! - Log warnings for partial scan failures
26//! - Continue scanning even when some paths fail
27//!
28//! ## ARCHITECTURAL ROLE
29//!
30//! The Extension Scanner is part of the **Extension Management** subsystem:
31//!
32//! ```text
33//! Startup ──► ScanPaths ──► Scanner ──► Extensions Map ──► ApplicationState
34//! ```
35//!
36//! ### Position in Mountain
37//! - `ExtensionManagement` module: Extension discovery and metadata
38//! - Used during application startup to populate extension registry
39//! - Provides data to `Cocoon` for extension host initialization
40//!
41//! ### Dependencies
42//! - `CommonLibrary::FileSystem`: ReadDirectory and ReadFile effects
43//! - `CommonLibrary::Error::CommonError`: Error handling
44//! - `ApplicationRunTime`: Effect execution
45//! - `ApplicationState`: Extension storage
46//!
47//! ### Dependents
48//! - `InitializationData::ConstructExtensionHostInitializationData`: Sends
49//!   extensions to Cocoon
50//! - `MountainEnvironment::ScanForExtensions`: Public API for extension
51//!   scanning
52//! - `ApplicationState::Internal::ScanExtensionsWithRecovery`: Robust scanning
53//!   wrapper
54//!
55//! ## SCANNING PROCESS
56//!
57//! 1. **Path Resolution**: Get scan paths from
58//!    `ApplicationState.Extension.Registry.ExtensionScanPaths`
59//! 2. **Directory Enumeration**: For each path, read directory entries
60//! 3. **Manifest Detection**: Look for `package.json` in each subdirectory
61//! 4. **Parsing**: Deserialize `package.json` into
62//!    `ExtensionDescriptionStateDTO`
63//! 5. **Augmentation**: Add `ExtensionLocation` (disk path) to metadata
64//! 6. **Storage**: Insert into `ApplicationState.Extension.ScannedExtensions`
65//!    map
66//!
67//! ## CONFIGURATION MERGING
68//!
69//! `CollectDefaultConfigurations()` extracts default values from all
70//! extensions' `contributes.configuration.properties` and merges them into a
71//! single JSON object:
72//!
73//! - Handles nested `.` notation (e.g., `editor.fontSize`)
74//! - Recursively processes nested `properties` objects
75//! - Detects circular references to prevent infinite loops
76//! - Returns a flat map of configuration keys to default values
77//!
78//! ## ERROR HANDLING
79//!
80//! - **Directory Read Failures**: Logged as warnings, scanning continues
81//! - **Invalid package.json**: Skipped with warning, scanning continues
82//! - **IO Errors**: Logged, operation continues or fails gracefully
83//!
84//! ## PERFORMANCE
85//!
86//! - Scans are performed asynchronously via `ApplicationRunTime`
87//! - Each directory read is a separate filesystem operation
88//! - Large extension directories may impact startup time
89//! - Consider caching scan results for development workflows
90//!
91//! ## VS CODE REFERENCE
92//!
93//! Borrowed from VS Code's extension management:
94//! - `vs/workbench/services/extensions/common/extensionPoints.ts` -
95//!   Configuration contribution
96//! - `vs/platform/extensionManagement/common/extensionManagementService.ts` -
97//!   Extension scanning
98//!
99//! ## TODO
100//!
101//! - [ ] Implement concurrent scanning for multiple paths
102//! - [ ] Add extension scan caching with invalidation
103//! - [ ] Implement extension validation rules (required fields, etc.)
104//! - [ ] Add scan progress reporting for UI feedback
105//! - [ ] Support extension scanning in subdirectories (recursive)
106//!
107//! ## MODULE CONTENTS
108//!
109//! - [`ScanDirectoryForExtensions`]: Scan a single directory for extensions
110//! - [`CollectDefaultConfigurations`]: Merge configuration defaults from all
111//!   extensions
112//! - `process_configuration_properties`: Recursive configuration property
113//! processor
114
115use std::{path::PathBuf, sync::Arc};
116
117use CommonLibrary::{
118	Effect::ApplicationRunTime::ApplicationRunTime as _,
119	Error::CommonError::CommonError,
120	FileSystem::{DTO::FileTypeDTO::FileTypeDTO, ReadDirectory::ReadDirectory, ReadFile::ReadFile},
121};
122use serde_json::{Map, Value};
123use tauri::Manager;
124
125use crate::{
126	ApplicationState::{
127		DTO::ExtensionDescriptionStateDTO::ExtensionDescriptionStateDTO,
128		State::ApplicationState::ApplicationState,
129	},
130	Environment::Utility,
131	RunTime::ApplicationRunTime::ApplicationRunTime,
132	dev_log,
133};
134
135/// Directory names that are never extensions themselves even though they
136/// sit at the top level of `extensions/`. VS Code's shipped tree keeps
137/// TypeScript type declarations in `types/`, build output in `out/`, and a
138/// flat `node_modules/` for shared dependencies. Scanning into those emits
139/// noise like `[ExtensionScanner] Could not read package.json at
140/// .../out/package.json` on every boot; callers use `ExtensionScanDenyList` to
141/// skip them without losing the ability to scan *nested* `node_modules` inside
142/// a real extension (e.g. a language server's bundled deps).
143const EXTENSION_SCAN_DENY_LIST:&[&str] = &["types", "out", "node_modules", "test", ".vscode-test", ".git"];
144
145/// Test-only extensions that only serve the upstream VS Code test harness.
146/// Excluded unless `Test=1` is set, because they
147/// pollute the registry with events nobody listens for and drag down boot
148/// time on every user session.
149const TEST_ONLY_EXTENSIONS:&[&str] = &[
150	"vscode-api-tests",
151	"vscode-test-resolver",
152	"vscode-colorize-tests",
153	"vscode-colorize-perf-tests",
154	"vscode-notebook-tests",
155];
156
157fn IncludeTestExtensions() -> bool { matches!(std::env::var("Test").as_deref(), Ok("1") | Ok("true")) }
158
159fn IsDeniedDirectory(Name:&str) -> bool { EXTENSION_SCAN_DENY_LIST.iter().any(|Denied| *Denied == Name) }
160
161fn IsTestOnlyExtension(Name:&str) -> bool { TEST_ONLY_EXTENSIONS.iter().any(|TestOnly| *TestOnly == Name) }
162
163/// Return `true` if the given scan path represents a user-writable extension
164/// directory (i.e. where `extensions:install` drops VSIX payloads), not a
165/// bundled "built-in" path that ships with the app.
166///
167/// VS Code's sidebar categorises installed extensions by `IsBuiltin`:
168/// `true` appears under **Built-in**, `false` under **Installed**
169/// (accessible via `@installed`). Previously this classifier was
170/// hardcoded to `true` for every scan path, so user-installed VSIXes
171/// showed up under Built-in and `@installed` was empty.
172///
173/// The canonical user extension root on macOS/Linux is `~/.land/extensions`
174/// (VS Code's equivalent is `~/.vscode/extensions`). We also honour a
175/// `Lodge` override in case callers remap it.
176///
177/// Everything else - the Mountain build's own `Resources/extensions`,
178/// Sky's `Static/Application/extensions`, the VS Code submodule's
179/// `Dependency/…/extensions` - is treated as built-in.
180fn IsUserExtensionScanPath(DirectoryPath:&std::path::Path) -> bool {
181	let Normalised = match DirectoryPath.canonicalize() {
182		Ok(Canonical) => Canonical,
183		Err(_) => DirectoryPath.to_path_buf(),
184	};
185
186	// `${Lodge}` explicit override takes priority.
187	if let Ok(Override) = std::env::var("Lodge") {
188		if !Override.is_empty() && Normalised == std::path::PathBuf::from(&Override) {
189			return true;
190		}
191	}
192
193	// `${HOME}/.land/extensions` is the default user-scope root - used by
194	// `VsixInstaller::InstallVsix` for local VSIX drops and by the scan
195	// path list in `ScanPathConfigure`.
196	if let Ok(Home) = std::env::var("HOME") {
197		let UserRoot = std::path::PathBuf::from(Home).join(".land/extensions");
198		if Normalised == UserRoot {
199			return true;
200		}
201	}
202
203	false
204}
205
206/// Scans a single directory for valid extensions.
207///
208/// This function iterates through a given directory, looking for subdirectories
209/// that contain a `package.json` file. It then attempts to parse this file
210/// into an `ExtensionDescriptionStateDTO`.
211pub async fn ScanDirectoryForExtensions(
212	ApplicationHandle:tauri::AppHandle,
213
214	DirectoryPath:PathBuf,
215) -> Result<Vec<ExtensionDescriptionStateDTO>, CommonError> {
216	// Decide up-front whether this scan path contributes built-ins or user
217	// extensions. Built-ins are ones shipped inside the Mountain/Sky/VS Code
218	// bundle; the `~/.land/extensions` root is user-space.
219	let IsUserPath = IsUserExtensionScanPath(&DirectoryPath);
220	let RunTime = ApplicationHandle.state::<Arc<ApplicationRunTime>>().inner().clone();
221
222	let mut FoundExtensions = Vec::new();
223
224	// Distinguish "directory does not exist" (first-run, no user extensions
225	// installed yet - perfectly normal) from a real I/O failure. Only the
226	// latter deserves a `warn:` prefix; the former is debug-level noise.
227	match DirectoryPath.try_exists() {
228		Ok(false) => {
229			dev_log!(
230				"extensions",
231				"[ExtensionScanner] Extension path '{}' does not exist, skipping (no extensions installed here)",
232				DirectoryPath.display()
233			);
234			return Ok(Vec::new());
235		},
236		Err(error) => {
237			dev_log!(
238				"extensions",
239				"[ExtensionScanner] Could not stat extension path '{}': {} - skipping",
240				DirectoryPath.display(),
241				error
242			);
243			return Ok(Vec::new());
244		},
245		Ok(true) => {},
246	}
247
248	let TopLevelEntries = match RunTime.Run(ReadDirectory(DirectoryPath.clone())).await {
249		Ok(entries) => entries,
250
251		Err(error) => {
252			dev_log!(
253				"extensions",
254				"warn: [ExtensionScanner] Could not read extension directory '{}': {}. Skipping.",
255				DirectoryPath.display(),
256				error
257			);
258
259			return Ok(Vec::new());
260		},
261	};
262
263	dev_log!(
264		"extensions",
265		"[ExtensionScanner] Directory '{}' contains {} top-level entries",
266		DirectoryPath.display(),
267		TopLevelEntries.len()
268	);
269
270	let mut parse_failures = 0usize;
271	let mut missing_package_json = 0usize;
272	let mut denied_directory_count = 0usize;
273	let mut test_extension_skips = 0usize;
274	let AllowTestExtensions = IncludeTestExtensions();
275
276	for (EntryName, FileType) in TopLevelEntries {
277		if FileType == FileTypeDTO::Directory {
278			// BATCH-18: skip scanner traversal into directories that are
279			// build output / shared deps, not extensions.
280			if IsDeniedDirectory(&EntryName) {
281				denied_directory_count += 1;
282				continue;
283			}
284			if !AllowTestExtensions && IsTestOnlyExtension(&EntryName) {
285				test_extension_skips += 1;
286				continue;
287			}
288			let PotentialExtensionPath = DirectoryPath.join(EntryName);
289
290			let PackageJsonPath = PotentialExtensionPath.join("package.json");
291
292			// Per-candidate-directory probe, fires for every top-level
293			// entry the scanner inspects (203 lines per session). The
294			// accepted / rejected disposition is already covered by the
295			// `ext-scan` tag below.
296			dev_log!(
297				"ext-scan-verbose",
298				"[ExtensionScanner] Checking for package.json in: {}",
299				PotentialExtensionPath.display()
300			);
301
302			match RunTime.Run(ReadFile(PackageJsonPath.clone())).await {
303				Ok(PackageJsonContent) => {
304					// Parse to a dynamic JSON value first so we can resolve
305					// VS Code NLS placeholders (`%key%` strings referencing
306					// `package.nls.json` entries) across every typed field.
307					// Without this the UI renders literal `%command.clone%`,
308					// `%displayName%`, etc. in the Command Palette and menus.
309					let mut ManifestValue:Value = match serde_json::from_slice::<Value>(&PackageJsonContent) {
310						Ok(v) => v,
311						Err(error) => {
312							parse_failures += 1;
313							dev_log!(
314								"extensions",
315								"warn: [ExtensionScanner] Failed to parse package.json at '{}': {}",
316								PotentialExtensionPath.display(),
317								error
318							);
319							continue;
320						},
321					};
322
323					// BATCH-18: only report "no bundle" when the manifest
324					// actually contains `%placeholder%` strings that need
325					// substitution. Many shipped extensions (js-debug-companion,
326					// js-profile-table) publish English-only manifests with no
327					// placeholders - surfacing a warning there is misleading
328					// because the UI renders correctly with the raw fields.
329					let ManifestUsesPlaceholders = ManifestContainsNLSPlaceholders(&ManifestValue);
330					if let Some(NLSMap) =
331						LoadNLSBundle(&RunTime, &PotentialExtensionPath, ManifestUsesPlaceholders).await
332					{
333						let mut Replaced = 0u32;
334						let mut Unresolved = 0u32;
335						ResolveNLSPlaceholdersInner(&mut ManifestValue, &NLSMap, &mut Replaced, &mut Unresolved);
336						dev_log!(
337							"nls",
338							"[LandFix:NLS] {} → {} replaced, {} unresolved placeholders",
339							PotentialExtensionPath.display(),
340							Replaced,
341							Unresolved
342						);
343					}
344
345					match serde_json::from_value::<ExtensionDescriptionStateDTO>(ManifestValue) {
346						Ok(mut Description) => {
347							// Augment the description with its location on disk.
348							Description.ExtensionLocation =
349								serde_json::to_value(url::Url::from_directory_path(&PotentialExtensionPath).unwrap())
350									.unwrap_or(Value::Null);
351
352							// Construct identifier from publisher.name if not set
353							if Description.Identifier == Value::Null
354								|| Description.Identifier == Value::Object(Default::default())
355							{
356								let Id = if Description.Publisher.is_empty() {
357									Description.Name.clone()
358								} else {
359									format!("{}.{}", Description.Publisher, Description.Name)
360								};
361								Description.Identifier = serde_json::json!({ "value": Id });
362							}
363
364							// Classify the extension by the scan path it came from.
365							// Built-in extensions ship in the Mountain/Sky/VS Code
366							// bundle; user extensions live under
367							// `~/.land/extensions` (written by
368							// `VsixInstaller::InstallVsix`). Hardcoding `true`
369							// here (the previous behaviour) made every VSIX
370							// install appear under **Built-in** in the
371							// Extensions sidebar and left `@installed` empty
372							// because the default query filters for User-scope
373							// extensions only.
374							Description.IsBuiltin = !IsUserPath;
375
376							// Boot-time exec-bit heal for user-scope extensions.
377							// Runs only against `~/.land/extensions/<id>/` (built-in
378							// trees ship with correct modes from the bundle). Walks
379							// `bin/`, `server/`, `tools/`, etc., promotes 0o644 →
380							// 0o755 on files matching ELF / Mach-O / shebang magic.
381							// One-shot per boot - cheap (a couple stat + read(4) calls
382							// per file in those directories), and recovers extensions
383							// installed before the in-extractor exec-bit fix landed
384							// without forcing the user to reinstall.
385							#[cfg(unix)]
386							if IsUserPath {
387								crate::ExtensionManagement::VsixInstaller::HealExecutableBits(&PotentialExtensionPath);
388							}
389
390							dev_log!(
391								"ext-scan",
392								"[ExtScan] accept path={} is_user={} is_builtin={} id={}",
393								PotentialExtensionPath.display(),
394								IsUserPath,
395								Description.IsBuiltin,
396								Description
397									.Identifier
398									.get("value")
399									.and_then(|V| V.as_str())
400									.unwrap_or("<unknown>")
401							);
402
403							FoundExtensions.push(Description);
404						},
405
406						Err(error) => {
407							parse_failures += 1;
408							dev_log!(
409								"extensions",
410								"warn: [ExtensionScanner] Failed to parse package.json for extension at '{}': {}",
411								PotentialExtensionPath.display(),
412								error
413							);
414							dev_log!(
415								"ext-scan",
416								"[ExtScan] skip path={} reason=parse-failure err={}",
417								PotentialExtensionPath.display(),
418								error
419							);
420						},
421					}
422				},
423				Err(error) => {
424					missing_package_json += 1;
425					dev_log!(
426						"extensions",
427						"warn: [ExtensionScanner] Could not read package.json at '{}': {}",
428						PackageJsonPath.display(),
429						error
430					);
431					dev_log!(
432						"ext-scan",
433						"[ExtScan] skip path={} reason=no-package-json err={}",
434						PotentialExtensionPath.display(),
435						error
436					);
437				},
438			}
439		}
440	}
441
442	dev_log!(
443		"extensions",
444		"[ExtensionScanner] Directory '{}' scan done: {} parsed, {} parse-failures, {} missing package.json, {} \
445		 denied-dirs, {} test-extensions-skipped (Test={})",
446		DirectoryPath.display(),
447		FoundExtensions.len(),
448		parse_failures,
449		missing_package_json,
450		denied_directory_count,
451		test_extension_skips,
452		AllowTestExtensions,
453	);
454
455	Ok(FoundExtensions)
456}
457
458/// Walk a manifest value and return true as soon as any `%placeholder%` string
459/// is encountered. Used to decide whether a missing `package.nls.json` bundle
460/// is a real problem or a shipped-as-English extension.
461fn ManifestContainsNLSPlaceholders(Value:&Value) -> bool {
462	match Value {
463		serde_json::Value::String(Text) => {
464			Text.len() >= 2 && Text.starts_with('%') && Text.ends_with('%') && !Text[1..Text.len() - 1].contains('%')
465		},
466		serde_json::Value::Array(Items) => Items.iter().any(ManifestContainsNLSPlaceholders),
467		serde_json::Value::Object(Object) => Object.values().any(ManifestContainsNLSPlaceholders),
468		_ => false,
469	}
470}
471
472/// Load an extension's NLS bundle (`package.nls.json`) into a `{key → string}`
473/// map. Returns `None` if the bundle is absent or unreadable; placeholders stay
474/// as-is in that case. Entries can be bare strings or `{message, comment}`
475/// objects - we only keep `message`.
476///
477/// The `PlaceholdersNeeded` flag downgrades the "no bundle" warning when the
478/// caller already proved the manifest has no `%placeholder%` entries to
479/// resolve - in that case the bundle is optional and its absence is benign
480/// (BATCH-18).
481async fn LoadNLSBundle(
482	RunTime:&Arc<ApplicationRunTime>,
483	ExtensionPath:&PathBuf,
484	PlaceholdersNeeded:bool,
485) -> Option<Map<String, Value>> {
486	let NLSPath = ExtensionPath.join("package.nls.json");
487	let Content = match RunTime.Run(ReadFile(NLSPath.clone())).await {
488		Ok(Bytes) => Bytes,
489		Err(Error) => {
490			if PlaceholdersNeeded {
491				dev_log!("nls", "[LandFix:NLS] no bundle for {} ({})", ExtensionPath.display(), Error);
492			} else {
493				dev_log!(
494					"nls",
495					"[LandFix:NLS] {} has no placeholders, no bundle needed",
496					ExtensionPath.display()
497				);
498			}
499			return None;
500		},
501	};
502	let Parsed:Value = match serde_json::from_slice(&Content) {
503		Ok(V) => V,
504		Err(Error) => {
505			dev_log!("nls", "warn: [LandFix:NLS] failed to parse {}: {}", NLSPath.display(), Error);
506			return None;
507		},
508	};
509	let Object = Parsed.as_object()?;
510	let mut Resolved = Map::with_capacity(Object.len());
511	for (Key, RawValue) in Object {
512		let Text = if let Some(s) = RawValue.as_str() {
513			Some(s.to_string())
514		} else if let Some(obj) = RawValue.as_object() {
515			obj.get("message").and_then(|m| m.as_str()).map(|s| s.to_string())
516		} else {
517			None
518		};
519		if let Some(t) = Text {
520			Resolved.insert(Key.clone(), Value::String(t));
521		}
522	}
523	dev_log!(
524		"nls",
525		"[LandFix:NLS] loaded {} keys for {}",
526		Resolved.len(),
527		ExtensionPath.display()
528	);
529	Some(Resolved)
530}
531
532/// Internal NLS walker that also counts substitutions made vs. unresolved
533/// placeholders it saw, so the outer scanner can log a one-line summary per
534/// extension.
535fn ResolveNLSPlaceholdersInner(Value:&mut Value, NLS:&Map<String, Value>, Replaced:&mut u32, Unresolved:&mut u32) {
536	match Value {
537		serde_json::Value::String(Text) => {
538			if Text.len() >= 2 && Text.starts_with('%') && Text.ends_with('%') {
539				let Key = &Text[1..Text.len() - 1];
540				if !Key.is_empty() && !Key.contains('%') {
541					if let Some(Replacement) = NLS.get(Key).and_then(|v| v.as_str()) {
542						*Text = Replacement.to_string();
543						*Replaced += 1;
544					} else {
545						*Unresolved += 1;
546					}
547				}
548			}
549		},
550		serde_json::Value::Array(Items) => {
551			for Item in Items {
552				ResolveNLSPlaceholdersInner(Item, NLS, Replaced, Unresolved);
553			}
554		},
555		serde_json::Value::Object(Map) => {
556			for (_, FieldValue) in Map {
557				ResolveNLSPlaceholdersInner(FieldValue, NLS, Replaced, Unresolved);
558			}
559		},
560		_ => {},
561	}
562}
563
564/// A helper function to extract default configuration values from all
565/// scanned extensions.
566pub fn CollectDefaultConfigurations(State:&ApplicationState) -> Result<Value, CommonError> {
567	let mut MergedDefaults = Map::new();
568
569	let Extensions = State
570		.Extension
571		.ScannedExtensions
572		.ScannedExtensions
573		.lock()
574		.map_err(Utility::ErrorMapping::MapApplicationStateLockErrorToCommonError)?;
575
576	for Extension in Extensions.values() {
577		if let Some(contributes) = Extension.Contributes.as_ref().and_then(|v| v.as_object()) {
578			if let Some(configuration) = contributes.get("configuration").and_then(|v| v.as_object()) {
579				if let Some(properties) = configuration.get("properties").and_then(|v| v.as_object()) {
580					// NESTED OBJECT HANDLING: Recursively process configuration properties
581					self::process_configuration_properties(&mut MergedDefaults, "", properties, &mut Vec::new())?;
582				}
583			}
584		}
585	}
586
587	Ok(Value::Object(MergedDefaults))
588}
589
590/// RECURSIVE CONFIGURATION PROCESSING: Handle nested object structures
591fn process_configuration_properties(
592	merged_defaults:&mut serde_json::Map<String, Value>,
593	current_path:&str,
594	properties:&serde_json::Map<String, Value>,
595	visited_keys:&mut Vec<String>,
596) -> Result<(), CommonError> {
597	for (key, value) in properties {
598		// Build the full path for this property
599		let full_path = if current_path.is_empty() {
600			key.clone()
601		} else {
602			format!("{}.{}", current_path, key)
603		};
604
605		// Check for circular references
606		if visited_keys.contains(&full_path) {
607			return Err(CommonError::Unknown {
608				Description:format!("Circular reference detected in configuration properties: {}", full_path),
609			});
610		}
611
612		visited_keys.push(full_path.clone());
613
614		if let Some(prop_details) = value.as_object() {
615			// Check if this is a nested object structure
616			if let Some(nested_properties) = prop_details.get("properties").and_then(|v| v.as_object()) {
617				// Recursively process nested properties
618				self::process_configuration_properties(merged_defaults, &full_path, nested_properties, visited_keys)?;
619			} else if let Some(default_value) = prop_details.get("default") {
620				// Handle regular property with default value
621				merged_defaults.insert(full_path.clone(), default_value.clone());
622			}
623		}
624
625		// Remove current key from visited keys
626		visited_keys.retain(|k| k != &full_path);
627	}
628
629	Ok(())
630}