quillmark_core/
quill.rs

1//! Quill template bundle types and implementations.
2
3use std::collections::HashMap;
4use std::error::Error as StdError;
5use std::path::{Path, PathBuf};
6
7use crate::schema::build_schema_from_fields;
8use crate::value::QuillValue;
9
10/// UI-specific metadata for field rendering
11#[derive(Debug, Clone, PartialEq)]
12pub struct UiSchema {
13    /// Group name for organizing fields (e.g., "Personal Info", "Preferences")
14    pub group: Option<String>,
15    /// Short tooltip text for the field (concise hint, unlike verbose description)
16    pub tooltip: Option<String>,
17    /// Order of the field in the UI (automatically generated based on field position in Quill.toml)
18    pub order: Option<i32>,
19}
20
21/// Schema definition for a template field
22#[derive(Debug, Clone, PartialEq)]
23pub struct FieldSchema {
24    pub name: String,
25    /// Field type hint (e.g., "string", "number", "boolean", "object", "array")
26    pub r#type: Option<String>,
27    /// Description of the field
28    pub description: String,
29    /// Default value for the field
30    pub default: Option<QuillValue>,
31    /// Example value for the field
32    pub example: Option<QuillValue>,
33    /// Example values for the field
34    pub examples: Option<QuillValue>,
35    /// UI-specific metadata for rendering
36    pub ui: Option<UiSchema>,
37}
38
39impl FieldSchema {
40    /// Create a new FieldSchema with default values
41    pub fn new(name: String, description: String) -> Self {
42        Self {
43            name,
44            r#type: None,
45            description,
46            default: None,
47            example: None,
48            examples: None,
49            ui: None,
50        }
51    }
52
53    /// Parse a FieldSchema from a QuillValue
54    pub fn from_quill_value(key: String, value: &QuillValue) -> Result<Self, String> {
55        let obj = value
56            .as_object()
57            .ok_or_else(|| "Field schema must be an object".to_string())?;
58
59        //Ensure only known keys are present
60        for key in obj.keys() {
61            match key.as_str() {
62                "name" | "type" | "description" | "example" | "default" | "ui" => {}
63                _ => {
64                    // Log warning but don't fail
65                    eprintln!("Warning: Unknown key '{}' in field schema", key);
66                }
67            }
68        }
69
70        let name = key.clone();
71
72        let description = obj
73            .get("description")
74            .and_then(|v| v.as_str())
75            .unwrap_or("")
76            .to_string();
77
78        let field_type = obj
79            .get("type")
80            .and_then(|v| v.as_str())
81            .map(|s| s.to_string());
82
83        let default = obj.get("default").map(|v| QuillValue::from_json(v.clone()));
84
85        let example = obj.get("example").map(|v| QuillValue::from_json(v.clone()));
86
87        let examples = obj
88            .get("examples")
89            .map(|v| QuillValue::from_json(v.clone()));
90
91        // Parse UI metadata if present
92        let ui = if let Some(ui_value) = obj.get("ui") {
93            if let Some(ui_obj) = ui_value.as_object() {
94                let group = ui_obj
95                    .get("group")
96                    .and_then(|v| v.as_str())
97                    .map(|s| s.to_string());
98
99                let tooltip = ui_obj
100                    .get("tooltip")
101                    .and_then(|v| v.as_str())
102                    .map(|s| s.to_string());
103
104                // Validate that only known UI properties are present
105                for key in ui_obj.keys() {
106                    match key.as_str() {
107                        "group" | "tooltip" => {}
108                        _ => {
109                            // Log warning but don't fail
110                            eprintln!("Warning: Unknown UI property '{}'. Only 'group' and 'tooltip' are supported.", key);
111                        }
112                    }
113                }
114
115                Some(UiSchema {
116                    group,
117                    tooltip,
118                    order: None, // Order is determined by position in Quill.toml
119                })
120            } else {
121                return Err("UI field must be an object".to_string());
122            }
123        } else {
124            None
125        };
126
127        Ok(Self {
128            name,
129            r#type: field_type,
130            description,
131            default,
132            example,
133            examples,
134            ui,
135        })
136    }
137}
138
139/// A node in the file tree structure
140#[derive(Debug, Clone)]
141pub enum FileTreeNode {
142    /// A file with its contents
143    File {
144        /// The file contents as bytes or UTF-8 string
145        contents: Vec<u8>,
146    },
147    /// A directory containing other files and directories
148    Directory {
149        /// The files and subdirectories in this directory
150        files: HashMap<String, FileTreeNode>,
151    },
152}
153
154impl FileTreeNode {
155    /// Get a file or directory node by path
156    pub fn get_node<P: AsRef<Path>>(&self, path: P) -> Option<&FileTreeNode> {
157        let path = path.as_ref();
158
159        // Handle root path
160        if path == Path::new("") {
161            return Some(self);
162        }
163
164        // Split path into components
165        let components: Vec<_> = path
166            .components()
167            .filter_map(|c| {
168                if let std::path::Component::Normal(s) = c {
169                    s.to_str()
170                } else {
171                    None
172                }
173            })
174            .collect();
175
176        if components.is_empty() {
177            return Some(self);
178        }
179
180        // Navigate through the tree
181        let mut current_node = self;
182        for component in components {
183            match current_node {
184                FileTreeNode::Directory { files } => {
185                    current_node = files.get(component)?;
186                }
187                FileTreeNode::File { .. } => {
188                    return None; // Can't traverse into a file
189                }
190            }
191        }
192
193        Some(current_node)
194    }
195
196    /// Get file contents by path
197    pub fn get_file<P: AsRef<Path>>(&self, path: P) -> Option<&[u8]> {
198        match self.get_node(path)? {
199            FileTreeNode::File { contents } => Some(contents.as_slice()),
200            FileTreeNode::Directory { .. } => None,
201        }
202    }
203
204    /// Check if a file exists at the given path
205    pub fn file_exists<P: AsRef<Path>>(&self, path: P) -> bool {
206        matches!(self.get_node(path), Some(FileTreeNode::File { .. }))
207    }
208
209    /// Check if a directory exists at the given path
210    pub fn dir_exists<P: AsRef<Path>>(&self, path: P) -> bool {
211        matches!(self.get_node(path), Some(FileTreeNode::Directory { .. }))
212    }
213
214    /// List all files in a directory (non-recursive)
215    pub fn list_files<P: AsRef<Path>>(&self, dir_path: P) -> Vec<String> {
216        match self.get_node(dir_path) {
217            Some(FileTreeNode::Directory { files }) => files
218                .iter()
219                .filter_map(|(name, node)| {
220                    if matches!(node, FileTreeNode::File { .. }) {
221                        Some(name.clone())
222                    } else {
223                        None
224                    }
225                })
226                .collect(),
227            _ => Vec::new(),
228        }
229    }
230
231    /// List all subdirectories in a directory (non-recursive)
232    pub fn list_subdirectories<P: AsRef<Path>>(&self, dir_path: P) -> Vec<String> {
233        match self.get_node(dir_path) {
234            Some(FileTreeNode::Directory { files }) => files
235                .iter()
236                .filter_map(|(name, node)| {
237                    if matches!(node, FileTreeNode::Directory { .. }) {
238                        Some(name.clone())
239                    } else {
240                        None
241                    }
242                })
243                .collect(),
244            _ => Vec::new(),
245        }
246    }
247
248    /// Insert a file or directory at the given path
249    pub fn insert<P: AsRef<Path>>(
250        &mut self,
251        path: P,
252        node: FileTreeNode,
253    ) -> Result<(), Box<dyn StdError + Send + Sync>> {
254        let path = path.as_ref();
255
256        // Split path into components
257        let components: Vec<_> = path
258            .components()
259            .filter_map(|c| {
260                if let std::path::Component::Normal(s) = c {
261                    s.to_str().map(|s| s.to_string())
262                } else {
263                    None
264                }
265            })
266            .collect();
267
268        if components.is_empty() {
269            return Err("Cannot insert at root path".into());
270        }
271
272        // Navigate to parent directory, creating directories as needed
273        let mut current_node = self;
274        for component in &components[..components.len() - 1] {
275            match current_node {
276                FileTreeNode::Directory { files } => {
277                    current_node =
278                        files
279                            .entry(component.clone())
280                            .or_insert_with(|| FileTreeNode::Directory {
281                                files: HashMap::new(),
282                            });
283                }
284                FileTreeNode::File { .. } => {
285                    return Err("Cannot traverse into a file".into());
286                }
287            }
288        }
289
290        // Insert the new node
291        let filename = &components[components.len() - 1];
292        match current_node {
293            FileTreeNode::Directory { files } => {
294                files.insert(filename.clone(), node);
295                Ok(())
296            }
297            FileTreeNode::File { .. } => Err("Cannot insert into a file".into()),
298        }
299    }
300
301    /// Parse a tree structure from JSON value
302    fn from_json_value(value: &serde_json::Value) -> Result<Self, Box<dyn StdError + Send + Sync>> {
303        if let Some(contents_str) = value.get("contents").and_then(|v| v.as_str()) {
304            // It's a file with string contents
305            Ok(FileTreeNode::File {
306                contents: contents_str.as_bytes().to_vec(),
307            })
308        } else if let Some(bytes_array) = value.get("contents").and_then(|v| v.as_array()) {
309            // It's a file with byte array contents
310            let contents: Vec<u8> = bytes_array
311                .iter()
312                .filter_map(|v| v.as_u64().and_then(|n| u8::try_from(n).ok()))
313                .collect();
314            Ok(FileTreeNode::File { contents })
315        } else if let Some(obj) = value.as_object() {
316            // It's a directory (either empty or with nested files)
317            let mut files = HashMap::new();
318            for (name, child_value) in obj {
319                files.insert(name.clone(), Self::from_json_value(child_value)?);
320            }
321            // Empty directories are valid
322            Ok(FileTreeNode::Directory { files })
323        } else {
324            Err(format!("Invalid file tree node: {:?}", value).into())
325        }
326    }
327
328    pub fn print_tree(&self) -> String {
329        self.__print_tree("", "", true)
330    }
331
332    pub fn __print_tree(&self, name: &str, prefix: &str, is_last: bool) -> String {
333        let mut result = String::new();
334
335        // Choose the appropriate tree characters
336        let connector = if is_last { "└── " } else { "├── " };
337        let extension = if is_last { "    " } else { "│   " };
338
339        match self {
340            FileTreeNode::File { .. } => {
341                result.push_str(&format!("{}{}{}\n", prefix, connector, name));
342            }
343            FileTreeNode::Directory { files } => {
344                // Add trailing slash for directories like `tree` does
345                result.push_str(&format!("{}{}{}/\n", prefix, connector, name));
346
347                let child_prefix = format!("{}{}", prefix, extension);
348                let count = files.len();
349
350                for (i, (child_name, node)) in files.iter().enumerate() {
351                    let is_last_child = i == count - 1;
352                    result.push_str(&node.__print_tree(child_name, &child_prefix, is_last_child));
353                }
354            }
355        }
356
357        result
358    }
359}
360
361/// Simple gitignore-style pattern matcher for .quillignore
362#[derive(Debug, Clone)]
363pub struct QuillIgnore {
364    patterns: Vec<String>,
365}
366
367impl QuillIgnore {
368    /// Create a new QuillIgnore from pattern strings
369    pub fn new(patterns: Vec<String>) -> Self {
370        Self { patterns }
371    }
372
373    /// Parse .quillignore content into patterns
374    pub fn from_content(content: &str) -> Self {
375        let patterns = content
376            .lines()
377            .map(|line| line.trim())
378            .filter(|line| !line.is_empty() && !line.starts_with('#'))
379            .map(|line| line.to_string())
380            .collect();
381        Self::new(patterns)
382    }
383
384    /// Check if a path should be ignored
385    pub fn is_ignored<P: AsRef<Path>>(&self, path: P) -> bool {
386        let path = path.as_ref();
387        let path_str = path.to_string_lossy();
388
389        for pattern in &self.patterns {
390            if self.matches_pattern(pattern, &path_str) {
391                return true;
392            }
393        }
394        false
395    }
396
397    /// Simple pattern matching (supports * wildcard and directory patterns)
398    fn matches_pattern(&self, pattern: &str, path: &str) -> bool {
399        // Handle directory patterns
400        if pattern.ends_with('/') {
401            let pattern_prefix = &pattern[..pattern.len() - 1];
402            return path.starts_with(pattern_prefix)
403                && (path.len() == pattern_prefix.len()
404                    || path.chars().nth(pattern_prefix.len()) == Some('/'));
405        }
406
407        // Handle exact matches
408        if !pattern.contains('*') {
409            return path == pattern || path.ends_with(&format!("/{}", pattern));
410        }
411
412        // Simple wildcard matching
413        if pattern == "*" {
414            return true;
415        }
416
417        // Handle patterns with wildcards
418        let pattern_parts: Vec<&str> = pattern.split('*').collect();
419        if pattern_parts.len() == 2 {
420            let (prefix, suffix) = (pattern_parts[0], pattern_parts[1]);
421            if prefix.is_empty() {
422                return path.ends_with(suffix);
423            } else if suffix.is_empty() {
424                return path.starts_with(prefix);
425            } else {
426                return path.starts_with(prefix) && path.ends_with(suffix);
427            }
428        }
429
430        false
431    }
432}
433
434/// A quill template bundle.
435#[derive(Debug, Clone)]
436pub struct Quill {
437    /// Quill-specific metadata
438    pub metadata: HashMap<String, QuillValue>,
439    /// Name of the quill
440    pub name: String,
441    /// Backend identifier (e.g., "typst")
442    pub backend: String,
443    /// Plate template content (optional)
444    pub plate: Option<String>,
445    /// Markdown template content (optional)
446    pub example: Option<String>,
447    /// Field JSON schema (single source of truth for schema and defaults)
448    pub schema: QuillValue,
449    /// Cached default values extracted from schema (for performance)
450    pub defaults: HashMap<String, QuillValue>,
451    /// Cached example values extracted from schema (for performance)
452    pub examples: HashMap<String, Vec<QuillValue>>,
453    /// In-memory file system (tree structure)
454    pub files: FileTreeNode,
455}
456
457/// Quill configuration extracted from Quill.toml
458#[derive(Debug, Clone)]
459pub struct QuillConfig {
460    /// Human-readable name
461    pub name: String,
462    /// Description of the quill
463    pub description: String,
464    /// Backend identifier (e.g., "typst")
465    pub backend: String,
466    /// Semantic version of the quill
467    pub version: Option<String>,
468    /// Author of the quill
469    pub author: Option<String>,
470    /// Example markdown file
471    pub example_file: Option<String>,
472    /// Plate file
473    pub plate_file: Option<String>,
474    /// Field schemas
475    pub fields: HashMap<String, FieldSchema>,
476    /// Additional metadata from [Quill] section (excluding standard fields)
477    pub metadata: HashMap<String, QuillValue>,
478    /// Typst-specific configuration from `[typst]` section
479    pub typst_config: HashMap<String, QuillValue>,
480}
481
482impl QuillConfig {
483    /// Parse QuillConfig from TOML content
484    pub fn from_toml(toml_content: &str) -> Result<Self, Box<dyn StdError + Send + Sync>> {
485        let quill_toml: toml::Value = toml::from_str(toml_content)
486            .map_err(|e| format!("Failed to parse Quill.toml: {}", e))?;
487
488        // Parse with toml_edit to get field order
489        let field_order: Vec<String> = toml_content
490            .parse::<toml_edit::DocumentMut>()
491            .ok()
492            .and_then(|doc| {
493                doc.get("fields")
494                    .and_then(|item| item.as_table())
495                    .map(|table| table.iter().map(|(k, _)| k.to_string()).collect())
496            })
497            .unwrap_or_default();
498
499        // Extract [Quill] section (required)
500        let quill_section = quill_toml
501            .get("Quill")
502            .ok_or("Missing required [Quill] section in Quill.toml")?;
503
504        // Extract required fields
505        let name = quill_section
506            .get("name")
507            .and_then(|v| v.as_str())
508            .ok_or("Missing required 'name' field in [Quill] section")?
509            .to_string();
510
511        let backend = quill_section
512            .get("backend")
513            .and_then(|v| v.as_str())
514            .ok_or("Missing required 'backend' field in [Quill] section")?
515            .to_string();
516
517        let description = quill_section
518            .get("description")
519            .and_then(|v| v.as_str())
520            .ok_or("Missing required 'description' field in [Quill] section")?;
521
522        if description.trim().is_empty() {
523            return Err("'description' field in [Quill] section cannot be empty".into());
524        }
525        let description = description.to_string();
526
527        // Extract optional fields
528        let version = quill_section
529            .get("version")
530            .and_then(|v| v.as_str())
531            .map(|s| s.to_string());
532
533        let author = quill_section
534            .get("author")
535            .and_then(|v| v.as_str())
536            .map(|s| s.to_string());
537
538        let example_file = quill_section
539            .get("example_file")
540            .and_then(|v| v.as_str())
541            .map(|s| s.to_string());
542
543        let plate_file = quill_section
544            .get("plate_file")
545            .and_then(|v| v.as_str())
546            .map(|s| s.to_string());
547
548        // Extract additional metadata from [Quill] section (excluding standard fields)
549        let mut metadata = HashMap::new();
550        if let toml::Value::Table(table) = quill_section {
551            for (key, value) in table {
552                // Skip standard fields that are stored in dedicated struct fields
553                if key != "name"
554                    && key != "backend"
555                    && key != "description"
556                    && key != "version"
557                    && key != "author"
558                    && key != "example_file"
559                    && key != "plate_file"
560                {
561                    match QuillValue::from_toml(value) {
562                        Ok(quill_value) => {
563                            metadata.insert(key.clone(), quill_value);
564                        }
565                        Err(e) => {
566                            eprintln!("Warning: Failed to convert field '{}': {}", key, e);
567                        }
568                    }
569                }
570            }
571        }
572
573        // Extract [typst] section (optional)
574        let mut typst_config = HashMap::new();
575        if let Some(typst_section) = quill_toml.get("typst") {
576            if let toml::Value::Table(table) = typst_section {
577                for (key, value) in table {
578                    match QuillValue::from_toml(value) {
579                        Ok(quill_value) => {
580                            typst_config.insert(key.clone(), quill_value);
581                        }
582                        Err(e) => {
583                            eprintln!("Warning: Failed to convert typst field '{}': {}", key, e);
584                        }
585                    }
586                }
587            }
588        }
589
590        // Extract [fields] section (optional)
591        let mut fields = HashMap::new();
592        if let Some(fields_section) = quill_toml.get("fields") {
593            if let toml::Value::Table(fields_table) = fields_section {
594                let mut order_counter = 0;
595                for (field_name, field_schema) in fields_table {
596                    // Determine order
597                    let order = if let Some(idx) = field_order.iter().position(|k| k == field_name)
598                    {
599                        idx as i32
600                    } else {
601                        let o = field_order.len() as i32 + order_counter;
602                        order_counter += 1;
603                        o
604                    };
605
606                    match QuillValue::from_toml(field_schema) {
607                        Ok(quill_value) => {
608                            match FieldSchema::from_quill_value(field_name.clone(), &quill_value) {
609                                Ok(mut schema) => {
610                                    // Always set ui.order based on position in Quill.toml
611                                    if schema.ui.is_none() {
612                                        schema.ui = Some(UiSchema {
613                                            group: None,
614                                            tooltip: None,
615                                            order: Some(order),
616                                        });
617                                    } else if let Some(ui) = &mut schema.ui {
618                                        ui.order = Some(order);
619                                    }
620
621                                    fields.insert(field_name.clone(), schema);
622                                }
623                                Err(e) => {
624                                    eprintln!(
625                                        "Warning: Failed to parse field schema '{}': {}",
626                                        field_name, e
627                                    );
628                                }
629                            }
630                        }
631                        Err(e) => {
632                            eprintln!(
633                                "Warning: Failed to convert field schema '{}': {}",
634                                field_name, e
635                            );
636                        }
637                    }
638                }
639            }
640        }
641
642        Ok(QuillConfig {
643            name,
644            description,
645            backend,
646            version,
647            author,
648            example_file,
649            plate_file,
650            fields,
651            metadata,
652            typst_config,
653        })
654    }
655}
656
657impl Quill {
658    /// Create a Quill from a directory path
659    pub fn from_path<P: AsRef<std::path::Path>>(
660        path: P,
661    ) -> Result<Self, Box<dyn StdError + Send + Sync>> {
662        use std::fs;
663
664        let path = path.as_ref();
665        let name = path
666            .file_name()
667            .and_then(|n| n.to_str())
668            .unwrap_or("unnamed")
669            .to_string();
670
671        // Load .quillignore if it exists
672        let quillignore_path = path.join(".quillignore");
673        let ignore = if quillignore_path.exists() {
674            let ignore_content = fs::read_to_string(&quillignore_path)
675                .map_err(|e| format!("Failed to read .quillignore: {}", e))?;
676            QuillIgnore::from_content(&ignore_content)
677        } else {
678            // Default ignore patterns
679            QuillIgnore::new(vec![
680                ".git/".to_string(),
681                ".gitignore".to_string(),
682                ".quillignore".to_string(),
683                "target/".to_string(),
684                "node_modules/".to_string(),
685            ])
686        };
687
688        // Load all files into a tree structure
689        let root = Self::load_directory_as_tree(path, path, &ignore)?;
690
691        // Create Quill from the file tree
692        Self::from_tree(root, Some(name))
693    }
694
695    /// Create a Quill from a tree structure
696    ///
697    /// This is the authoritative method for creating a Quill from an in-memory file tree.
698    ///
699    /// # Arguments
700    ///
701    /// * `root` - The root node of the file tree
702    /// * `_default_name` - Unused parameter kept for API compatibility (name always from Quill.toml)
703    ///
704    /// # Errors
705    ///
706    /// Returns an error if:
707    /// - Quill.toml is not found in the file tree
708    /// - Quill.toml is not valid UTF-8 or TOML
709    /// - The plate file specified in Quill.toml is not found or not valid UTF-8
710    /// - Validation fails
711    pub fn from_tree(
712        root: FileTreeNode,
713        _default_name: Option<String>,
714    ) -> Result<Self, Box<dyn StdError + Send + Sync>> {
715        // Read Quill.toml
716        let quill_toml_bytes = root
717            .get_file("Quill.toml")
718            .ok_or("Quill.toml not found in file tree")?;
719
720        let quill_toml_content = String::from_utf8(quill_toml_bytes.to_vec())
721            .map_err(|e| format!("Quill.toml is not valid UTF-8: {}", e))?;
722
723        // Parse TOML into QuillConfig
724        let config = QuillConfig::from_toml(&quill_toml_content)?;
725
726        // Construct Quill from QuillConfig
727        Self::from_config(config, root)
728    }
729
730    /// Create a Quill from a QuillConfig and file tree
731    ///
732    /// This method constructs a Quill from a parsed QuillConfig and validates
733    /// all file references.
734    ///
735    /// # Arguments
736    ///
737    /// * `config` - The parsed QuillConfig
738    /// * `root` - The root node of the file tree
739    ///
740    /// # Errors
741    ///
742    /// Returns an error if:
743    /// - The plate file specified in config is not found or not valid UTF-8
744    /// - The example file specified in config is not found or not valid UTF-8
745    /// - Schema generation fails
746    fn from_config(
747        config: QuillConfig,
748        root: FileTreeNode,
749    ) -> Result<Self, Box<dyn StdError + Send + Sync>> {
750        // Build metadata from config
751        let mut metadata = config.metadata.clone();
752
753        // Add backend to metadata
754        metadata.insert(
755            "backend".to_string(),
756            QuillValue::from_json(serde_json::Value::String(config.backend.clone())),
757        );
758
759        // Add description to metadata
760        metadata.insert(
761            "description".to_string(),
762            QuillValue::from_json(serde_json::Value::String(config.description.clone())),
763        );
764
765        // Add author if present
766        if let Some(ref author) = config.author {
767            metadata.insert(
768                "author".to_string(),
769                QuillValue::from_json(serde_json::Value::String(author.clone())),
770            );
771        }
772
773        // Add typst config to metadata with typst_ prefix
774        for (key, value) in &config.typst_config {
775            metadata.insert(format!("typst_{}", key), value.clone());
776        }
777
778        // Build JSON schema from field schemas
779        let schema = build_schema_from_fields(&config.fields)
780            .map_err(|e| format!("Failed to build JSON schema from field schemas: {}", e))?;
781
782        // Read the plate content from plate file (if specified)
783        let plate_content: Option<String> = if let Some(ref plate_file_name) = config.plate_file {
784            let plate_bytes = root.get_file(plate_file_name).ok_or_else(|| {
785                format!("Plate file '{}' not found in file tree", plate_file_name)
786            })?;
787
788            let content = String::from_utf8(plate_bytes.to_vec()).map_err(|e| {
789                format!("Plate file '{}' is not valid UTF-8: {}", plate_file_name, e)
790            })?;
791            Some(content)
792        } else {
793            // No plate file specified
794            None
795        };
796
797        // Read the markdown example content if specified
798        let example_content = if let Some(ref example_file_name) = config.example_file {
799            root.get_file(example_file_name).and_then(|bytes| {
800                String::from_utf8(bytes.to_vec())
801                    .map_err(|e| {
802                        eprintln!(
803                            "Warning: Example file '{}' is not valid UTF-8: {}",
804                            example_file_name, e
805                        );
806                        e
807                    })
808                    .ok()
809            })
810        } else {
811            None
812        };
813
814        // Extract and cache defaults and examples from schema for performance
815        let defaults = crate::schema::extract_defaults_from_schema(&schema);
816        let examples = crate::schema::extract_examples_from_schema(&schema);
817
818        let quill = Quill {
819            metadata,
820            name: config.name,
821            backend: config.backend,
822            plate: plate_content,
823            example: example_content,
824            schema,
825            defaults,
826            examples: examples,
827            files: root,
828        };
829
830        Ok(quill)
831    }
832
833    /// Create a Quill from a JSON representation
834    ///
835    /// Parses a JSON string into an in-memory file tree and validates it. The
836    /// precise JSON contract is documented in `designs/QUILL.md`.
837    /// The JSON format MUST have a root object with a `files` key. The optional
838    /// `metadata` key provides additional metadata that overrides defaults.
839    pub fn from_json(json_str: &str) -> Result<Self, Box<dyn StdError + Send + Sync>> {
840        use serde_json::Value as JsonValue;
841
842        let json: JsonValue =
843            serde_json::from_str(json_str).map_err(|e| format!("Failed to parse JSON: {}", e))?;
844
845        let obj = json.as_object().ok_or_else(|| "Root must be an object")?;
846
847        // Extract metadata (optional)
848        let default_name = obj
849            .get("metadata")
850            .and_then(|m| m.get("name"))
851            .and_then(|v| v.as_str())
852            .map(String::from);
853
854        // Extract files (required)
855        let files_obj = obj
856            .get("files")
857            .and_then(|v| v.as_object())
858            .ok_or_else(|| "Missing or invalid 'files' key")?;
859
860        // Parse file tree
861        let mut root_files = HashMap::new();
862        for (key, value) in files_obj {
863            root_files.insert(key.clone(), FileTreeNode::from_json_value(value)?);
864        }
865
866        let root = FileTreeNode::Directory { files: root_files };
867
868        // Create Quill from tree
869        Self::from_tree(root, default_name)
870    }
871
872    /// Recursively load all files from a directory into a tree structure
873    fn load_directory_as_tree(
874        current_dir: &Path,
875        base_dir: &Path,
876        ignore: &QuillIgnore,
877    ) -> Result<FileTreeNode, Box<dyn StdError + Send + Sync>> {
878        use std::fs;
879
880        if !current_dir.exists() {
881            return Ok(FileTreeNode::Directory {
882                files: HashMap::new(),
883            });
884        }
885
886        let mut files = HashMap::new();
887
888        for entry in fs::read_dir(current_dir)? {
889            let entry = entry?;
890            let path = entry.path();
891            let relative_path = path
892                .strip_prefix(base_dir)
893                .map_err(|e| format!("Failed to get relative path: {}", e))?
894                .to_path_buf();
895
896            // Check if this path should be ignored
897            if ignore.is_ignored(&relative_path) {
898                continue;
899            }
900
901            // Get the filename
902            let filename = path
903                .file_name()
904                .and_then(|n| n.to_str())
905                .ok_or_else(|| format!("Invalid filename: {}", path.display()))?
906                .to_string();
907
908            if path.is_file() {
909                let contents = fs::read(&path)
910                    .map_err(|e| format!("Failed to read file '{}': {}", path.display(), e))?;
911
912                files.insert(filename, FileTreeNode::File { contents });
913            } else if path.is_dir() {
914                // Recursively process subdirectory
915                let subdir_tree = Self::load_directory_as_tree(&path, base_dir, ignore)?;
916                files.insert(filename, subdir_tree);
917            }
918        }
919
920        Ok(FileTreeNode::Directory { files })
921    }
922
923    /// Get the list of typst packages to download, if specified in Quill.toml
924    pub fn typst_packages(&self) -> Vec<String> {
925        self.metadata
926            .get("typst_packages")
927            .and_then(|v| v.as_array())
928            .map(|arr| {
929                arr.iter()
930                    .filter_map(|v| v.as_str().map(|s| s.to_string()))
931                    .collect()
932            })
933            .unwrap_or_default()
934    }
935
936    /// Get default values from the cached schema defaults
937    ///
938    /// Returns a reference to the pre-computed defaults HashMap that was extracted
939    /// during Quill construction. This is more efficient than re-parsing the schema.
940    ///
941    /// This is used by `ParsedDocument::with_defaults()` to apply default values
942    /// to missing fields.
943    pub fn extract_defaults(&self) -> &HashMap<String, QuillValue> {
944        &self.defaults
945    }
946
947    /// Get example values from the cached schema examples
948    ///
949    /// Returns a reference to the pre-computed examples HashMap that was extracted
950    /// during Quill construction. This is more efficient than re-parsing the schema.
951    pub fn extract_examples(&self) -> &HashMap<String, Vec<QuillValue>> {
952        &self.examples
953    }
954
955    /// Get file contents by path (relative to quill root)
956    pub fn get_file<P: AsRef<Path>>(&self, path: P) -> Option<&[u8]> {
957        self.files.get_file(path)
958    }
959
960    /// Check if a file exists in memory
961    pub fn file_exists<P: AsRef<Path>>(&self, path: P) -> bool {
962        self.files.file_exists(path)
963    }
964
965    /// Check if a directory exists in memory
966    pub fn dir_exists<P: AsRef<Path>>(&self, path: P) -> bool {
967        self.files.dir_exists(path)
968    }
969
970    /// List files in a directory (non-recursive, returns file names only)
971    pub fn list_files<P: AsRef<Path>>(&self, path: P) -> Vec<String> {
972        self.files.list_files(path)
973    }
974
975    /// List subdirectories in a directory (non-recursive, returns directory names only)
976    pub fn list_subdirectories<P: AsRef<Path>>(&self, path: P) -> Vec<String> {
977        self.files.list_subdirectories(path)
978    }
979
980    /// List all files in a directory (returns paths relative to quill root)
981    pub fn list_directory<P: AsRef<Path>>(&self, dir_path: P) -> Vec<PathBuf> {
982        let dir_path = dir_path.as_ref();
983        let filenames = self.files.list_files(dir_path);
984
985        // Convert filenames to full paths
986        filenames
987            .iter()
988            .map(|name| {
989                if dir_path == Path::new("") {
990                    PathBuf::from(name)
991                } else {
992                    dir_path.join(name)
993                }
994            })
995            .collect()
996    }
997
998    /// List all directories in a directory (returns paths relative to quill root)
999    pub fn list_directories<P: AsRef<Path>>(&self, dir_path: P) -> Vec<PathBuf> {
1000        let dir_path = dir_path.as_ref();
1001        let subdirs = self.files.list_subdirectories(dir_path);
1002
1003        // Convert subdirectory names to full paths
1004        subdirs
1005            .iter()
1006            .map(|name| {
1007                if dir_path == Path::new("") {
1008                    PathBuf::from(name)
1009                } else {
1010                    dir_path.join(name)
1011                }
1012            })
1013            .collect()
1014    }
1015
1016    /// Get all files matching a pattern (supports glob-style wildcards)
1017    pub fn find_files<P: AsRef<Path>>(&self, pattern: P) -> Vec<PathBuf> {
1018        let pattern_str = pattern.as_ref().to_string_lossy();
1019        let mut matches = Vec::new();
1020
1021        // Compile the glob pattern
1022        let glob_pattern = match glob::Pattern::new(&pattern_str) {
1023            Ok(pat) => pat,
1024            Err(_) => return matches, // Invalid pattern returns empty results
1025        };
1026
1027        // Recursively search the tree for matching files
1028        self.find_files_recursive(&self.files, Path::new(""), &glob_pattern, &mut matches);
1029
1030        matches.sort();
1031        matches
1032    }
1033
1034    /// Helper method to recursively search for files matching a pattern
1035    fn find_files_recursive(
1036        &self,
1037        node: &FileTreeNode,
1038        current_path: &Path,
1039        pattern: &glob::Pattern,
1040        matches: &mut Vec<PathBuf>,
1041    ) {
1042        match node {
1043            FileTreeNode::File { .. } => {
1044                let path_str = current_path.to_string_lossy();
1045                if pattern.matches(&path_str) {
1046                    matches.push(current_path.to_path_buf());
1047                }
1048            }
1049            FileTreeNode::Directory { files } => {
1050                for (name, child_node) in files {
1051                    let child_path = if current_path == Path::new("") {
1052                        PathBuf::from(name)
1053                    } else {
1054                        current_path.join(name)
1055                    };
1056                    self.find_files_recursive(child_node, &child_path, pattern, matches);
1057                }
1058            }
1059        }
1060    }
1061}
1062
1063#[cfg(test)]
1064mod tests {
1065    use super::*;
1066    use std::fs;
1067    use tempfile::TempDir;
1068
1069    #[test]
1070    fn test_quillignore_parsing() {
1071        let ignore_content = r#"
1072# This is a comment
1073*.tmp
1074target/
1075node_modules/
1076.git/
1077"#;
1078        let ignore = QuillIgnore::from_content(ignore_content);
1079        assert_eq!(ignore.patterns.len(), 4);
1080        assert!(ignore.patterns.contains(&"*.tmp".to_string()));
1081        assert!(ignore.patterns.contains(&"target/".to_string()));
1082    }
1083
1084    #[test]
1085    fn test_quillignore_matching() {
1086        let ignore = QuillIgnore::new(vec![
1087            "*.tmp".to_string(),
1088            "target/".to_string(),
1089            "node_modules/".to_string(),
1090            ".git/".to_string(),
1091        ]);
1092
1093        // Test file patterns
1094        assert!(ignore.is_ignored("test.tmp"));
1095        assert!(ignore.is_ignored("path/to/file.tmp"));
1096        assert!(!ignore.is_ignored("test.txt"));
1097
1098        // Test directory patterns
1099        assert!(ignore.is_ignored("target"));
1100        assert!(ignore.is_ignored("target/debug"));
1101        assert!(ignore.is_ignored("target/debug/deps"));
1102        assert!(!ignore.is_ignored("src/target.rs"));
1103
1104        assert!(ignore.is_ignored("node_modules"));
1105        assert!(ignore.is_ignored("node_modules/package"));
1106        assert!(!ignore.is_ignored("my_node_modules"));
1107    }
1108
1109    #[test]
1110    fn test_in_memory_file_system() {
1111        let temp_dir = TempDir::new().unwrap();
1112        let quill_dir = temp_dir.path();
1113
1114        // Create test files
1115        fs::write(
1116            quill_dir.join("Quill.toml"),
1117            "[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"",
1118        )
1119        .unwrap();
1120        fs::write(quill_dir.join("plate.typ"), "test plate").unwrap();
1121
1122        let assets_dir = quill_dir.join("assets");
1123        fs::create_dir_all(&assets_dir).unwrap();
1124        fs::write(assets_dir.join("test.txt"), "asset content").unwrap();
1125
1126        let packages_dir = quill_dir.join("packages");
1127        fs::create_dir_all(&packages_dir).unwrap();
1128        fs::write(packages_dir.join("package.typ"), "package content").unwrap();
1129
1130        // Load quill
1131        let quill = Quill::from_path(quill_dir).unwrap();
1132
1133        // Test file access
1134        assert!(quill.file_exists("plate.typ"));
1135        assert!(quill.file_exists("assets/test.txt"));
1136        assert!(quill.file_exists("packages/package.typ"));
1137        assert!(!quill.file_exists("nonexistent.txt"));
1138
1139        // Test file content
1140        let asset_content = quill.get_file("assets/test.txt").unwrap();
1141        assert_eq!(asset_content, b"asset content");
1142
1143        // Test directory listing
1144        let asset_files = quill.list_directory("assets");
1145        assert_eq!(asset_files.len(), 1);
1146        assert!(asset_files.contains(&PathBuf::from("assets/test.txt")));
1147    }
1148
1149    #[test]
1150    fn test_quillignore_integration() {
1151        let temp_dir = TempDir::new().unwrap();
1152        let quill_dir = temp_dir.path();
1153
1154        // Create .quillignore
1155        fs::write(quill_dir.join(".quillignore"), "*.tmp\ntarget/\n").unwrap();
1156
1157        // Create test files
1158        fs::write(
1159            quill_dir.join("Quill.toml"),
1160            "[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"",
1161        )
1162        .unwrap();
1163        fs::write(quill_dir.join("plate.typ"), "test template").unwrap();
1164        fs::write(quill_dir.join("should_ignore.tmp"), "ignored").unwrap();
1165
1166        let target_dir = quill_dir.join("target");
1167        fs::create_dir_all(&target_dir).unwrap();
1168        fs::write(target_dir.join("debug.txt"), "also ignored").unwrap();
1169
1170        // Load quill
1171        let quill = Quill::from_path(quill_dir).unwrap();
1172
1173        // Test that ignored files are not loaded
1174        assert!(quill.file_exists("plate.typ"));
1175        assert!(!quill.file_exists("should_ignore.tmp"));
1176        assert!(!quill.file_exists("target/debug.txt"));
1177    }
1178
1179    #[test]
1180    fn test_find_files_pattern() {
1181        let temp_dir = TempDir::new().unwrap();
1182        let quill_dir = temp_dir.path();
1183
1184        // Create test directory structure
1185        fs::write(
1186            quill_dir.join("Quill.toml"),
1187            "[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"",
1188        )
1189        .unwrap();
1190        fs::write(quill_dir.join("plate.typ"), "template").unwrap();
1191
1192        let assets_dir = quill_dir.join("assets");
1193        fs::create_dir_all(&assets_dir).unwrap();
1194        fs::write(assets_dir.join("image.png"), "png data").unwrap();
1195        fs::write(assets_dir.join("data.json"), "json data").unwrap();
1196
1197        let fonts_dir = assets_dir.join("fonts");
1198        fs::create_dir_all(&fonts_dir).unwrap();
1199        fs::write(fonts_dir.join("font.ttf"), "font data").unwrap();
1200
1201        // Load quill
1202        let quill = Quill::from_path(quill_dir).unwrap();
1203
1204        // Test pattern matching
1205        let all_assets = quill.find_files("assets/*");
1206        assert!(all_assets.len() >= 3); // At least image.png, data.json, fonts/font.ttf
1207
1208        let typ_files = quill.find_files("*.typ");
1209        assert_eq!(typ_files.len(), 1);
1210        assert!(typ_files.contains(&PathBuf::from("plate.typ")));
1211    }
1212
1213    #[test]
1214    fn test_new_standardized_toml_format() {
1215        let temp_dir = TempDir::new().unwrap();
1216        let quill_dir = temp_dir.path();
1217
1218        // Create test files using new standardized format
1219        let toml_content = r#"[Quill]
1220name = "my-custom-quill"
1221backend = "typst"
1222plate_file = "custom_plate.typ"
1223description = "Test quill with new format"
1224author = "Test Author"
1225"#;
1226        fs::write(quill_dir.join("Quill.toml"), toml_content).unwrap();
1227        fs::write(
1228            quill_dir.join("custom_plate.typ"),
1229            "= Custom Template\n\nThis is a custom template.",
1230        )
1231        .unwrap();
1232
1233        // Load quill
1234        let quill = Quill::from_path(quill_dir).unwrap();
1235
1236        // Test that name comes from TOML, not directory
1237        assert_eq!(quill.name, "my-custom-quill");
1238
1239        // Test that backend is in metadata
1240        assert!(quill.metadata.contains_key("backend"));
1241        if let Some(backend_val) = quill.metadata.get("backend") {
1242            if let Some(backend_str) = backend_val.as_str() {
1243                assert_eq!(backend_str, "typst");
1244            } else {
1245                panic!("Backend value is not a string");
1246            }
1247        }
1248
1249        // Test that other fields are in metadata (but not version)
1250        assert!(quill.metadata.contains_key("description"));
1251        assert!(quill.metadata.contains_key("author"));
1252        assert!(!quill.metadata.contains_key("version")); // version should be excluded
1253
1254        // Test that plate template content is loaded correctly
1255        assert!(quill.plate.unwrap().contains("Custom Template"));
1256    }
1257
1258    #[test]
1259    fn test_typst_packages_parsing() {
1260        let temp_dir = TempDir::new().unwrap();
1261        let quill_dir = temp_dir.path();
1262
1263        let toml_content = r#"
1264[Quill]
1265name = "test-quill"
1266backend = "typst"
1267plate_file = "plate.typ"
1268description = "Test quill for packages"
1269
1270[typst]
1271packages = ["@preview/bubble:0.2.2", "@preview/example:1.0.0"]
1272"#;
1273
1274        fs::write(quill_dir.join("Quill.toml"), toml_content).unwrap();
1275        fs::write(quill_dir.join("plate.typ"), "test").unwrap();
1276
1277        let quill = Quill::from_path(quill_dir).unwrap();
1278        let packages = quill.typst_packages();
1279
1280        assert_eq!(packages.len(), 2);
1281        assert_eq!(packages[0], "@preview/bubble:0.2.2");
1282        assert_eq!(packages[1], "@preview/example:1.0.0");
1283    }
1284
1285    #[test]
1286    fn test_template_loading() {
1287        let temp_dir = TempDir::new().unwrap();
1288        let quill_dir = temp_dir.path();
1289
1290        // Create test files with example specified
1291        let toml_content = r#"[Quill]
1292name = "test-with-template"
1293backend = "typst"
1294plate_file = "plate.typ"
1295example_file = "example.md"
1296description = "Test quill with template"
1297"#;
1298        fs::write(quill_dir.join("Quill.toml"), toml_content).unwrap();
1299        fs::write(quill_dir.join("plate.typ"), "plate content").unwrap();
1300        fs::write(
1301            quill_dir.join("example.md"),
1302            "---\ntitle: Test\n---\n\nThis is a test template.",
1303        )
1304        .unwrap();
1305
1306        // Load quill
1307        let quill = Quill::from_path(quill_dir).unwrap();
1308
1309        // Test that example content is loaded and includes some the text
1310        assert!(quill.example.is_some());
1311        let example = quill.example.unwrap();
1312        assert!(example.contains("title: Test"));
1313        assert!(example.contains("This is a test template"));
1314
1315        // Test that plate template is still loaded
1316        assert_eq!(quill.plate.unwrap(), "plate content");
1317    }
1318
1319    #[test]
1320    fn test_template_optional() {
1321        let temp_dir = TempDir::new().unwrap();
1322        let quill_dir = temp_dir.path();
1323
1324        // Create test files without example specified
1325        let toml_content = r#"[Quill]
1326name = "test-without-template"
1327backend = "typst"
1328plate_file = "plate.typ"
1329description = "Test quill without template"
1330"#;
1331        fs::write(quill_dir.join("Quill.toml"), toml_content).unwrap();
1332        fs::write(quill_dir.join("plate.typ"), "plate content").unwrap();
1333
1334        // Load quill
1335        let quill = Quill::from_path(quill_dir).unwrap();
1336
1337        // Test that example fields are None
1338        assert_eq!(quill.example, None);
1339
1340        // Test that plate template is still loaded
1341        assert_eq!(quill.plate.unwrap(), "plate content");
1342    }
1343
1344    #[test]
1345    fn test_from_tree() {
1346        // Create a simple in-memory file tree
1347        let mut root_files = HashMap::new();
1348
1349        // Add Quill.toml
1350        let quill_toml = r#"[Quill]
1351name = "test-from-tree"
1352backend = "typst"
1353plate_file = "plate.typ"
1354description = "A test quill from tree"
1355"#;
1356        root_files.insert(
1357            "Quill.toml".to_string(),
1358            FileTreeNode::File {
1359                contents: quill_toml.as_bytes().to_vec(),
1360            },
1361        );
1362
1363        // Add plate file
1364        let plate_content = "= Test Template\n\nThis is a test.";
1365        root_files.insert(
1366            "plate.typ".to_string(),
1367            FileTreeNode::File {
1368                contents: plate_content.as_bytes().to_vec(),
1369            },
1370        );
1371
1372        let root = FileTreeNode::Directory { files: root_files };
1373
1374        // Create Quill from tree
1375        let quill = Quill::from_tree(root, Some("test-from-tree".to_string())).unwrap();
1376
1377        // Validate the quill
1378        assert_eq!(quill.name, "test-from-tree");
1379        assert_eq!(quill.plate.unwrap(), plate_content);
1380        assert!(quill.metadata.contains_key("backend"));
1381        assert!(quill.metadata.contains_key("description"));
1382    }
1383
1384    #[test]
1385    fn test_from_tree_with_template() {
1386        let mut root_files = HashMap::new();
1387
1388        // Add Quill.toml with example specified
1389        let quill_toml = r#"[Quill]
1390name = "test-tree-template"
1391backend = "typst"
1392plate_file = "plate.typ"
1393example_file = "template.md"
1394description = "Test tree with template"
1395"#;
1396        root_files.insert(
1397            "Quill.toml".to_string(),
1398            FileTreeNode::File {
1399                contents: quill_toml.as_bytes().to_vec(),
1400            },
1401        );
1402
1403        // Add plate file
1404        root_files.insert(
1405            "plate.typ".to_string(),
1406            FileTreeNode::File {
1407                contents: b"plate content".to_vec(),
1408            },
1409        );
1410
1411        // Add template file
1412        let template_content = "# {{ title }}\n\n{{ body }}";
1413        root_files.insert(
1414            "template.md".to_string(),
1415            FileTreeNode::File {
1416                contents: template_content.as_bytes().to_vec(),
1417            },
1418        );
1419
1420        let root = FileTreeNode::Directory { files: root_files };
1421
1422        // Create Quill from tree
1423        let quill = Quill::from_tree(root, None).unwrap();
1424
1425        // Validate template is loaded
1426        assert_eq!(quill.example, Some(template_content.to_string()));
1427    }
1428
1429    #[test]
1430    fn test_from_json() {
1431        // Create JSON representation of a Quill using new format
1432        let json_str = r#"{
1433            "metadata": {
1434                "name": "test-from-json"
1435            },
1436            "files": {
1437                "Quill.toml": {
1438                    "contents": "[Quill]\nname = \"test-from-json\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill from JSON\"\n"
1439                },
1440                "plate.typ": {
1441                    "contents": "= Test Plate\n\nThis is test content."
1442                }
1443            }
1444        }"#;
1445
1446        // Create Quill from JSON
1447        let quill = Quill::from_json(json_str).unwrap();
1448
1449        // Validate the quill
1450        assert_eq!(quill.name, "test-from-json");
1451        assert!(quill.plate.unwrap().contains("Test Plate"));
1452        assert!(quill.metadata.contains_key("backend"));
1453    }
1454
1455    #[test]
1456    fn test_from_json_with_byte_array() {
1457        // Create JSON with byte array representation using new format
1458        let json_str = r#"{
1459            "files": {
1460                "Quill.toml": {
1461                    "contents": "[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"\n"
1462                },
1463                "plate.typ": {
1464                    "contents": "test plate"
1465                }
1466            }
1467        }"#;
1468
1469        // Create Quill from JSON
1470        let quill = Quill::from_json(json_str).unwrap();
1471
1472        // Validate the quill was created
1473        assert_eq!(quill.name, "test");
1474        assert_eq!(quill.plate.unwrap(), "test plate");
1475    }
1476
1477    #[test]
1478    fn test_from_json_missing_files() {
1479        // JSON without files field should fail
1480        let json_str = r#"{
1481            "metadata": {
1482                "name": "test"
1483            }
1484        }"#;
1485
1486        let result = Quill::from_json(json_str);
1487        assert!(result.is_err());
1488        // Should fail because there's no 'files' key
1489        assert!(result.unwrap_err().to_string().contains("files"));
1490    }
1491
1492    #[test]
1493    fn test_from_json_tree_structure() {
1494        // Test the new tree structure format
1495        let json_str = r#"{
1496            "files": {
1497                "Quill.toml": {
1498                    "contents": "[Quill]\nname = \"test-tree-json\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test tree JSON\"\n"
1499                },
1500                "plate.typ": {
1501                    "contents": "= Test Plate\n\nTree structure content."
1502                }
1503            }
1504        }"#;
1505
1506        let quill = Quill::from_json(json_str).unwrap();
1507
1508        assert_eq!(quill.name, "test-tree-json");
1509        assert!(quill.plate.unwrap().contains("Tree structure content"));
1510        assert!(quill.metadata.contains_key("backend"));
1511    }
1512
1513    #[test]
1514    fn test_from_json_nested_tree_structure() {
1515        // Test nested directories in tree structure
1516        let json_str = r#"{
1517            "files": {
1518                "Quill.toml": {
1519                    "contents": "[Quill]\nname = \"nested-test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Nested test\"\n"
1520                },
1521                "plate.typ": {
1522                    "contents": "plate"
1523                },
1524                "src": {
1525                    "main.rs": {
1526                        "contents": "fn main() {}"
1527                    },
1528                    "lib.rs": {
1529                        "contents": "// lib"
1530                    }
1531                }
1532            }
1533        }"#;
1534
1535        let quill = Quill::from_json(json_str).unwrap();
1536
1537        assert_eq!(quill.name, "nested-test");
1538        // Verify nested files are accessible
1539        assert!(quill.file_exists("src/main.rs"));
1540        assert!(quill.file_exists("src/lib.rs"));
1541
1542        let main_rs = quill.get_file("src/main.rs").unwrap();
1543        assert_eq!(main_rs, b"fn main() {}");
1544    }
1545
1546    #[test]
1547    fn test_from_tree_structure_direct() {
1548        // Test using from_tree_structure directly
1549        let mut root_files = HashMap::new();
1550
1551        root_files.insert(
1552            "Quill.toml".to_string(),
1553            FileTreeNode::File {
1554                contents:
1555                    b"[Quill]\nname = \"direct-tree\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Direct tree test\"\n"
1556                        .to_vec(),
1557            },
1558        );
1559
1560        root_files.insert(
1561            "plate.typ".to_string(),
1562            FileTreeNode::File {
1563                contents: b"plate content".to_vec(),
1564            },
1565        );
1566
1567        // Add a nested directory
1568        let mut src_files = HashMap::new();
1569        src_files.insert(
1570            "main.rs".to_string(),
1571            FileTreeNode::File {
1572                contents: b"fn main() {}".to_vec(),
1573            },
1574        );
1575
1576        root_files.insert(
1577            "src".to_string(),
1578            FileTreeNode::Directory { files: src_files },
1579        );
1580
1581        let root = FileTreeNode::Directory { files: root_files };
1582
1583        let quill = Quill::from_tree(root, None).unwrap();
1584
1585        assert_eq!(quill.name, "direct-tree");
1586        assert!(quill.file_exists("src/main.rs"));
1587        assert!(quill.file_exists("plate.typ"));
1588    }
1589
1590    #[test]
1591    fn test_from_json_with_metadata_override() {
1592        // Test that metadata key overrides name from Quill.toml
1593        let json_str = r#"{
1594            "metadata": {
1595                "name": "override-name"
1596            },
1597            "files": {
1598                "Quill.toml": {
1599                    "contents": "[Quill]\nname = \"toml-name\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"TOML name test\"\n"
1600                },
1601                "plate.typ": {
1602                    "contents": "= plate"
1603                }
1604            }
1605        }"#;
1606
1607        let quill = Quill::from_json(json_str).unwrap();
1608        // Metadata name should be used as default, but Quill.toml takes precedence
1609        // when from_tree is called
1610        assert_eq!(quill.name, "toml-name");
1611    }
1612
1613    #[test]
1614    fn test_from_json_empty_directory() {
1615        // Test that empty directories are supported
1616        let json_str = r#"{
1617            "files": {
1618                "Quill.toml": {
1619                    "contents": "[Quill]\nname = \"empty-dir-test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Empty directory test\"\n"
1620                },
1621                "plate.typ": {
1622                    "contents": "plate"
1623                },
1624                "empty_dir": {}
1625            }
1626        }"#;
1627
1628        let quill = Quill::from_json(json_str).unwrap();
1629        assert_eq!(quill.name, "empty-dir-test");
1630        assert!(quill.dir_exists("empty_dir"));
1631        assert!(!quill.file_exists("empty_dir"));
1632    }
1633
1634    #[test]
1635    fn test_dir_exists_and_list_apis() {
1636        let mut root_files = HashMap::new();
1637
1638        // Add Quill.toml
1639        root_files.insert(
1640            "Quill.toml".to_string(),
1641            FileTreeNode::File {
1642                contents: b"[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"\n"
1643                    .to_vec(),
1644            },
1645        );
1646
1647        // Add plate file
1648        root_files.insert(
1649            "plate.typ".to_string(),
1650            FileTreeNode::File {
1651                contents: b"plate content".to_vec(),
1652            },
1653        );
1654
1655        // Add assets directory with files
1656        let mut assets_files = HashMap::new();
1657        assets_files.insert(
1658            "logo.png".to_string(),
1659            FileTreeNode::File {
1660                contents: vec![137, 80, 78, 71],
1661            },
1662        );
1663        assets_files.insert(
1664            "icon.svg".to_string(),
1665            FileTreeNode::File {
1666                contents: b"<svg></svg>".to_vec(),
1667            },
1668        );
1669
1670        // Add subdirectory in assets
1671        let mut fonts_files = HashMap::new();
1672        fonts_files.insert(
1673            "font.ttf".to_string(),
1674            FileTreeNode::File {
1675                contents: b"font data".to_vec(),
1676            },
1677        );
1678        assets_files.insert(
1679            "fonts".to_string(),
1680            FileTreeNode::Directory { files: fonts_files },
1681        );
1682
1683        root_files.insert(
1684            "assets".to_string(),
1685            FileTreeNode::Directory {
1686                files: assets_files,
1687            },
1688        );
1689
1690        // Add empty directory
1691        root_files.insert(
1692            "empty".to_string(),
1693            FileTreeNode::Directory {
1694                files: HashMap::new(),
1695            },
1696        );
1697
1698        let root = FileTreeNode::Directory { files: root_files };
1699        let quill = Quill::from_tree(root, None).unwrap();
1700
1701        // Test dir_exists
1702        assert!(quill.dir_exists("assets"));
1703        assert!(quill.dir_exists("assets/fonts"));
1704        assert!(quill.dir_exists("empty"));
1705        assert!(!quill.dir_exists("nonexistent"));
1706        assert!(!quill.dir_exists("plate.typ")); // file, not directory
1707
1708        // Test file_exists
1709        assert!(quill.file_exists("plate.typ"));
1710        assert!(quill.file_exists("assets/logo.png"));
1711        assert!(quill.file_exists("assets/fonts/font.ttf"));
1712        assert!(!quill.file_exists("assets")); // directory, not file
1713
1714        // Test list_files
1715        let root_files_list = quill.list_files("");
1716        assert_eq!(root_files_list.len(), 2); // Quill.toml and plate.typ
1717        assert!(root_files_list.contains(&"Quill.toml".to_string()));
1718        assert!(root_files_list.contains(&"plate.typ".to_string()));
1719
1720        let assets_files_list = quill.list_files("assets");
1721        assert_eq!(assets_files_list.len(), 2); // logo.png and icon.svg
1722        assert!(assets_files_list.contains(&"logo.png".to_string()));
1723        assert!(assets_files_list.contains(&"icon.svg".to_string()));
1724
1725        // Test list_subdirectories
1726        let root_subdirs = quill.list_subdirectories("");
1727        assert_eq!(root_subdirs.len(), 2); // assets and empty
1728        assert!(root_subdirs.contains(&"assets".to_string()));
1729        assert!(root_subdirs.contains(&"empty".to_string()));
1730
1731        let assets_subdirs = quill.list_subdirectories("assets");
1732        assert_eq!(assets_subdirs.len(), 1); // fonts
1733        assert!(assets_subdirs.contains(&"fonts".to_string()));
1734
1735        let empty_subdirs = quill.list_subdirectories("empty");
1736        assert_eq!(empty_subdirs.len(), 0);
1737    }
1738
1739    #[test]
1740    fn test_field_schemas_parsing() {
1741        let mut root_files = HashMap::new();
1742
1743        // Add Quill.toml with field schemas
1744        let quill_toml = r#"[Quill]
1745name = "taro"
1746backend = "typst"
1747plate_file = "plate.typ"
1748example_file = "taro.md"
1749description = "Test template for field schemas"
1750
1751[fields]
1752author = {description = "Author of document" }
1753ice_cream = {description = "favorite ice cream flavor"}
1754title = {description = "title of document" }
1755"#;
1756        root_files.insert(
1757            "Quill.toml".to_string(),
1758            FileTreeNode::File {
1759                contents: quill_toml.as_bytes().to_vec(),
1760            },
1761        );
1762
1763        // Add plate file
1764        let plate_content = "= Test Template\n\nThis is a test.";
1765        root_files.insert(
1766            "plate.typ".to_string(),
1767            FileTreeNode::File {
1768                contents: plate_content.as_bytes().to_vec(),
1769            },
1770        );
1771
1772        // Add template file
1773        root_files.insert(
1774            "taro.md".to_string(),
1775            FileTreeNode::File {
1776                contents: b"# Template".to_vec(),
1777            },
1778        );
1779
1780        let root = FileTreeNode::Directory { files: root_files };
1781
1782        // Create Quill from tree
1783        let quill = Quill::from_tree(root, Some("taro".to_string())).unwrap();
1784
1785        // Validate field schemas were parsed
1786        assert_eq!(quill.schema["properties"].as_object().unwrap().len(), 3);
1787        assert!(quill.schema["properties"]
1788            .as_object()
1789            .unwrap()
1790            .contains_key("author"));
1791        assert!(quill.schema["properties"]
1792            .as_object()
1793            .unwrap()
1794            .contains_key("ice_cream"));
1795        assert!(quill.schema["properties"]
1796            .as_object()
1797            .unwrap()
1798            .contains_key("title"));
1799
1800        // Verify author field schema
1801        let author_schema = quill.schema["properties"]["author"].as_object().unwrap();
1802        assert_eq!(author_schema["description"], "Author of document");
1803
1804        // Verify ice_cream field schema (no required field, should default to false)
1805        let ice_cream_schema = quill.schema["properties"]["ice_cream"].as_object().unwrap();
1806        assert_eq!(ice_cream_schema["description"], "favorite ice cream flavor");
1807
1808        // Verify title field schema
1809        let title_schema = quill.schema["properties"]["title"].as_object().unwrap();
1810        assert_eq!(title_schema["description"], "title of document");
1811    }
1812
1813    #[test]
1814    fn test_field_schema_struct() {
1815        // Test creating FieldSchema with minimal fields
1816        let schema1 = FieldSchema::new("test_name".to_string(), "Test description".to_string());
1817        assert_eq!(schema1.description, "Test description");
1818        assert_eq!(schema1.r#type, None);
1819        assert_eq!(schema1.example, None);
1820        assert_eq!(schema1.default, None);
1821
1822        // Test parsing FieldSchema from YAML with all fields
1823        let yaml_str = r#"
1824description: "Full field schema"
1825type: "string"
1826example: "Example value"
1827default: "Default value"
1828"#;
1829        let yaml_value: serde_yaml::Value = serde_yaml::from_str(yaml_str).unwrap();
1830        let quill_value = QuillValue::from_yaml(yaml_value).unwrap();
1831        let schema2 = FieldSchema::from_quill_value("test_name".to_string(), &quill_value).unwrap();
1832        assert_eq!(schema2.name, "test_name");
1833        assert_eq!(schema2.description, "Full field schema");
1834        assert_eq!(schema2.r#type, Some("string".to_string()));
1835        assert_eq!(
1836            schema2.example.as_ref().and_then(|v| v.as_str()),
1837            Some("Example value")
1838        );
1839        assert_eq!(
1840            schema2.default.as_ref().and_then(|v| v.as_str()),
1841            Some("Default value")
1842        );
1843    }
1844
1845    #[test]
1846    fn test_quill_without_plate_file() {
1847        // Test creating a Quill without specifying a plate file
1848        let mut root_files = HashMap::new();
1849
1850        // Add Quill.toml without plate field
1851        let quill_toml = r#"[Quill]
1852name = "test-no-plate"
1853backend = "typst"
1854description = "Test quill without plate file"
1855"#;
1856        root_files.insert(
1857            "Quill.toml".to_string(),
1858            FileTreeNode::File {
1859                contents: quill_toml.as_bytes().to_vec(),
1860            },
1861        );
1862
1863        let root = FileTreeNode::Directory { files: root_files };
1864
1865        // Create Quill from tree
1866        let quill = Quill::from_tree(root, None).unwrap();
1867
1868        // Validate that plate is null (will use auto plate)
1869        assert!(quill.plate.clone().is_none());
1870        assert_eq!(quill.name, "test-no-plate");
1871    }
1872
1873    #[test]
1874    fn test_quill_config_from_toml() {
1875        // Test parsing QuillConfig from TOML content
1876        let toml_content = r#"[Quill]
1877name = "test-config"
1878backend = "typst"
1879description = "Test configuration parsing"
1880version = "1.0.0"
1881author = "Test Author"
1882plate_file = "plate.typ"
1883example_file = "example.md"
1884
1885[typst]
1886packages = ["@preview/bubble:0.2.2"]
1887
1888[fields]
1889title = {description = "Document title", type = "string"}
1890author = {description = "Document author"}
1891"#;
1892
1893        let config = QuillConfig::from_toml(toml_content).unwrap();
1894
1895        // Verify required fields
1896        assert_eq!(config.name, "test-config");
1897        assert_eq!(config.backend, "typst");
1898        assert_eq!(config.description, "Test configuration parsing");
1899
1900        // Verify optional fields
1901        assert_eq!(config.version, Some("1.0.0".to_string()));
1902        assert_eq!(config.author, Some("Test Author".to_string()));
1903        assert_eq!(config.plate_file, Some("plate.typ".to_string()));
1904        assert_eq!(config.example_file, Some("example.md".to_string()));
1905
1906        // Verify typst config
1907        assert!(config.typst_config.contains_key("packages"));
1908
1909        // Verify field schemas
1910        assert_eq!(config.fields.len(), 2);
1911        assert!(config.fields.contains_key("title"));
1912        assert!(config.fields.contains_key("author"));
1913
1914        let title_field = &config.fields["title"];
1915        assert_eq!(title_field.description, "Document title");
1916        assert_eq!(title_field.r#type, Some("string".to_string()));
1917    }
1918
1919    #[test]
1920    fn test_quill_config_missing_required_fields() {
1921        // Test that missing required fields result in error
1922        let toml_missing_name = r#"[Quill]
1923backend = "typst"
1924description = "Missing name"
1925"#;
1926        let result = QuillConfig::from_toml(toml_missing_name);
1927        assert!(result.is_err());
1928        assert!(result
1929            .unwrap_err()
1930            .to_string()
1931            .contains("Missing required 'name'"));
1932
1933        let toml_missing_backend = r#"[Quill]
1934name = "test"
1935description = "Missing backend"
1936"#;
1937        let result = QuillConfig::from_toml(toml_missing_backend);
1938        assert!(result.is_err());
1939        assert!(result
1940            .unwrap_err()
1941            .to_string()
1942            .contains("Missing required 'backend'"));
1943
1944        let toml_missing_description = r#"[Quill]
1945name = "test"
1946backend = "typst"
1947"#;
1948        let result = QuillConfig::from_toml(toml_missing_description);
1949        assert!(result.is_err());
1950        assert!(result
1951            .unwrap_err()
1952            .to_string()
1953            .contains("Missing required 'description'"));
1954    }
1955
1956    #[test]
1957    fn test_quill_config_empty_description() {
1958        // Test that empty description results in error
1959        let toml_empty_description = r#"[Quill]
1960name = "test"
1961backend = "typst"
1962description = "   "
1963"#;
1964        let result = QuillConfig::from_toml(toml_empty_description);
1965        assert!(result.is_err());
1966        assert!(result
1967            .unwrap_err()
1968            .to_string()
1969            .contains("description' field in [Quill] section cannot be empty"));
1970    }
1971
1972    #[test]
1973    fn test_quill_config_missing_quill_section() {
1974        // Test that missing [Quill] section results in error
1975        let toml_no_section = r#"[fields]
1976title = {description = "Title"}
1977"#;
1978        let result = QuillConfig::from_toml(toml_no_section);
1979        assert!(result.is_err());
1980        assert!(result
1981            .unwrap_err()
1982            .to_string()
1983            .contains("Missing required [Quill] section"));
1984    }
1985
1986    #[test]
1987    fn test_quill_from_config_metadata() {
1988        // Test that QuillConfig metadata flows through to Quill
1989        let mut root_files = HashMap::new();
1990
1991        let quill_toml = r#"[Quill]
1992name = "metadata-test"
1993backend = "typst"
1994description = "Test metadata flow"
1995author = "Test Author"
1996custom_field = "custom_value"
1997
1998[typst]
1999packages = ["@preview/bubble:0.2.2"]
2000"#;
2001        root_files.insert(
2002            "Quill.toml".to_string(),
2003            FileTreeNode::File {
2004                contents: quill_toml.as_bytes().to_vec(),
2005            },
2006        );
2007
2008        let root = FileTreeNode::Directory { files: root_files };
2009        let quill = Quill::from_tree(root, None).unwrap();
2010
2011        // Verify metadata includes backend and description
2012        assert!(quill.metadata.contains_key("backend"));
2013        assert!(quill.metadata.contains_key("description"));
2014        assert!(quill.metadata.contains_key("author"));
2015
2016        // Verify custom field is in metadata
2017        assert!(quill.metadata.contains_key("custom_field"));
2018        assert_eq!(
2019            quill.metadata.get("custom_field").unwrap().as_str(),
2020            Some("custom_value")
2021        );
2022
2023        // Verify typst config with typst_ prefix
2024        assert!(quill.metadata.contains_key("typst_packages"));
2025    }
2026
2027    #[test]
2028    fn test_extract_defaults_method() {
2029        // Test the extract_defaults method on Quill
2030        let mut root_files = HashMap::new();
2031
2032        let quill_toml = r#"[Quill]
2033name = "defaults-test"
2034backend = "typst"
2035description = "Test defaults extraction"
2036
2037[fields]
2038title = {description = "Title"}
2039author = {description = "Author", default = "Anonymous"}
2040status = {description = "Status", default = "draft"}
2041"#;
2042
2043        root_files.insert(
2044            "Quill.toml".to_string(),
2045            FileTreeNode::File {
2046                contents: quill_toml.as_bytes().to_vec(),
2047            },
2048        );
2049
2050        let root = FileTreeNode::Directory { files: root_files };
2051        let quill = Quill::from_tree(root, None).unwrap();
2052
2053        // Extract defaults
2054        let defaults = quill.extract_defaults();
2055
2056        // Verify only fields with defaults are returned
2057        assert_eq!(defaults.len(), 2);
2058        assert!(!defaults.contains_key("title")); // no default
2059        assert!(defaults.contains_key("author"));
2060        assert!(defaults.contains_key("status"));
2061
2062        // Verify default values
2063        assert_eq!(defaults.get("author").unwrap().as_str(), Some("Anonymous"));
2064        assert_eq!(defaults.get("status").unwrap().as_str(), Some("draft"));
2065    }
2066
2067    #[test]
2068    fn test_field_order_preservation() {
2069        let toml_content = r#"[Quill]
2070name = "order-test"
2071backend = "typst"
2072description = "Test field order"
2073
2074[fields]
2075first = {description = "First field"}
2076second = {description = "Second field"}
2077third = {description = "Third field", ui = {group = "Test Group"}}
2078fourth = {description = "Fourth field"}
2079"#;
2080
2081        let config = QuillConfig::from_toml(toml_content).unwrap();
2082
2083        // Check that fields have correct order based on TOML position
2084        // Order is automatically generated based on field position
2085
2086        let first = config.fields.get("first").unwrap();
2087        assert_eq!(first.ui.as_ref().unwrap().order, Some(0));
2088
2089        let second = config.fields.get("second").unwrap();
2090        assert_eq!(second.ui.as_ref().unwrap().order, Some(1));
2091
2092        let third = config.fields.get("third").unwrap();
2093        assert_eq!(third.ui.as_ref().unwrap().order, Some(2));
2094        assert_eq!(
2095            third.ui.as_ref().unwrap().group,
2096            Some("Test Group".to_string())
2097        );
2098
2099        let fourth = config.fields.get("fourth").unwrap();
2100        assert_eq!(fourth.ui.as_ref().unwrap().order, Some(3));
2101    }
2102
2103    #[test]
2104    fn test_quill_with_all_ui_properties() {
2105        let toml_content = r#"[Quill]
2106name = "full-ui-test"
2107backend = "typst"
2108description = "Test all UI properties"
2109
2110[fields.author]
2111description = "The full name of the document author"
2112type = "str"
2113
2114[fields.author.ui]
2115group = "Author Info"
2116tooltip = "Your full name"
2117"#;
2118
2119        let config = QuillConfig::from_toml(toml_content).unwrap();
2120
2121        let author_field = &config.fields["author"];
2122        let ui = author_field.ui.as_ref().unwrap();
2123        assert_eq!(ui.group, Some("Author Info".to_string()));
2124        assert_eq!(ui.tooltip, Some("Your full name".to_string()));
2125        assert_eq!(ui.order, Some(0)); // First field should have order 0
2126    }
2127}