ggen-cli-lib 26.7.3

CLI interface for ggen
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
//! Project conventions resolver
//!
//! This module provides functionality for discovering and resolving project conventions
//! from the file system. It automatically detects RDF files, templates, SPARQL queries,
//! and output directories based on common patterns, with support for custom overrides
//! via `.ggen/conventions.toml`.
//!
//! ## Features
//!
//! - **Automatic Discovery**: Find RDF files, templates, and queries in standard locations
//! - **Convention Presets**: Support for presets like "clap-noun-verb" and "default"
//! - **Custom Overrides**: Override patterns via configuration file
//! - **File Watching**: Track directories for changes (for watch mode)
//!
//! ## Convention Structure
//!
//! Conventions define:
//! - RDF file patterns (e.g., `domain/**/*.ttl`)
//! - Template patterns (e.g., `templates/**/*.tmpl`)
//! - Query patterns (e.g., `queries/**/*.rq`)
//! - Output directory location
//!
//! ## Examples
//!
//! ### Resolving Conventions
//!
//! ```rust,no_run
//! use ggen_cli_lib::conventions::resolver::ConventionResolver;
//!
//! # fn main() -> ggen_core::utils::error::Result<()> {
//! let conventions = ConventionResolver::new(".").discover()?;
//! println!("Found {} RDF files", conventions.rdf_files.len());
//! println!("Found {} templates", conventions.templates.len());
//! # Ok(())
//! # }
//! ```

use ggen_core::utils::error::{Context, Result};
use glob::glob;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// Project conventions discovered from the file system
#[derive(Debug, Clone)]
pub struct ProjectConventions {
    /// RDF files discovered in domain/ directory
    pub rdf_files: Vec<PathBuf>,
    /// Base directory for RDF files (for watching)
    pub rdf_dir: PathBuf,
    /// Templates discovered in templates/ directory (name -> path)
    pub templates: HashMap<String, PathBuf>,
    /// Base directory for templates (for watching)
    pub templates_dir: PathBuf,
    /// SPARQL queries discovered in queries/ directory (name -> content)
    pub queries: HashMap<String, String>,
    /// Output directory for generated code
    pub output_dir: PathBuf,
    /// Convention preset name (e.g., "clap-noun-verb", "default")
    pub preset: String,
}

/// Convention overrides from .ggen/conventions.toml
#[derive(Debug, Clone, Deserialize, Serialize, Default)]
struct ConventionOverrides {
    #[serde(default)]
    rdf: RdfOverrides,
    #[serde(default)]
    templates: TemplatesOverrides,
    #[serde(default)]
    queries: QueriesOverrides,
    #[serde(default)]
    output: OutputOverrides,
}

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
struct RdfOverrides {
    #[serde(default)]
    patterns: Vec<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
struct TemplatesOverrides {
    #[serde(default)]
    patterns: Vec<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
struct QueriesOverrides {
    #[serde(default)]
    patterns: Vec<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize, Default)]
struct OutputOverrides {
    #[serde(default)]
    dir: Option<String>,
}

/// Convention resolver that discovers project structure
pub struct ConventionResolver {
    project_root: PathBuf,
}

impl ConventionResolver {
    /// Create a new convention resolver for the given project root
    pub fn new(project_root: impl Into<PathBuf>) -> Self {
        Self {
            project_root: project_root.into(),
        }
    }

    /// Discover project conventions by scanning the file system
    pub fn discover(&self) -> Result<ProjectConventions> {
        // Load overrides if they exist
        let overrides = self.load_overrides()?;

        // Discover RDF files
        let rdf_files = self.discover_rdf(&overrides)?;

        // Discover templates
        let templates = self.discover_templates(&overrides)?;

        // Discover queries
        let queries = self.discover_queries(&overrides)?;

        // Resolve output directory
        let output_dir = self.resolve_output_dir(&overrides);

        Ok(ProjectConventions {
            rdf_files,
            rdf_dir: self.project_root.join("domain"),
            templates,
            templates_dir: self.project_root.join("templates"),
            queries,
            output_dir,
            preset: "clap-noun-verb".to_string(), // Default preset
        })
    }

