ryo-symbol 0.1.0

Symbol system for Rust codebase - unique identifiers and file path management
Documentation
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
//! Workspace metadata provider - CargoMetadataProvider implementation

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use camino::{Utf8Path, Utf8PathBuf};
use cargo_metadata::{Metadata, MetadataCommand};
use thiserror::Error;

use crate::crate_name::CrateName;
use crate::file_path::WorkspaceFilePath;
use crate::resolver::{CrateLayout, WorkspaceType};

/// Workspace metadata provider trait
///
/// Provides metadata about the workspace, such as crate information.
/// This trait abstracts away the details of how workspace information
/// is obtained.
///
/// # Thread Safety
/// Implementations must be `Send + Sync` for use in multi-threaded contexts.
pub trait WorkspaceMetadataProvider: Send + Sync {
    /// Get the crate name for a file path
    ///
    /// Returns the crate that contains the given file, or None if
    /// the file is not part of any known crate.
    fn crate_for_file(&self, path: &WorkspaceFilePath) -> Option<CrateName>;

    /// Get all crate names in the workspace
    fn all_crates(&self) -> Vec<CrateName>;

    /// Get the root directory of a crate
    fn crate_root(&self, crate_name: &CrateName) -> Option<PathBuf>;

    /// Get the workspace root directory
    fn workspace_root(&self) -> &Path;

    /// Get the CrateLayout for a crate.
    ///
    /// Determines the directory structure of a crate within the workspace.
    /// Used for converting crate-relative paths to workspace-relative paths.
    ///
    /// # Returns
    ///
    /// - `Some(CrateLayout::Root)` - Crate at workspace root
    /// - `Some(CrateLayout::InCrates { .. })` - Crate in `crates/` directory
    /// - `Some(CrateLayout::Custom { .. })` - Crate at custom path
    /// - `None` - Crate not found
    fn crate_layout(&self, crate_name: &CrateName) -> Option<CrateLayout>;
}

/// Error type for CargoMetadataProvider
#[derive(Debug, Error)]
pub enum MetadataError {
    /// The expected `Cargo.toml` file does not exist at the given path.
    #[error("manifest not found: {0}")]
    ManifestNotFound(PathBuf),

