ryo-app 0.1.0

[preview] Application layer for RYO - Project management, Intent handling, API
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
697
698
//! Project: In-memory collection of AST files with workspace metadata
//!
//! Provides file collection with I/O capabilities.
//! Does NOT include transformation logic (use ryo-executor).
//! Does NOT include search logic (use ryo-analysis).
//!
//! # Design
//!
//! In the Context-centric design (Phase 5), `Project` serves as an I/O adapter:
//! - Loading: `Project::load()` → files + metadata used to create `AnalysisContext`
//! - Writing: `Project::write_from_context()` → sync Context changes to disk
//!
//! The `AnalysisContext` is the Single Source of Truth for file content.
//!
//! # Workspace Detection
//!
//! `Project` uses `ryo_symbol::CargoMetadataProvider` for accurate workspace detection:
//! 1. If `ryo.toml` exists, use `manifest_path` or `workspace_root` settings
//! 2. Otherwise, detect `Cargo.toml` from the given path
//!
//! This ensures consistent workspace root detection across all components.

use crate::config::RyoConfig;
use ryo_source::pure::PureFile;
use ryo_symbol::{
    write_with_parents, CargoMetadataProvider, WorkspaceFilePath, WorkspaceMetadataProvider,
    WorkspacePathResolver,
};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Project error types
#[derive(Debug, thiserror::Error)]
pub enum ProjectError {
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("Parse error in {path}: {message}")]
    Parse { path: PathBuf, message: String },

    #[error("File not found: {0}")]
    FileNotFound(PathBuf),

    #[error("Cargo metadata error: {0}")]
    Metadata(#[from] ryo_symbol::MetadataError),

    #[error("Config error: {0}")]
    Config(#[from] crate::config::ConfigError),

    #[error("Source generation failed: {0}")]
    SourceGeneration(#[from] ryo_source::pure::ToSynError),
}

/// A project loaded entirely in memory as PureFile ASTs.
///
/// This is a pure data container with I/O capabilities.
/// For transformations, use `ryo-executor::Workspace`.
/// For searching, use `ryo-analysis::DiscoveryEngine`.
///
/// # Fields
///
/// - `config_root`: Location of `ryo.toml` (or where it would be)
/// - `metadata`: Cargo workspace metadata (crate info, paths)
/// - `config`: Project configuration from `ryo.toml`
/// - `files`: Loaded source files
pub struct Project {
    /// Location of ryo.toml (or the directory passed to load)
    config_root: PathBuf,

    /// Cargo metadata provider (workspace info from cargo metadata)
    metadata: CargoMetadataProvider,

    /// Project configuration (from ryo.toml)
    config: RyoConfig,

    /// Files loaded as PureFile ASTs (keyed by absolute PathBuf for backward compat)
    files: HashMap<PathBuf, PureFile>,
}

impl Project {
    /// Load a project from disk
    ///
    /// # Workflow
    ///
    /// 1. Look for `ryo.toml` in the given directory
    /// 2. Determine Cargo.toml location from config or auto-detect
    /// 3. Create `CargoMetadataProvider` for workspace info
    /// 4. Load files by traversing mod declarations from entry points
    ///
    /// # Arguments
    ///
    /// * `path` - Directory containing the project (with or without ryo.toml)
    pub fn load(path: impl AsRef<Path>) -> Result<Self, ProjectError> {
        let config_root = path.as_ref().canonicalize()?;

        // 1. Load ryo.toml (or use default)
        let config = RyoConfig::load_or_default(&config_root);

        // 2. Determine manifest path
        let manifest_path = Self::resolve_manifest_path(&config_root, &config);

        // 3. Create CargoMetadataProvider
        let metadata = CargoMetadataProvider::from_manifest(&manifest_path)?;

        // 4. Load files by traversing mod declarations from entry points
        let mut files = HashMap::new();
        let workspace_root = metadata.workspace_root();
        for member in metadata.members() {
            Self::load_from_entry_points(workspace_root, member, &mut files)?;
        }

        Ok(Self {
            config_root,
            metadata,
            config,
            files,
        })
    }

    /// Resolve the Cargo.toml manifest path
    fn resolve_manifest_path(config_root: &Path, config: &RyoConfig) -> PathBuf {
        // Priority:
        // 1. Explicit manifest_path in config
        // 2. workspace_root + Cargo.toml
        // 3. config_root + Cargo.toml (no upward search if exists)
        // 4. Search upward for Cargo.toml (only if not found in config_root)

        if let Some(ref manifest) = config.project.manifest_path {
            return config_root.join(manifest);
        }

        if let Some(ref ws_root) = config.project.workspace_root {
            return config_root.join(ws_root).join("Cargo.toml");
        }

        // Check config_root first - if it exists, use it directly
        let default_manifest = config_root.join("Cargo.toml");
        if default_manifest.exists() {
            return default_manifest;
        }

        // Only search upward if not found in config_root
        config_root
            .ancestors()
            .skip(1) // Skip config_root itself (already checked)
            .find(|p| p.join("Cargo.toml").exists())
            .map(|p| p.join("Cargo.toml"))
            .unwrap_or(default_manifest)
    }

    /// Get the config root (where ryo.toml is or would be)
    pub fn config_root(&self) -> &Path {
        &self.config_root
    }

    /// Get the workspace root (from Cargo metadata)
    pub fn workspace_root(&self) -> &Path {
        self.metadata.workspace_root()
    }

    /// Get the root path (alias for workspace_root for backward compatibility)
    pub fn root(&self) -> &Path {
        self.workspace_root()
    }

    /// Get the Cargo metadata provider
    pub fn metadata(&self) -> &CargoMetadataProvider {
        &self.metadata
    }

    /// Get the project configuration
    pub fn config(&self) -> &RyoConfig {
        &self.config
    }

    /// Create a WorkspacePathResolver for this project
    ///
    /// Uses workspace type from CargoMetadataProvider to correctly validate
    /// `crate::` paths (ambiguous in multi-crate workspaces).
    pub fn path_resolver(&self) -> WorkspacePathResolver {
        WorkspacePathResolver::with_type(
            self.workspace_root().to_path_buf(),
            self.metadata.workspace_type(),
        )
    }

    /// Get all file paths
    pub fn file_paths(&self) -> impl Iterator<Item = &PathBuf> {
        self.files.keys()
    }

    /// Get all files
    pub fn files(&self) -> &HashMap<PathBuf, PureFile> {
        &self.files
    }

    /// Get mutable access to files
    pub fn files_mut(&mut self) -> &mut HashMap<PathBuf, PureFile> {
        &mut self.files
    }

    /// Number of files loaded
    pub fn file_count(&self) -> usize {
        self.files.len()
    }

    /// Resolve a path to the actual key in the files HashMap.
    /// Handles both relative and absolute paths.
    pub fn resolve_path(&self, path: &Path) -> Option<PathBuf> {
        // Try exact match first
        if self.files.contains_key(path) {
            return Some(path.to_path_buf());
        }

        // If relative path, try joining with root
        if path.is_relative() {
            let absolute = self.root().join(path);
            if self.files.contains_key(&absolute) {
                return Some(absolute);
            }
        }

        // If absolute path, try canonicalizing (handles symlinks like /var -> /private/var)
        if path.is_absolute() {
            if let Ok(canonical) = path.canonicalize() {
                if self.files.contains_key(&canonical) {
                    return Some(canonical);
                }
            }
            // Also try stripping root to get relative
            if let Ok(relative) = path.strip_prefix(self.root()) {
                let relative_buf = relative.to_path_buf();
                if self.files.contains_key(&relative_buf) {
                    return Some(relative_buf);
                }
            }
        }

        None
    }

    /// Get a file by path
    pub fn get_file(&self, path: &Path) -> Option<&PureFile> {
        self.resolve_path(path)
            .and_then(|resolved| self.files.get(&resolved))
    }

    /// Get a mutable file by path
    pub fn get_file_mut(&mut self, path: &Path) -> Option<&mut PureFile> {
        if let Some(resolved) = self.resolve_path(path) {
            self.files.get_mut(&resolved)
        } else {
            None
        }
    }

    /// Insert or update a file
    pub fn insert_file(&mut self, path: PathBuf, file: PureFile) {
        self.files.insert(path, file);
    }

    /// Get a file and its resolved path
    pub fn get_file_with_path(&self, path: &Path) -> Option<(PathBuf, &PureFile)> {
        self.resolve_path(path)
            .and_then(|resolved| self.files.get(&resolved).map(|f| (resolved, f)))
    }

    /// Get a mutable file and its resolved path
    pub fn get_file_mut_with_path(&mut self, path: &Path) -> Option<(PathBuf, &mut PureFile)> {
        if let Some(resolved) = self.resolve_path(path) {
            self.files.get_mut(&resolved).map(|f| (resolved, f))
        } else {
            None
        }
    }

    /// Check if a file exists
    pub fn contains_file(&self, path: &Path) -> bool {
        self.resolve_path(path).is_some()
    }

    /// Get generated source for a file
    pub fn get_source(&self, path: &Path) -> Result<Option<String>, ProjectError> {
        Ok(self.get_file(path).map(|f| f.to_source()).transpose()?)
    }

    /// Write modified files back to disk
    ///
    /// Creates parent directories if they don't exist (for newly created files).
    pub fn write_to_disk(&self, paths: &[PathBuf]) -> Result<usize, ProjectError> {
        let mut written = 0;

        for path in paths {
            if let Some(file) = self.files.get(path) {
                let source = file.to_source()?;
                write_with_parents(path, &source)?;
                written += 1;
            }
        }

        Ok(written)
    }

    /// Write all files to disk
    pub fn write_all_to_disk(&self) -> Result<usize, ProjectError> {
        let paths: Vec<_> = self.files.keys().cloned().collect();
        self.write_to_disk(&paths)
    }

    // ========================================================================
    // Context-Centric I/O (Phase 5)
    // ========================================================================

    /// Load files from a project directory without creating a Project instance.
    ///
    /// This is the preferred method for the Context-centric design where
    /// `AnalysisContext` is the Single Source of Truth for file content.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let files = Project::load_files("/path/to/project")?;
    /// let context = AnalysisContext::from_path_files(files, "crate");
    /// ```
    pub fn load_files(root: impl AsRef<Path>) -> Result<HashMap<PathBuf, PureFile>, ProjectError> {
        let root = root.as_ref().canonicalize()?;
        let mut files = HashMap::new();

        Self::load_dir(&root, &root, &mut files)?;

        Ok(files)
    }

    /// Write modified files from an AnalysisContext to disk.
    ///
    /// # Arguments
    ///
    /// * `ctx` - The AnalysisContext containing the modified files
    /// * `files` - The WorkspaceFilePaths of the files to write
    ///
    /// # Returns
    ///
    /// The number of files successfully written to disk.
    pub fn write_from_context(
        &self,
        ctx: &ryo_analysis::AnalysisContext,
        files: &[WorkspaceFilePath],
    ) -> Result<usize, ProjectError> {
        let mut written = 0;

        for file_path in files {
            if let Some(file) = ctx.file(file_path) {
                let source = file.to_source()?;
                // Use WorkspaceFilePath::write() to ensure parent dirs are created
                file_path.write(&source)?;
                written += 1;
            }
        }

        Ok(written)
    }

    /// Sync modified files from Context back to Project.files.
    ///
    /// Maintains backward compatibility for code that still reads from Project.files.
    pub fn sync_from_context(
        &mut self,
        ctx: &ryo_analysis::AnalysisContext,
        files: &[WorkspaceFilePath],
    ) {
        for file_path in files {
            if let Some(file) = ctx.file(file_path) {
                let absolute_path = file_path.to_absolute();
                self.files.insert(absolute_path, (*file).clone());
            }
        }
    }

    // ========================================================================
    // Private helpers
    // ========================================================================

    /// Load files from a crate's entry points by traversing mod declarations
    fn load_from_entry_points(
        workspace_root: &Path,
        crate_info: &ryo_symbol::CrateInfo,
        files: &mut HashMap<PathBuf, PureFile>,
    ) -> Result<(), ProjectError> {
        use ryo_symbol::TargetKind;

        for target in &crate_info.entry_points {
            // Only process lib and bin targets (skip tests, examples, benches)
            if !matches!(target.kind, TargetKind::Lib | TargetKind::Bin) {
                continue;
            }

            // target.src_path is relative to workspace_root
            let entry_path = workspace_root.join(target.src_path.as_str());
            if entry_path.exists() {
                Self::load_module_tree(&entry_path, files)?;
            }
        }

        Ok(())
    }

    /// Recursively load a module and all its child modules
    fn load_module_tree(
        file_path: &Path,
        files: &mut HashMap<PathBuf, PureFile>,
    ) -> Result<(), ProjectError> {
        // Skip if already loaded
        if files.contains_key(file_path) {
            return Ok(());
        }

        // Try to canonicalize for consistent keys
        let canonical_path = file_path
            .canonicalize()
            .unwrap_or_else(|_| file_path.to_path_buf());

        if files.contains_key(&canonical_path) {
            return Ok(());
        }

        // Load and parse the file
        let pure_file = match Self::load_file(file_path) {
            Ok(f) => f,
            Err(e) => {
                tracing::warn!("Failed to load {}: {}", file_path.display(), e);
                return Ok(());
            }
        };

        // Extract mod declarations before inserting
        let mod_names: Vec<String> = pure_file
            .items
            .iter()
            .filter_map(|item| {
                if let ryo_source::pure::PureItem::Mod(m) = item {
                    // Only external mod declarations (mod foo;)
                    if m.items.is_empty() {
                        return Some(m.name.clone());
                    }
                }
                None
            })
            .collect();

        // Insert the file
        files.insert(canonical_path.clone(), pure_file);

        // Get the directory for child modules.
        // For Rust 2018 style (src/foo.rs), child modules are in src/foo/
        // For classic style (src/foo/mod.rs), child modules are in src/foo/
        let parent_dir = canonical_path
            .parent()
            .ok_or_else(|| ProjectError::FileNotFound(file_path.to_path_buf()))?;

        // Determine the search directory for child modules
        let child_search_dir = if let Some(file_stem) = canonical_path.file_stem() {
            let file_name = canonical_path.file_name().and_then(|n| n.to_str());
            if file_name != Some("mod.rs")
                && file_name != Some("lib.rs")
                && file_name != Some("main.rs")
            {
                // Rust 2018 style: src/foo.rs -> child modules in src/foo/
                parent_dir.join(file_stem)
            } else {
                // Classic style: src/foo/mod.rs -> child modules in src/foo/
                parent_dir.to_path_buf()
            }
        } else {
            parent_dir.to_path_buf()
        };

        // Resolve and load child modules
        for mod_name in mod_names {
            if let Some(child_path) = Self::resolve_mod_path(&child_search_dir, &mod_name) {
                Self::load_module_tree(&child_path, files)?;
            }
        }

        Ok(())
    }

    /// Resolve a module name to its file path
    ///
    /// Follows Rust's module resolution rules:
    /// - `mod foo;` in `src/lib.rs` → `src/foo.rs` or `src/foo/mod.rs`
    /// - `mod bar;` in `src/foo/mod.rs` → `src/foo/bar.rs` or `src/foo/bar/mod.rs`
    fn resolve_mod_path(parent_dir: &Path, mod_name: &str) -> Option<PathBuf> {
        // Try modern style: parent/mod_name.rs
        let modern_path = parent_dir.join(format!("{}.rs", mod_name));
        if modern_path.exists() {
            return Some(modern_path);
        }

        // Try classic style: parent/mod_name/mod.rs
        let classic_path = parent_dir.join(mod_name).join("mod.rs");
        if classic_path.exists() {
            return Some(classic_path);
        }

        // Module file not found (could be in #[path = "..."] attribute)
        tracing::debug!(
            "Module '{}' not found in {} (tried {} and {})",
            mod_name,
            parent_dir.display(),
            modern_path.display(),
            classic_path.display()
        );
        None
    }

    #[allow(dead_code)]
    fn load_dir(
        _root: &Path,
        dir: &Path,
        files: &mut HashMap<PathBuf, PureFile>,
    ) -> Result<(), ProjectError> {
        if !dir.is_dir() {
            return Ok(());
        }

        let dir_name = dir.file_name().and_then(|n| n.to_str()).unwrap_or("");
        if matches!(
            dir_name,
            "target" | "node_modules" | ".git" | "dist" | "build"
        ) {
            return Ok(());
        }

        for entry in std::fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();

            if path.is_dir() {
                Self::load_dir(_root, &path, files)?;
            } else if path.extension().map(|e| e == "rs").unwrap_or(false) {
                match Self::load_file(&path) {
                    Ok(pure) => {
                        files.insert(path, pure);
                    }
                    Err(e) => {
                        tracing::warn!("Failed to parse {}: {}", path.display(), e);
                    }
                }
            }
        }

        Ok(())
    }

    fn load_file(path: &Path) -> Result<PureFile, ProjectError> {
        let content = std::fs::read_to_string(path)?;
        PureFile::from_source(&content).map_err(|e| ProjectError::Parse {
            path: path.to_path_buf(),
            message: e.to_string(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    fn create_test_project() -> tempfile::TempDir {
        let dir = tempdir().unwrap();
        let src = dir.path().join("src");
        fs::create_dir(&src).unwrap();

        // Create Cargo.toml (required for CargoMetadataProvider)
        fs::write(
            dir.path().join("Cargo.toml"),
            r#"[package]
name = "test-project"
version = "0.1.0"
edition = "2021"
"#,
        )
        .unwrap();

        fs::write(
            src.join("lib.rs"),
            r#"
pub fn hello() -> &'static str {
    "Hello, World!"
}
"#,
        )
        .unwrap();

        fs::write(
            src.join("main.rs"),
            r#"
fn main() {
    println!("{}", hello());
}
"#,
        )
        .unwrap();

        dir
    }

    #[test]
    fn test_load_project() {
        let dir = create_test_project();
        let project = Project::load(dir.path()).unwrap();

        // Project successfully loaded
        assert!(
            project.file_count() >= 1,
            "Expected at least 1 file, got {}",
            project.file_count()
        );
        assert!(project.workspace_root().exists());

        // Verify lib.rs is present (bin targets may not be loaded depending on cargo metadata)
        let lib_exists = project.file_paths().any(|p| p.ends_with("lib.rs"));
        assert!(lib_exists, "lib.rs not found in project");
    }

    #[test]
    fn test_get_file() {
        let dir = create_test_project();
        let project = Project::load(dir.path()).unwrap();

        // Use canonicalized path to handle macOS /var -> /private/var symlink
        let lib_path = dir.path().canonicalize().unwrap().join("src/lib.rs");
        assert!(project.get_file(&lib_path).is_some());
    }

    #[test]
    fn test_resolve_relative_path() {
        let dir = create_test_project();
        let project = Project::load(dir.path()).unwrap();

        // Should resolve relative path
        let relative = PathBuf::from("src/lib.rs");
        let resolved = project.resolve_path(&relative);
        assert!(resolved.is_some(), "Failed to resolve src/lib.rs");

        // Verify the resolved path exists in files
        if let Some(resolved_path) = resolved {
            assert!(
                project.files().contains_key(&resolved_path),
                "Resolved path not in files: {:?}",
                resolved_path
            );
        }
    }

    #[test]
    fn test_metadata_provider() {
        let dir = create_test_project();
        let project = Project::load(dir.path()).unwrap();

        // Check that metadata provider is available
        let metadata = project.metadata();
        assert_eq!(metadata.workspace_root(), project.workspace_root());

        // Check crate info
        let crates = metadata.all_crates();
        assert!(!crates.is_empty());
    }

    #[test]
    fn test_path_resolver() {
        let dir = create_test_project();
        let project = Project::load(dir.path()).unwrap();

        // Check that path resolver works
        let resolver = project.path_resolver();
        // Use canonicalized path to handle macOS /var -> /private/var symlink
        let absolute_path = dir.path().canonicalize().unwrap().join("src/lib.rs");
        let result = resolver.resolve(&absolute_path);
        assert!(result.is_ok());
    }

    #[test]
    fn test_load_files_static() {
        // Test that load_files() returns files without creating a Project instance
        let dir = create_test_project();
        let files = Project::load_files(dir.path()).unwrap();

        assert_eq!(files.len(), 2);
        assert!(files
            .values()
            .any(|f| f.to_source().unwrap().contains("hello")));
    }

    // Note: Context integration tests removed - they depend on old FileId-based API.
    // New tests should use WorkspaceFilePath-based API with AnalysisContext.files().
}