    /// Load convention overrides from .ggen/conventions.toml if it exists
    fn load_overrides(&self) -> Result<ConventionOverrides> {
        let override_path = self.project_root.join(".ggen").join("conventions.toml");

        if override_path.exists() {
            let content = std::fs::read_to_string(&override_path).map_err(|e| {
                ggen_core::utils::error::Error::new(&format!(
                    "Failed to read conventions.toml: {}",
                    e
                ))
            })?;
            let overrides: ConventionOverrides = Context::context(
                toml::from_str(&content).map_err(|e| {
                    ggen_core::utils::error::Error::new(&format!(
                        "Failed to parse conventions.toml: {}",
                        e
                    ))
                }),
                "Failed to parse conventions.toml",
            )?;
            Ok(overrides)
        } else {
            Ok(ConventionOverrides::default())
        }
    }

    /// Discover RDF files in domain/ directory
    fn discover_rdf(&self, overrides: &ConventionOverrides) -> Result<Vec<PathBuf>> {
        let patterns = if overrides.rdf.patterns.is_empty() {
            vec!["domain/**/*.ttl".to_string()]
        } else {
            overrides.rdf.patterns.clone()
        };

        let mut files = Vec::new();
        for pattern in patterns {
            let full_pattern = self.project_root.join(&pattern);
            for entry in glob(&full_pattern.to_string_lossy()).map_err(|e| {
                ggen_core::utils::error::Error::new(&format!(
                    "Failed to glob pattern {}: {}",
                    full_pattern.display(),
                    e
                ))
            })? {
                files.push(entry.map_err(|e| {
                    ggen_core::utils::error::Error::new(&format!(
                        "Failed to read glob entry: {}",
                        e
                    ))
                })?);
            }
        }

        // Sort alphabetically for deterministic order
        files.sort();

        Ok(files)
    }

    /// Discover templates in templates/ directory
    fn discover_templates(
        &self, overrides: &ConventionOverrides,
    ) -> Result<HashMap<String, PathBuf>> {
        let patterns = if overrides.templates.patterns.is_empty() {
            vec!["templates/**/*.tmpl".to_string()]
        } else {
            overrides.templates.patterns.clone()
        };

        let mut templates = HashMap::new();
        let templates_base = self.project_root.join("templates");

        for pattern in patterns {
            let full_pattern = self.project_root.join(&pattern);
            for entry in glob(&full_pattern.to_string_lossy()).map_err(|e| {
                ggen_core::utils::error::Error::new(&format!(
                    "Failed to glob pattern {}: {}",
                    full_pattern.display(),
                    e
                ))
            })? {
                let path = entry.map_err(|e| {
                    ggen_core::utils::error::Error::new(&format!(
                        "Failed to read glob entry: {}",
                        e
                    ))
                })?;

                // Convert nested path to template name
                // e.g., templates/api/user.tmpl -> api/user
                let name = if let Ok(rel_path) = path.strip_prefix(&templates_base) {
                    rel_path
                        .with_extension("") // Remove .tmpl extension
                        .to_string_lossy()
                        .to_string()
                } else {
                    // Fallback: use file stem with proper error handling
                    match path.file_stem().and_then(|s| s.to_str()) {
                        Some(stem) => stem.to_string(),
                        None => {
                            log::warn!(
                                "Could not extract template name from path: {}",
                                path.display()
                            );
                            continue; // Skip templates with invalid names
                        }
                    }
                };

                templates.insert(name, path);
            }
        }

        Ok(templates)
    }

    /// Discover SPARQL queries in queries/ directory
    fn discover_queries(&self, overrides: &ConventionOverrides) -> Result<HashMap<String, String>> {
        let patterns = if overrides.queries.patterns.is_empty() {
            vec!["queries/**/*.sparql".to_string()]
        } else {
            overrides.queries.patterns.clone()
        };

        let mut queries = HashMap::new();
        let queries_base = self.project_root.join("queries");

        for pattern in patterns {
            let full_pattern = self.project_root.join(&pattern);
            for entry in glob(&full_pattern.to_string_lossy()).map_err(|e| {
                ggen_core::utils::error::Error::new(&format!(
                    "Failed to glob pattern {}: {}",
                    full_pattern.display(),
                    e
                ))
            })? {
                let path = entry.map_err(|e| {
                    ggen_core::utils::error::Error::new(&format!(
                        "Failed to read glob entry: {}",
                        e
                    ))
                })?;

                // Read query content
                let content = Context::with_context(
                    std::fs::read_to_string(&path).map_err(|e| {
                        ggen_core::utils::error::Error::new(&format!(
                            "Failed to read query file {}: {}",
                            path.display(),
                            e
                        ))
                    }),
                    || format!("Failed to read query file: {}", path.display()),
                )?;

                // Convert nested path to query name
                // e.g., queries/user/find.sparql -> user/find
                let name = if let Ok(rel_path) = path.strip_prefix(&queries_base) {
                    rel_path
                        .with_extension("") // Remove .sparql extension
                        .to_string_lossy()
                        .to_string()
                } else {
                    // Fallback: use file stem with proper error handling
                    match path.file_stem().and_then(|s| s.to_str()) {
                        Some(stem) => stem.to_string(),
                        None => {
                            log::warn!(
                                "Could not extract query name from path: {}",
                                path.display()
                            );
                            continue; // Skip queries with invalid names
                        }
                    }
                };

                queries.insert(name, content);
            }
        }

        Ok(queries)
    }