    /// `cargo metadata` invocation failed (I/O, parse, or non-zero exit).
    #[error("cargo metadata failed: {0}")]
    CargoMetadata(#[from] cargo_metadata::Error),

    /// The requested path is not within the resolved workspace root, so no
    /// crate mapping can be produced for it.
    #[error("path is outside workspace: {0}")]
    OutsideWorkspace(PathBuf),
}

/// Information about a crate in the workspace
#[derive(Debug, Clone)]
pub struct CrateInfo {
    /// Crate name (e.g., "ryo-app")
    pub name: String,
    /// Module name (hyphens → underscores, e.g., "ryo_app")
    pub module_name: String,
    /// Path to Cargo.toml
    pub manifest_path: Utf8PathBuf,
    /// Root source directory (typically "src")
    pub src_path: Utf8PathBuf,
    /// Is this a workspace member (vs external dependency)
    pub is_workspace_member: bool,
    /// Entry points (lib.rs, main.rs, etc.) from Cargo targets
    pub entry_points: Vec<TargetInfo>,
}

/// Information about a cargo target (lib, bin, etc.)
#[derive(Debug, Clone)]
pub struct TargetInfo {
    /// Target name
    pub name: String,
    /// Target kind ("lib", "bin", "example", "test", "bench")
    pub kind: TargetKind,
    /// Path to source file (e.g., src/lib.rs, src/main.rs)
    pub src_path: Utf8PathBuf,
}

/// Kind of cargo target
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TargetKind {
    /// Library target (`[lib]`), including rlib / dylib / cdylib / staticlib
    /// / proc-macro flavors collapsed into one bucket.
    Lib,
    /// Binary target (`[[bin]]`).
    Bin,
    /// Example target under `examples/`.
    Example,
    /// Integration test target under `tests/`.
    Test,
    /// Benchmark target under `benches/`.
    Bench,
    /// Any cargo target kind not recognized by this crate (forward-compat
    /// catch-all for new Cargo target kinds added upstream).
    Other,
}

impl TargetKind {
    fn from_cargo_kinds(kinds: &[cargo_metadata::TargetKind]) -> Self {
        use cargo_metadata::TargetKind as CK;
        for kind in kinds {
            match kind {
                CK::Lib | CK::RLib | CK::DyLib | CK::CDyLib | CK::StaticLib | CK::ProcMacro => {
                    return Self::Lib
                }
                CK::Bin => return Self::Bin,
                CK::Example => return Self::Example,
                CK::Test => return Self::Test,
                CK::Bench => return Self::Bench,
                _ => {}
            }
        }
        Self::Other
    }
}

/// Cargo metadata based workspace provider
///
/// This is the default implementation of `WorkspaceMetadataProvider`.
/// It uses `cargo metadata` to discover workspace structure and
/// map file paths to crate names.
///
/// # Example
/// ```ignore
/// use ryo_symbol::{CargoMetadataProvider, WorkspaceMetadataProvider};
///
/// let provider = CargoMetadataProvider::from_manifest("Cargo.toml")?;
///
/// // Get crate name for a file
/// let path = provider.resolver().resolve("crates/ryo-app/src/lib.rs")?;
/// let crate_name = provider.crate_for_file(&path);
/// ```
#[derive(Debug)]
pub struct CargoMetadataProvider {
    /// Workspace root directory
    workspace_root: Utf8PathBuf,
    /// All crates in the workspace (by name)
    crates: HashMap<String, CrateInfo>,
    /// File path prefix → crate name mapping (for fast lookup)
    path_to_crate: Vec<(Utf8PathBuf, String)>,
    /// Workspace type (Workspace or Crate)
    workspace_type: WorkspaceType,
}

impl CargoMetadataProvider {
    /// Create a provider from a Cargo.toml path
    pub fn from_manifest(manifest_path: impl AsRef<Path>) -> Result<Self, MetadataError> {
        let manifest_path = manifest_path.as_ref();

        if !manifest_path.exists() {
            return Err(MetadataError::ManifestNotFound(manifest_path.to_path_buf()));
        }

        let metadata = MetadataCommand::new()
            .manifest_path(manifest_path)
            .no_deps() // Only workspace members, faster
            .exec()?;

        Self::from_metadata(metadata)
    }

    /// Create a provider from a directory containing Cargo.toml
    pub fn from_directory(dir: impl AsRef<Path>) -> Result<Self, MetadataError> {
        let dir = dir.as_ref();
        let manifest_path = dir.join("Cargo.toml");
        Self::from_manifest(manifest_path)
    }