    /// Resolve output directory (default: project root)
    fn resolve_output_dir(&self, overrides: &ConventionOverrides) -> PathBuf {
        if let Some(ref dir) = overrides.output.dir {
            self.project_root.join(dir)
        } else {
            self.project_root.clone()
        }
    }
}

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

    fn setup_test_project() -> TempDir {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();

        // Create directory structure
        fs::create_dir_all(root.join("domain")).unwrap();
        fs::create_dir_all(root.join("templates/api")).unwrap();
        fs::create_dir_all(root.join("queries/user")).unwrap();

        // Create RDF files
        fs::write(
            root.join("domain/user.ttl"),
            "@prefix ex: <http://example.org/> .",
        )
        .unwrap();
        fs::write(
            root.join("domain/order.ttl"),
            "@prefix ex: <http://example.org/> .",
        )
        .unwrap();

        // Create template files
        fs::write(root.join("templates/main.tmpl"), "Hello {{ name }}").unwrap();
        fs::write(root.join("templates/api/user.tmpl"), "User API").unwrap();

        // Create query files
        fs::write(
            root.join("queries/user/find.sparql"),
            "SELECT * WHERE { ?s ?p ?o }",
        )
        .unwrap();

        temp_dir
    }

    #[test]
    fn test_new() {
        let temp_dir = TempDir::new().unwrap();
        let resolver = ConventionResolver::new(temp_dir.path());

        assert_eq!(resolver.project_root, temp_dir.path());
    }

    #[test]
    fn test_discover_rdf_files() {
        let temp_dir = setup_test_project();
        let resolver = ConventionResolver::new(temp_dir.path());

        let conventions = resolver.discover().unwrap();

        assert_eq!(conventions.rdf_files.len(), 2);
        assert!(conventions
            .rdf_files
            .iter()
            .any(|p| p.ends_with("user.ttl")));
        assert!(conventions
            .rdf_files
            .iter()
            .any(|p| p.ends_with("order.ttl")));

        // Verify alphabetical order
        assert!(conventions.rdf_files[0].ends_with("order.ttl"));
        assert!(conventions.rdf_files[1].ends_with("user.ttl"));
    }

    #[test]
    fn test_discover_templates() {
        let temp_dir = setup_test_project();
        let resolver = ConventionResolver::new(temp_dir.path());

        let conventions = resolver.discover().unwrap();

        assert_eq!(conventions.templates.len(), 2);
        assert!(conventions.templates.contains_key("main"));
        assert!(conventions.templates.contains_key("api/user"));

        let main_path = &conventions.templates["main"];
        assert!(main_path.ends_with("templates/main.tmpl"));
    }

    #[test]
    fn test_discover_queries() {
        let temp_dir = setup_test_project();
        let resolver = ConventionResolver::new(temp_dir.path());

        let conventions = resolver.discover().unwrap();

        assert_eq!(conventions.queries.len(), 1);
        assert!(conventions.queries.contains_key("user/find"));

        let query = &conventions.queries["user/find"];
        assert!(query.contains("SELECT * WHERE"));
    }

    #[test]
    fn test_resolve_output_dir_default() {
        let temp_dir = TempDir::new().unwrap();
        let resolver = ConventionResolver::new(temp_dir.path());

        let conventions = resolver.discover().unwrap();

        assert_eq!(conventions.output_dir, temp_dir.path());
    }