    /// Create a provider from pre-fetched metadata
    pub fn from_metadata(metadata: Metadata) -> Result<Self, MetadataError> {
        let workspace_root = metadata.workspace_root.clone();
        let workspace_members: std::collections::HashSet<_> =
            metadata.workspace_members.iter().collect();

        let mut crates = HashMap::new();
        let mut path_to_crate = Vec::new();

        for pkg in &metadata.packages {
            let is_member = workspace_members.contains(&pkg.id);
            let manifest_dir = pkg.manifest_path.parent().unwrap_or(&pkg.manifest_path);
            let src_path_absolute = manifest_dir.join("src");

            // Convert to relative path from workspace root
            let src_path = src_path_absolute
                .strip_prefix(&workspace_root)
                .unwrap_or(&src_path_absolute)
                .to_path_buf();

            // Collect entry points from targets
            let entry_points: Vec<TargetInfo> = pkg
                .targets
                .iter()
                .map(|target| {
                    // Convert target src_path to relative
                    let target_src_relative = target
                        .src_path
                        .strip_prefix(&workspace_root)
                        .unwrap_or(&target.src_path)
                        .to_path_buf();
                    TargetInfo {
                        name: target.name.clone(),
                        kind: TargetKind::from_cargo_kinds(&target.kind),
                        src_path: target_src_relative,
                    }
                })
                .collect();

            let info = CrateInfo {
                name: pkg.name.clone(),
                module_name: pkg.name.replace('-', "_"),
                manifest_path: pkg.manifest_path.clone(),
                src_path: src_path.clone(),
                is_workspace_member: is_member,
                entry_points,
            };

            // Only index workspace members for path resolution
            if is_member {
                path_to_crate.push((src_path, info.module_name.clone()));
            }

            crates.insert(pkg.name.clone(), info);
        }

        // Sort by path length (longest first) for prefix matching
        path_to_crate.sort_by_key(|b| std::cmp::Reverse(b.0.as_str().len()));

        // Determine workspace type:
        // - Multiple members → Workspace
        // - Single member at workspace_root (manifest in root) → Crate
        // - Single member in subdirectory → Workspace
        let workspace_type = if workspace_members.len() > 1 {
            WorkspaceType::Workspace
        } else if let Some(pkg) = metadata
            .packages
            .iter()
            .find(|p| workspace_members.contains(&p.id))
        {
            // Check if the single member's manifest is at workspace root
            let manifest_dir = pkg.manifest_path.parent().unwrap_or(&pkg.manifest_path);
            if manifest_dir == workspace_root {
                WorkspaceType::Crate
            } else {
                WorkspaceType::Workspace
            }
        } else {
            WorkspaceType::Workspace
        };

        Ok(Self {
            workspace_root,
            crates,
            path_to_crate,
            workspace_type,
        })
    }

    /// Get crate info by name
    pub fn get_crate(&self, name: &str) -> Option<&CrateInfo> {
        self.crates.get(name)
    }

    /// Get the CrateLayout for a crate by module name.
    ///
    /// Determines the directory structure of a crate within the workspace
    /// based on its `src_path`. This is essential for converting crate-relative
    /// paths (e.g., `"src/lib.rs"`) to workspace-relative paths
    /// (e.g., `"crates/my-crate/src/lib.rs"`).
    ///
    /// # Returns
    ///
    /// - `Some(CrateLayout::Root)` - Crate at workspace root (`src/lib.rs`)
    /// - `Some(CrateLayout::InCrates { .. })` - Crate in `crates/` directory
    /// - `Some(CrateLayout::Custom { .. })` - Crate at custom path
    /// - `None` - Crate not found in workspace
    ///
    /// # Example
    ///
    /// ```ignore
    /// let provider = CargoMetadataProvider::from_directory(".")?;
    /// let crate_name = CrateName::new("my_crate")?;
    ///
    /// match provider.crate_layout(&crate_name) {
    ///     Some(CrateLayout::Root) => println!("Crate at workspace root"),
    ///     Some(CrateLayout::InCrates { crate_dir_name }) => {
    ///         println!("Crate in crates/{}", crate_dir_name);
    ///     }
    ///     Some(CrateLayout::Custom { prefix }) => {
    ///         println!("Crate at {}", prefix.display());
    ///     }
    ///     None => println!("Crate not found"),
    /// }
    /// ```
    pub fn crate_layout(&self, crate_name: &CrateName) -> Option<CrateLayout> {
        // Find crate by module name (underscores)
        let module_name = crate_name.to_module_name();
        let info = self
            .crates
            .values()
            .find(|c| c.module_name == module_name && c.is_workspace_member)?;

        // Analyze src_path to determine layout
        let src_path = info.src_path.as_str();

        // Pattern 1: "src" → Root (crate at workspace root)
        if src_path == "src" {
            return Some(CrateLayout::Root);
        }

        // Pattern 2: "crates/{name}/src" → InCrates
        if let Some(rest) = src_path.strip_prefix("crates/") {
            if let Some(crate_dir) = rest.strip_suffix("/src") {
                return Some(CrateLayout::InCrates {
                    crate_dir_name: crate_dir.to_string(),
                });
            }
        }

        // Pattern 3: "{prefix}/src" → Custom
        if let Some(prefix) = src_path.strip_suffix("/src") {
            return Some(CrateLayout::Custom {
                prefix: PathBuf::from(prefix),
            });
        }

        // Fallback: treat entire src_path as custom prefix
        Some(CrateLayout::Custom {
            prefix: PathBuf::from(src_path),
        })
    }