    #[test]
    fn test_resolve_output_dir_override() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();

        // Create .ggen directory and conventions.toml
        fs::create_dir_all(root.join(".ggen")).unwrap();
        fs::write(
            root.join(".ggen/conventions.toml"),
            r#"
[output]
dir = "build/generated"
"#,
        )
        .unwrap();

        let resolver = ConventionResolver::new(root);
        let conventions = resolver.discover().unwrap();

        assert_eq!(conventions.output_dir, root.join("build/generated"));
    }

    #[test]
    fn test_override_rdf_patterns() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();

        // Create custom RDF location
        fs::create_dir_all(root.join("ontology")).unwrap();
        fs::write(
            root.join("ontology/custom.ttl"),
            "@prefix ex: <http://example.org/> .",
        )
        .unwrap();

        // Create override config
        fs::create_dir_all(root.join(".ggen")).unwrap();
        fs::write(
            root.join(".ggen/conventions.toml"),
            r#"
[rdf]
patterns = ["ontology/**/*.ttl"]
"#,
        )
        .unwrap();

        let resolver = ConventionResolver::new(root);
        let conventions = resolver.discover().unwrap();

        assert_eq!(conventions.rdf_files.len(), 1);
        assert!(conventions.rdf_files[0].ends_with("custom.ttl"));
    }

    #[test]
    fn test_override_template_patterns() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();

        // Create custom template location
        fs::create_dir_all(root.join("views")).unwrap();
        fs::write(root.join("views/page.tmpl"), "Page template").unwrap();

        // Create override config
        fs::create_dir_all(root.join(".ggen")).unwrap();
        fs::write(
            root.join(".ggen/conventions.toml"),
            r#"
[templates]
patterns = ["views/**/*.tmpl"]
"#,
        )
        .unwrap();

        let resolver = ConventionResolver::new(root);
        let conventions = resolver.discover().unwrap();

        assert_eq!(conventions.templates.len(), 1);
        // The template name will be just "page" since views is not recognized as templates base
        assert!(conventions
            .templates
            .values()
            .any(|p| p.ends_with("page.tmpl")));
    }

    #[test]
    fn test_override_query_patterns() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();

        // Create custom query location
        fs::create_dir_all(root.join("sparql")).unwrap();
        fs::write(
            root.join("sparql/select.sparql"),
            "SELECT * WHERE { ?s ?p ?o }",
        )
        .unwrap();

        // Create override config
        fs::create_dir_all(root.join(".ggen")).unwrap();
        fs::write(
            root.join(".ggen/conventions.toml"),
            r#"
[queries]
patterns = ["sparql/**/*.sparql"]
"#,
        )
        .unwrap();

        let resolver = ConventionResolver::new(root);
        let conventions = resolver.discover().unwrap();

        assert_eq!(conventions.queries.len(), 1);
        assert!(conventions
            .queries
            .values()
            .any(|c| c.contains("SELECT * WHERE")));
    }

    #[test]
    fn test_empty_project() {
        let temp_dir = TempDir::new().unwrap();
        let resolver = ConventionResolver::new(temp_dir.path());

        let conventions = resolver.discover().unwrap();

        assert!(conventions.rdf_files.is_empty());
        assert!(conventions.templates.is_empty());
        assert!(conventions.queries.is_empty());
        assert_eq!(conventions.output_dir, temp_dir.path());
    }

    #[test]
    fn test_nested_template_names() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();

        // Create nested template structure
        fs::create_dir_all(root.join("templates/api/v1")).unwrap();
        fs::write(root.join("templates/api/v1/user.tmpl"), "User API").unwrap();

        let resolver = ConventionResolver::new(root);
        let conventions = resolver.discover().unwrap();

        assert_eq!(conventions.templates.len(), 1);
        assert!(conventions.templates.contains_key("api/v1/user"));
    }

    #[test]
    fn test_load_overrides_invalid_toml() {
        let temp_dir = TempDir::new().unwrap();
        let root = temp_dir.path();

        // Create invalid TOML
        fs::create_dir_all(root.join(".ggen")).unwrap();
        fs::write(
            root.join(".ggen/conventions.toml"),
            "invalid toml content [[[",
        )
        .unwrap();

        let resolver = ConventionResolver::new(root);

        // Should return an error
        assert!(resolver.discover().is_err());
    }
}