    /// Get the workspace type
    pub fn workspace_type(&self) -> WorkspaceType {
        self.workspace_type
    }

    /// Get all workspace members
    pub fn members(&self) -> impl Iterator<Item = &CrateInfo> {
        self.crates.values().filter(|c| c.is_workspace_member)
    }

    /// Check if a path is within the workspace
    pub fn is_in_workspace(&self, path: impl AsRef<Path>) -> bool {
        let path = path.as_ref();
        path.to_str()
            .map(|s| Utf8Path::new(s).starts_with(&self.workspace_root))
            .unwrap_or(false)
    }

    /// Get the module path within a crate for a file
    ///
    /// Example: "crates/ryo-app/src/config/mod.rs" → "config"
    pub fn module_path_for_file(&self, file_path: impl AsRef<Path>) -> Option<String> {
        let file_path = file_path.as_ref();
        let file_path_str = file_path.to_str()?;
        let file_path = Utf8Path::new(file_path_str);

        let file_path = if file_path.is_relative() {
            self.workspace_root.join(file_path)
        } else {
            file_path.to_path_buf()
        };

        // Find matching crate
        for (src_path, _) in &self.path_to_crate {
            if file_path.starts_with(src_path) {
                // Get relative path within src
                let relative = file_path.strip_prefix(src_path).ok()?;
                let relative_str = relative.as_str();

                // Remove .rs extension
                let module_path = relative_str.trim_end_matches(".rs");

                // Convert path separators to ::
                let module_path = module_path.replace('/', "::");

                // Handle lib.rs and mod.rs
                let module_path = if module_path == "lib" || module_path.is_empty() {
                    String::new()
                } else if module_path.ends_with("::mod") {
                    module_path.trim_end_matches("::mod").to_string()
                } else {
                    module_path
                };

                return Some(module_path);
            }
        }

        None
    }

    /// Get the full symbol path for a file
    ///
    /// Example: "crates/ryo-app/src/config/mod.rs" → "ryo_app::config"
    pub fn symbol_path_for_file(&self, file_path: impl AsRef<Path>) -> Option<String> {
        let file_path = file_path.as_ref();
        let file_path_str = file_path.to_str()?;
        let utf8_path = Utf8Path::new(file_path_str);

        let canonical_path = if utf8_path.is_relative() {
            self.workspace_root.join(utf8_path)
        } else {
            utf8_path.to_path_buf()
        };

        // Find crate name
        for (src_path, module_name) in &self.path_to_crate {
            if canonical_path.starts_with(src_path) {
                let module_path = self.module_path_for_file(file_path)?;
                return if module_path.is_empty() {
                    Some(module_name.clone())
                } else {
                    Some(format!("{}::{}", module_name, module_path))
                };
            }
        }

        None
    }

    /// Get internal crate name lookup (for trait implementation)
    fn crate_name_for_path(&self, file_path: &Path) -> Option<&str> {
        let file_path_str = file_path.to_str()?;
        let file_path = Utf8Path::new(file_path_str);

        // Convert to absolute path
        let file_path_absolute = if file_path.is_relative() {
            self.workspace_root.join(file_path)
        } else {
            file_path.to_path_buf()
        };

        // Find matching crate by src path prefix
        // Note: path_to_crate contains relative paths (relative to workspace_root)
        for (src_path, module_name) in &self.path_to_crate {
            // Convert src_path to absolute for comparison
            let src_path_absolute = self.workspace_root.join(src_path);
            if file_path_absolute.starts_with(&src_path_absolute) {
                return Some(module_name.as_str());
            }
        }

        None
    }
}

impl WorkspaceMetadataProvider for CargoMetadataProvider {
    fn crate_for_file(&self, path: &WorkspaceFilePath) -> Option<CrateName> {
        let absolute = path.to_absolute();
        let module_name = self.crate_name_for_path(&absolute)?;
        Some(CrateName::new_unchecked(module_name))
    }

    fn all_crates(&self) -> Vec<CrateName> {
        self.crates
            .values()
            .filter(|c| c.is_workspace_member)
            .map(|c| CrateName::new_unchecked(&c.module_name))
            .collect()
    }

    fn crate_root(&self, crate_name: &CrateName) -> Option<PathBuf> {
        // Try to find by module name first (underscores)
        let module_name = crate_name.to_module_name();

        for info in self.crates.values() {
            if info.module_name == module_name {
                return info
                    .manifest_path
                    .parent()
                    .map(|p| PathBuf::from(p.as_str()));
            }
        }

        // Try by cargo name (hyphens)
        self.crates
            .get(crate_name.as_str())
            .and_then(|info| info.manifest_path.parent())
            .map(|p| PathBuf::from(p.as_str()))
    }

    fn workspace_root(&self) -> &Path {
        self.workspace_root.as_std_path()
    }

    fn crate_layout(&self, crate_name: &CrateName) -> Option<CrateLayout> {
        // Delegate to the inherent method
        CargoMetadataProvider::crate_layout(self, crate_name)
    }
}

/// Mock metadata provider for testing
///
/// Provides a simple in-memory implementation of `WorkspaceMetadataProvider`
/// that returns a fixed crate name for all files.
///
/// # Example
/// ```ignore
/// use ryo_symbol::{MockMetadataProvider, WorkspaceMetadataProvider};
///
/// let provider = MockMetadataProvider::new("/workspace", "mylib");
/// let path = WorkspaceFilePath::new_for_test("src/lib.rs", "/workspace");
/// assert_eq!(provider.crate_for_file(&path).unwrap().as_str(), "mylib");
/// ```
#[cfg(any(test, feature = "test-utils"))]
#[derive(Debug, Clone)]
pub struct MockMetadataProvider {
    workspace_root: PathBuf,
    crate_name: CrateName,
}

#[cfg(any(test, feature = "test-utils"))]
impl MockMetadataProvider {
    /// Create a new mock provider with a fixed crate name
    pub fn new(workspace_root: impl Into<PathBuf>, crate_name: impl AsRef<str>) -> Self {
        Self {
            workspace_root: workspace_root.into(),
            crate_name: CrateName::new_unchecked(crate_name.as_ref()),
        }
    }
}

#[cfg(any(test, feature = "test-utils"))]
impl WorkspaceMetadataProvider for MockMetadataProvider {
    fn crate_for_file(&self, _path: &WorkspaceFilePath) -> Option<CrateName> {
        Some(self.crate_name.clone())
    }

    fn all_crates(&self) -> Vec<CrateName> {
        vec![self.crate_name.clone()]
    }

    fn crate_root(&self, _crate_name: &CrateName) -> Option<PathBuf> {
        Some(self.workspace_root.clone())
    }

    fn workspace_root(&self) -> &Path {
        &self.workspace_root
    }

    fn crate_layout(&self, _crate_name: &CrateName) -> Option<CrateLayout> {
        // Mock always returns Root layout
        Some(CrateLayout::Root)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::resolver::CrateLayout;

    // ========================================================================
    // crate_layout() tests - TDD RED phase
    // ========================================================================

    #[test]
    fn test_crate_layout_root_crate() {
        // Single crate at workspace root: src/lib.rs
        // src_path = "src" (relative to workspace root)
        let provider = create_test_provider_with_src_path("my_crate", "src");
        let crate_name = CrateName::new_unchecked("my_crate");

        let layout = provider.crate_layout(&crate_name);

        assert_eq!(layout, Some(CrateLayout::Root));
    }

    #[test]
    fn test_crate_layout_in_crates_directory() {
        // Crate in crates/ directory: crates/my-crate/src/lib.rs
        // src_path = "crates/my-crate/src" (relative to workspace root)
        let provider = create_test_provider_with_src_path("my_crate", "crates/my-crate/src");
        let crate_name = CrateName::new_unchecked("my_crate");

        let layout = provider.crate_layout(&crate_name);

        assert_eq!(
            layout,
            Some(CrateLayout::InCrates {
                crate_dir_name: "my-crate".to_string()
            })
        );
    }

    #[test]
    fn test_crate_layout_custom_path() {
        // Crate at custom path: packages/core/src/lib.rs
        // src_path = "packages/core/src" (relative to workspace root)
        let provider = create_test_provider_with_src_path("core", "packages/core/src");
        let crate_name = CrateName::new_unchecked("core");

        let layout = provider.crate_layout(&crate_name);

        assert_eq!(
            layout,
            Some(CrateLayout::Custom {
                prefix: PathBuf::from("packages/core")
            })
        );
    }

    #[test]
    fn test_crate_layout_unknown_crate_returns_none() {
        let provider = create_test_provider_with_src_path("my_crate", "src");
        let crate_name = CrateName::new_unchecked("unknown_crate");

        let layout = provider.crate_layout(&crate_name);

        assert_eq!(layout, None);
    }

    /// Helper: Create a test provider with specified src_path
    fn create_test_provider_with_src_path(
        module_name: &str,
        src_path: &str,
    ) -> CargoMetadataProvider {
        let workspace_root = Utf8PathBuf::from("/workspace");
        let mut crates = HashMap::new();

        let info = CrateInfo {
            name: module_name.replace('_', "-"),
            module_name: module_name.to_string(),
            manifest_path: Utf8PathBuf::from(format!(
                "/workspace/{}/Cargo.toml",
                src_path.trim_end_matches("/src")
            )),
            src_path: Utf8PathBuf::from(src_path),
            is_workspace_member: true,
            entry_points: vec![],
        };

        crates.insert(info.name.clone(), info.clone());

        let path_to_crate = vec![(Utf8PathBuf::from(src_path), module_name.to_string())];

        CargoMetadataProvider {
            workspace_root,
            crates,
            path_to_crate,
            workspace_type: WorkspaceType::Workspace,
        }
    }

    // ========================================================================
    // Existing tests
    // ========================================================================

    #[test]
    fn test_crate_info() {
        let info = CrateInfo {
            name: "ryo-app".to_string(),
            module_name: "ryo_app".to_string(),
            manifest_path: Utf8PathBuf::from("/test/Cargo.toml"),
            src_path: Utf8PathBuf::from("/test/src"),
            is_workspace_member: true,
            entry_points: vec![TargetInfo {
                name: "ryo_app".to_string(),
                kind: TargetKind::Lib,
                src_path: Utf8PathBuf::from("/test/src/lib.rs"),
            }],
        };

        assert_eq!(info.module_name, "ryo_app");
        assert!(info.is_workspace_member);
        assert_eq!(info.entry_points.len(), 1);
    }

    #[test]
    fn test_mock_provider() {
        let provider = MockMetadataProvider::new("/workspace", "mylib");
        let path = WorkspaceFilePath::new_for_test("src/lib.rs", "/workspace", "mylib");

        assert_eq!(provider.crate_for_file(&path).unwrap().as_str(), "mylib");
        assert_eq!(provider.workspace_root(), Path::new("/workspace"));
        assert_eq!(provider.all_crates().len(), 1);
    }
}