1use std::collections::HashMap;
4use std::error::Error as StdError;
5use std::path::{Path, PathBuf};
6
7use crate::value::QuillValue;
8
9#[derive(Debug, Clone, PartialEq)]
11pub struct UiSchema {
12 pub group: Option<String>,
14 pub order: Option<i32>,
16}
17
18#[derive(Debug, Clone, PartialEq)]
20pub struct CardSchema {
21 pub name: String,
23 pub title: Option<String>,
25 pub description: String,
27 pub ui: Option<UiSchema>,
29 pub fields: HashMap<String, FieldSchema>,
31}
32
33#[derive(Debug, Clone, PartialEq)]
35pub struct FieldSchema {
36 pub name: String,
37 pub title: Option<String>,
39 pub r#type: Option<String>,
41 pub description: String,
43 pub default: Option<QuillValue>,
45 pub examples: Option<QuillValue>,
47 pub ui: Option<UiSchema>,
49 pub required: bool,
51}
52
53impl FieldSchema {
54 pub fn new(name: String, description: String) -> Self {
56 Self {
57 name,
58 title: None,
59 r#type: None,
60 description,
61 default: None,
62 examples: None,
63 ui: None,
64 required: false,
65 }
66 }
67
68 pub fn from_quill_value(key: String, value: &QuillValue) -> Result<Self, String> {
70 let obj = value
71 .as_object()
72 .ok_or_else(|| "Field schema must be an object".to_string())?;
73
74 for key in obj.keys() {
76 match key.as_str() {
77 "name" | "title" | "type" | "description" | "examples" | "default" | "ui"
78 | "required" => {}
79 _ => {
80 eprintln!("Warning: Unknown key '{}' in field schema", key);
82 }
83 }
84 }
85
86 let name = key.clone();
87
88 let title = obj
89 .get("title")
90 .and_then(|v| v.as_str())
91 .map(|s| s.to_string());
92
93 let description = obj
94 .get("description")
95 .and_then(|v| v.as_str())
96 .unwrap_or("")
97 .to_string();
98
99 let field_type = obj
100 .get("type")
101 .and_then(|v| v.as_str())
102 .map(|s| s.to_string());
103
104 let default = obj.get("default").map(|v| QuillValue::from_json(v.clone()));
105
106 let examples = obj
107 .get("examples")
108 .map(|v| QuillValue::from_json(v.clone()));
109
110 let required = obj
112 .get("required")
113 .and_then(|v| v.as_bool())
114 .unwrap_or(false);
115
116 let ui = if let Some(ui_value) = obj.get("ui") {
118 if let Some(ui_obj) = ui_value.as_object() {
119 let group = ui_obj
120 .get("group")
121 .and_then(|v| v.as_str())
122 .map(|s| s.to_string());
123
124 for key in ui_obj.keys() {
126 match key.as_str() {
127 "group" => {}
128 _ => {
129 eprintln!(
130 "Warning: Unknown UI property '{}'. Only 'group' is supported.",
131 key
132 );
133 }
134 }
135 }
136
137 Some(UiSchema {
138 group,
139 order: None, })
141 } else {
142 return Err("UI field must be an object".to_string());
143 }
144 } else {
145 None
146 };
147
148 Ok(Self {
149 name,
150 title,
151 r#type: field_type,
152 description,
153 default,
154 examples,
155 ui,
156 required,
157 })
158 }
159}
160
161#[derive(Debug, Clone)]
163pub enum FileTreeNode {
164 File {
166 contents: Vec<u8>,
168 },
169 Directory {
171 files: HashMap<String, FileTreeNode>,
173 },
174}
175
176impl FileTreeNode {
177 pub fn get_node<P: AsRef<Path>>(&self, path: P) -> Option<&FileTreeNode> {
179 let path = path.as_ref();
180
181 if path == Path::new("") {
183 return Some(self);
184 }
185
186 let components: Vec<_> = path
188 .components()
189 .filter_map(|c| {
190 if let std::path::Component::Normal(s) = c {
191 s.to_str()
192 } else {
193 None
194 }
195 })
196 .collect();
197
198 if components.is_empty() {
199 return Some(self);
200 }
201
202 let mut current_node = self;
204 for component in components {
205 match current_node {
206 FileTreeNode::Directory { files } => {
207 current_node = files.get(component)?;
208 }
209 FileTreeNode::File { .. } => {
210 return None; }
212 }
213 }
214
215 Some(current_node)
216 }
217
218 pub fn get_file<P: AsRef<Path>>(&self, path: P) -> Option<&[u8]> {
220 match self.get_node(path)? {
221 FileTreeNode::File { contents } => Some(contents.as_slice()),
222 FileTreeNode::Directory { .. } => None,
223 }
224 }
225
226 pub fn file_exists<P: AsRef<Path>>(&self, path: P) -> bool {
228 matches!(self.get_node(path), Some(FileTreeNode::File { .. }))
229 }
230
231 pub fn dir_exists<P: AsRef<Path>>(&self, path: P) -> bool {
233 matches!(self.get_node(path), Some(FileTreeNode::Directory { .. }))
234 }
235
236 pub fn list_files<P: AsRef<Path>>(&self, dir_path: P) -> Vec<String> {
238 match self.get_node(dir_path) {
239 Some(FileTreeNode::Directory { files }) => files
240 .iter()
241 .filter_map(|(name, node)| {
242 if matches!(node, FileTreeNode::File { .. }) {
243 Some(name.clone())
244 } else {
245 None
246 }
247 })
248 .collect(),
249 _ => Vec::new(),
250 }
251 }
252
253 pub fn list_subdirectories<P: AsRef<Path>>(&self, dir_path: P) -> Vec<String> {
255 match self.get_node(dir_path) {
256 Some(FileTreeNode::Directory { files }) => files
257 .iter()
258 .filter_map(|(name, node)| {
259 if matches!(node, FileTreeNode::Directory { .. }) {
260 Some(name.clone())
261 } else {
262 None
263 }
264 })
265 .collect(),
266 _ => Vec::new(),
267 }
268 }
269
270 pub fn insert<P: AsRef<Path>>(
272 &mut self,
273 path: P,
274 node: FileTreeNode,
275 ) -> Result<(), Box<dyn StdError + Send + Sync>> {
276 let path = path.as_ref();
277
278 let components: Vec<_> = path
280 .components()
281 .filter_map(|c| {
282 if let std::path::Component::Normal(s) = c {
283 s.to_str().map(|s| s.to_string())
284 } else {
285 None
286 }
287 })
288 .collect();
289
290 if components.is_empty() {
291 return Err("Cannot insert at root path".into());
292 }
293
294 let mut current_node = self;
296 for component in &components[..components.len() - 1] {
297 match current_node {
298 FileTreeNode::Directory { files } => {
299 current_node =
300 files
301 .entry(component.clone())
302 .or_insert_with(|| FileTreeNode::Directory {
303 files: HashMap::new(),
304 });
305 }
306 FileTreeNode::File { .. } => {
307 return Err("Cannot traverse into a file".into());
308 }
309 }
310 }
311
312 let filename = &components[components.len() - 1];
314 match current_node {
315 FileTreeNode::Directory { files } => {
316 files.insert(filename.clone(), node);
317 Ok(())
318 }
319 FileTreeNode::File { .. } => Err("Cannot insert into a file".into()),
320 }
321 }
322
323 fn from_json_value(value: &serde_json::Value) -> Result<Self, Box<dyn StdError + Send + Sync>> {
325 if let Some(contents_str) = value.get("contents").and_then(|v| v.as_str()) {
326 Ok(FileTreeNode::File {
328 contents: contents_str.as_bytes().to_vec(),
329 })
330 } else if let Some(bytes_array) = value.get("contents").and_then(|v| v.as_array()) {
331 let contents: Vec<u8> = bytes_array
333 .iter()
334 .filter_map(|v| v.as_u64().and_then(|n| u8::try_from(n).ok()))
335 .collect();
336 Ok(FileTreeNode::File { contents })
337 } else if let Some(obj) = value.as_object() {
338 let mut files = HashMap::new();
340 for (name, child_value) in obj {
341 files.insert(name.clone(), Self::from_json_value(child_value)?);
342 }
343 Ok(FileTreeNode::Directory { files })
345 } else {
346 Err(format!("Invalid file tree node: {:?}", value).into())
347 }
348 }
349
350 pub fn print_tree(&self) -> String {
351 self.__print_tree("", "", true)
352 }
353
354 pub fn __print_tree(&self, name: &str, prefix: &str, is_last: bool) -> String {
355 let mut result = String::new();
356
357 let connector = if is_last { "└── " } else { "├── " };
359 let extension = if is_last { " " } else { "│ " };
360
361 match self {
362 FileTreeNode::File { .. } => {
363 result.push_str(&format!("{}{}{}\n", prefix, connector, name));
364 }
365 FileTreeNode::Directory { files } => {
366 result.push_str(&format!("{}{}{}/\n", prefix, connector, name));
368
369 let child_prefix = format!("{}{}", prefix, extension);
370 let count = files.len();
371
372 for (i, (child_name, node)) in files.iter().enumerate() {
373 let is_last_child = i == count - 1;
374 result.push_str(&node.__print_tree(child_name, &child_prefix, is_last_child));
375 }
376 }
377 }
378
379 result
380 }
381}
382
383#[derive(Debug, Clone)]
385pub struct QuillIgnore {
386 patterns: Vec<String>,
387}
388
389impl QuillIgnore {
390 pub fn new(patterns: Vec<String>) -> Self {
392 Self { patterns }
393 }
394
395 pub fn from_content(content: &str) -> Self {
397 let patterns = content
398 .lines()
399 .map(|line| line.trim())
400 .filter(|line| !line.is_empty() && !line.starts_with('#'))
401 .map(|line| line.to_string())
402 .collect();
403 Self::new(patterns)
404 }
405
406 pub fn is_ignored<P: AsRef<Path>>(&self, path: P) -> bool {
408 let path = path.as_ref();
409 let path_str = path.to_string_lossy();
410
411 for pattern in &self.patterns {
412 if self.matches_pattern(pattern, &path_str) {
413 return true;
414 }
415 }
416 false
417 }
418
419 fn matches_pattern(&self, pattern: &str, path: &str) -> bool {
421 if let Some(pattern_prefix) = pattern.strip_suffix('/') {
423 return path.starts_with(pattern_prefix)
424 && (path.len() == pattern_prefix.len()
425 || path.chars().nth(pattern_prefix.len()) == Some('/'));
426 }
427
428 if !pattern.contains('*') {
430 return path == pattern || path.ends_with(&format!("/{}", pattern));
431 }
432
433 if pattern == "*" {
435 return true;
436 }
437
438 let pattern_parts: Vec<&str> = pattern.split('*').collect();
440 if pattern_parts.len() == 2 {
441 let (prefix, suffix) = (pattern_parts[0], pattern_parts[1]);
442 if prefix.is_empty() {
443 return path.ends_with(suffix);
444 } else if suffix.is_empty() {
445 return path.starts_with(prefix);
446 } else {
447 return path.starts_with(prefix) && path.ends_with(suffix);
448 }
449 }
450
451 false
452 }
453}
454
455#[derive(Debug, Clone)]
457pub struct Quill {
458 pub metadata: HashMap<String, QuillValue>,
460 pub name: String,
462 pub backend: String,
464 pub plate: Option<String>,
466 pub example: Option<String>,
468 pub schema: QuillValue,
470 pub defaults: HashMap<String, QuillValue>,
472 pub examples: HashMap<String, Vec<QuillValue>>,
474 pub files: FileTreeNode,
476}
477
478#[derive(Debug, Clone)]
480pub struct QuillConfig {
481 pub name: String,
483 pub description: String,
485 pub backend: String,
487 pub version: Option<String>,
489 pub author: Option<String>,
491 pub example_file: Option<String>,
493 pub plate_file: Option<String>,
495 pub fields: HashMap<String, FieldSchema>,
497 pub cards: HashMap<String, CardSchema>,
499 pub metadata: HashMap<String, QuillValue>,
501 pub typst_config: HashMap<String, QuillValue>,
503}
504
505impl QuillConfig {
506 pub fn from_toml(toml_content: &str) -> Result<Self, Box<dyn StdError + Send + Sync>> {
508 let quill_toml: toml::Value = toml::from_str(toml_content)
509 .map_err(|e| format!("Failed to parse Quill.toml: {}", e))?;
510
511 let (field_order, card_order): (Vec<String>, Vec<String>) = toml_content
513 .parse::<toml_edit::DocumentMut>()
514 .ok()
515 .map(|doc| {
516 let f_order = doc
517 .get("fields")
518 .and_then(|item| item.as_table())
519 .map(|table| table.iter().map(|(k, _)| k.to_string()).collect())
520 .unwrap_or_default();
521
522 let s_order = doc
523 .get("cards")
524 .and_then(|item| item.as_table())
525 .map(|table| table.iter().map(|(k, _)| k.to_string()).collect())
526 .unwrap_or_default();
527
528 (f_order, s_order)
529 })
530 .unwrap_or_default();
531
532 let quill_section = quill_toml
534 .get("Quill")
535 .ok_or("Missing required [Quill] section in Quill.toml")?;
536
537 let name = quill_section
539 .get("name")
540 .and_then(|v| v.as_str())
541 .ok_or("Missing required 'name' field in [Quill] section")?
542 .to_string();
543
544 let backend = quill_section
545 .get("backend")
546 .and_then(|v| v.as_str())
547 .ok_or("Missing required 'backend' field in [Quill] section")?
548 .to_string();
549
550 let description = quill_section
551 .get("description")
552 .and_then(|v| v.as_str())
553 .ok_or("Missing required 'description' field in [Quill] section")?;
554
555 if description.trim().is_empty() {
556 return Err("'description' field in [Quill] section cannot be empty".into());
557 }
558 let description = description.to_string();
559
560 let version = quill_section
562 .get("version")
563 .and_then(|v| v.as_str())
564 .map(|s| s.to_string());
565
566 let author = quill_section
567 .get("author")
568 .and_then(|v| v.as_str())
569 .map(|s| s.to_string());
570
571 let example_file = quill_section
572 .get("example_file")
573 .and_then(|v| v.as_str())
574 .map(|s| s.to_string());
575
576 let plate_file = quill_section
577 .get("plate_file")
578 .and_then(|v| v.as_str())
579 .map(|s| s.to_string());
580
581 let mut metadata = HashMap::new();
583 if let toml::Value::Table(table) = quill_section {
584 for (key, value) in table {
585 if key != "name"
587 && key != "backend"
588 && key != "description"
589 && key != "version"
590 && key != "author"
591 && key != "example_file"
592 && key != "plate_file"
593 {
594 match QuillValue::from_toml(value) {
595 Ok(quill_value) => {
596 metadata.insert(key.clone(), quill_value);
597 }
598 Err(e) => {
599 eprintln!("Warning: Failed to convert field '{}': {}", key, e);
600 }
601 }
602 }
603 }
604 }
605
606 let mut typst_config = HashMap::new();
608 if let Some(toml::Value::Table(table)) = quill_toml.get("typst") {
609 for (key, value) in table {
610 match QuillValue::from_toml(value) {
611 Ok(quill_value) => {
612 typst_config.insert(key.clone(), quill_value);
613 }
614 Err(e) => {
615 eprintln!("Warning: Failed to convert typst field '{}': {}", key, e);
616 }
617 }
618 }
619 }
620
621 let mut fields = HashMap::new();
623 if let Some(toml::Value::Table(fields_table)) = quill_toml.get("fields") {
624 let mut order_counter = 0;
625 for (field_name, field_schema) in fields_table {
626 let order = if let Some(idx) = field_order.iter().position(|k| k == field_name) {
628 idx as i32
629 } else {
630 let o = field_order.len() as i32 + order_counter;
631 order_counter += 1;
632 o
633 };
634
635 match QuillValue::from_toml(field_schema) {
636 Ok(quill_value) => {
637 match FieldSchema::from_quill_value(field_name.clone(), &quill_value) {
638 Ok(mut schema) => {
639 if schema.ui.is_none() {
641 schema.ui = Some(UiSchema {
642 group: None,
643 order: Some(order),
644 });
645 } else if let Some(ui) = &mut schema.ui {
646 ui.order = Some(order);
647 }
648
649 fields.insert(field_name.clone(), schema);
650 }
651 Err(e) => {
652 eprintln!(
653 "Warning: Failed to parse field schema '{}': {}",
654 field_name, e
655 );
656 }
657 }
658 }
659 Err(e) => {
660 eprintln!(
661 "Warning: Failed to convert field schema '{}': {}",
662 field_name, e
663 );
664 }
665 }
666 }
667 }
668
669 let mut cards: HashMap<String, CardSchema> = HashMap::new();
671 if let Some(toml::Value::Table(cards_table)) = quill_toml.get("cards") {
672 let current_field_count = fields.len() as i32;
673 let mut order_counter = 0;
674
675 for (card_name, card_value) in cards_table {
676 if fields.contains_key(card_name) {
678 return Err(format!(
679 "Card definition '{}' conflicts with an existing field name",
680 card_name
681 )
682 .into());
683 }
684
685 let order = if let Some(idx) = card_order.iter().position(|k| k == card_name) {
687 current_field_count + idx as i32
688 } else {
689 let o = current_field_count + card_order.len() as i32 + order_counter;
690 order_counter += 1;
691 o
692 };
693
694 let card_table = card_value
696 .as_table()
697 .ok_or_else(|| format!("Card definition '{}' must be a table", card_name))?;
698
699 let title = card_table
700 .get("title")
701 .and_then(|v| v.as_str())
702 .map(|s| s.to_string());
703
704 let description = card_table
705 .get("description")
706 .and_then(|v| v.as_str())
707 .unwrap_or("")
708 .to_string();
709
710 let ui = if let Some(ui_value) = card_table.get("ui") {
712 if let Some(ui_table) = ui_value.as_table() {
713 let group = ui_table
714 .get("group")
715 .and_then(|v| v.as_str())
716 .map(|s| s.to_string());
717 Some(UiSchema {
718 group,
719 order: Some(order),
720 })
721 } else {
722 None
723 }
724 } else {
725 Some(UiSchema {
726 group: None,
727 order: Some(order),
728 })
729 };
730
731 let mut card_fields: HashMap<String, FieldSchema> = HashMap::new();
733 if let Some(fields_value) = card_table.get("fields") {
734 if let Some(fields_table) = fields_value.as_table() {
735 for (field_name, field_value) in fields_table {
736 match QuillValue::from_toml(field_value) {
737 Ok(quill_value) => {
738 match FieldSchema::from_quill_value(
739 field_name.clone(),
740 &quill_value,
741 ) {
742 Ok(field_schema) => {
743 card_fields.insert(field_name.clone(), field_schema);
744 }
745 Err(e) => {
746 eprintln!(
747 "Warning: Failed to parse card field '{}.{}': {}",
748 card_name, field_name, e
749 );
750 }
751 }
752 }
753 Err(e) => {
754 eprintln!(
755 "Warning: Failed to convert card field '{}.{}': {}",
756 card_name, field_name, e
757 );
758 }
759 }
760 }
761 }
762 }
763
764 let card_schema = CardSchema {
765 name: card_name.clone(),
766 title,
767 description,
768 ui,
769 fields: card_fields,
770 };
771
772 cards.insert(card_name.clone(), card_schema);
773 }
774 }
775
776 Ok(QuillConfig {
777 name,
778 description,
779 backend,
780 version,
781 author,
782 example_file,
783 plate_file,
784 fields,
785 cards,
786 metadata,
787 typst_config,
788 })
789 }
790}
791
792impl Quill {
793 pub fn from_path<P: AsRef<std::path::Path>>(
795 path: P,
796 ) -> Result<Self, Box<dyn StdError + Send + Sync>> {
797 use std::fs;
798
799 let path = path.as_ref();
800 let name = path
801 .file_name()
802 .and_then(|n| n.to_str())
803 .unwrap_or("unnamed")
804 .to_string();
805
806 let quillignore_path = path.join(".quillignore");
808 let ignore = if quillignore_path.exists() {
809 let ignore_content = fs::read_to_string(&quillignore_path)
810 .map_err(|e| format!("Failed to read .quillignore: {}", e))?;
811 QuillIgnore::from_content(&ignore_content)
812 } else {
813 QuillIgnore::new(vec![
815 ".git/".to_string(),
816 ".gitignore".to_string(),
817 ".quillignore".to_string(),
818 "target/".to_string(),
819 "node_modules/".to_string(),
820 ])
821 };
822
823 let root = Self::load_directory_as_tree(path, path, &ignore)?;
825
826 Self::from_tree(root, Some(name))
828 }
829
830 pub fn from_tree(
847 root: FileTreeNode,
848 _default_name: Option<String>,
849 ) -> Result<Self, Box<dyn StdError + Send + Sync>> {
850 let quill_toml_bytes = root
852 .get_file("Quill.toml")
853 .ok_or("Quill.toml not found in file tree")?;
854
855 let quill_toml_content = String::from_utf8(quill_toml_bytes.to_vec())
856 .map_err(|e| format!("Quill.toml is not valid UTF-8: {}", e))?;
857
858 let config = QuillConfig::from_toml(&quill_toml_content)?;
860
861 Self::from_config(config, root)
863 }
864
865 fn from_config(
882 config: QuillConfig,
883 root: FileTreeNode,
884 ) -> Result<Self, Box<dyn StdError + Send + Sync>> {
885 let mut metadata = config.metadata.clone();
887
888 metadata.insert(
890 "backend".to_string(),
891 QuillValue::from_json(serde_json::Value::String(config.backend.clone())),
892 );
893
894 metadata.insert(
896 "description".to_string(),
897 QuillValue::from_json(serde_json::Value::String(config.description.clone())),
898 );
899
900 if let Some(ref author) = config.author {
902 metadata.insert(
903 "author".to_string(),
904 QuillValue::from_json(serde_json::Value::String(author.clone())),
905 );
906 }
907
908 for (key, value) in &config.typst_config {
910 metadata.insert(format!("typst_{}", key), value.clone());
911 }
912
913 let schema = crate::schema::build_schema(&config.fields, &config.cards)
915 .map_err(|e| format!("Failed to build JSON schema from field schemas: {}", e))?;
916
917 let plate_content: Option<String> = if let Some(ref plate_file_name) = config.plate_file {
919 let plate_bytes = root.get_file(plate_file_name).ok_or_else(|| {
920 format!("Plate file '{}' not found in file tree", plate_file_name)
921 })?;
922
923 let content = String::from_utf8(plate_bytes.to_vec()).map_err(|e| {
924 format!("Plate file '{}' is not valid UTF-8: {}", plate_file_name, e)
925 })?;
926 Some(content)
927 } else {
928 None
930 };
931
932 let example_content = if let Some(ref example_file_name) = config.example_file {
934 root.get_file(example_file_name).and_then(|bytes| {
935 String::from_utf8(bytes.to_vec())
936 .map_err(|e| {
937 eprintln!(
938 "Warning: Example file '{}' is not valid UTF-8: {}",
939 example_file_name, e
940 );
941 e
942 })
943 .ok()
944 })
945 } else {
946 None
947 };
948
949 let defaults = crate::schema::extract_defaults_from_schema(&schema);
951 let examples = crate::schema::extract_examples_from_schema(&schema);
952
953 let quill = Quill {
954 metadata,
955 name: config.name,
956 backend: config.backend,
957 plate: plate_content,
958 example: example_content,
959 schema,
960 defaults,
961 examples,
962 files: root,
963 };
964
965 Ok(quill)
966 }
967
968 pub fn from_json(json_str: &str) -> Result<Self, Box<dyn StdError + Send + Sync>> {
975 use serde_json::Value as JsonValue;
976
977 let json: JsonValue =
978 serde_json::from_str(json_str).map_err(|e| format!("Failed to parse JSON: {}", e))?;
979
980 let obj = json.as_object().ok_or("Root must be an object")?;
981
982 let default_name = obj
984 .get("metadata")
985 .and_then(|m| m.get("name"))
986 .and_then(|v| v.as_str())
987 .map(String::from);
988
989 let files_obj = obj
991 .get("files")
992 .and_then(|v| v.as_object())
993 .ok_or("Missing or invalid 'files' key")?;
994
995 let mut root_files = HashMap::new();
997 for (key, value) in files_obj {
998 root_files.insert(key.clone(), FileTreeNode::from_json_value(value)?);
999 }
1000
1001 let root = FileTreeNode::Directory { files: root_files };
1002
1003 Self::from_tree(root, default_name)
1005 }
1006
1007 fn load_directory_as_tree(
1009 current_dir: &Path,
1010 base_dir: &Path,
1011 ignore: &QuillIgnore,
1012 ) -> Result<FileTreeNode, Box<dyn StdError + Send + Sync>> {
1013 use std::fs;
1014
1015 if !current_dir.exists() {
1016 return Ok(FileTreeNode::Directory {
1017 files: HashMap::new(),
1018 });
1019 }
1020
1021 let mut files = HashMap::new();
1022
1023 for entry in fs::read_dir(current_dir)? {
1024 let entry = entry?;
1025 let path = entry.path();
1026 let relative_path = path
1027 .strip_prefix(base_dir)
1028 .map_err(|e| format!("Failed to get relative path: {}", e))?
1029 .to_path_buf();
1030
1031 if ignore.is_ignored(&relative_path) {
1033 continue;
1034 }
1035
1036 let filename = path
1038 .file_name()
1039 .and_then(|n| n.to_str())
1040 .ok_or_else(|| format!("Invalid filename: {}", path.display()))?
1041 .to_string();
1042
1043 if path.is_file() {
1044 let contents = fs::read(&path)
1045 .map_err(|e| format!("Failed to read file '{}': {}", path.display(), e))?;
1046
1047 files.insert(filename, FileTreeNode::File { contents });
1048 } else if path.is_dir() {
1049 let subdir_tree = Self::load_directory_as_tree(&path, base_dir, ignore)?;
1051 files.insert(filename, subdir_tree);
1052 }
1053 }
1054
1055 Ok(FileTreeNode::Directory { files })
1056 }
1057
1058 pub fn typst_packages(&self) -> Vec<String> {
1060 self.metadata
1061 .get("typst_packages")
1062 .and_then(|v| v.as_array())
1063 .map(|arr| {
1064 arr.iter()
1065 .filter_map(|v| v.as_str().map(|s| s.to_string()))
1066 .collect()
1067 })
1068 .unwrap_or_default()
1069 }
1070
1071 pub fn extract_defaults(&self) -> &HashMap<String, QuillValue> {
1079 &self.defaults
1080 }
1081
1082 pub fn extract_examples(&self) -> &HashMap<String, Vec<QuillValue>> {
1087 &self.examples
1088 }
1089
1090 pub fn get_file<P: AsRef<Path>>(&self, path: P) -> Option<&[u8]> {
1092 self.files.get_file(path)
1093 }
1094
1095 pub fn file_exists<P: AsRef<Path>>(&self, path: P) -> bool {
1097 self.files.file_exists(path)
1098 }
1099
1100 pub fn dir_exists<P: AsRef<Path>>(&self, path: P) -> bool {
1102 self.files.dir_exists(path)
1103 }
1104
1105 pub fn list_files<P: AsRef<Path>>(&self, path: P) -> Vec<String> {
1107 self.files.list_files(path)
1108 }
1109
1110 pub fn list_subdirectories<P: AsRef<Path>>(&self, path: P) -> Vec<String> {
1112 self.files.list_subdirectories(path)
1113 }
1114
1115 pub fn list_directory<P: AsRef<Path>>(&self, dir_path: P) -> Vec<PathBuf> {
1117 let dir_path = dir_path.as_ref();
1118 let filenames = self.files.list_files(dir_path);
1119
1120 filenames
1122 .iter()
1123 .map(|name| {
1124 if dir_path == Path::new("") {
1125 PathBuf::from(name)
1126 } else {
1127 dir_path.join(name)
1128 }
1129 })
1130 .collect()
1131 }
1132
1133 pub fn list_directories<P: AsRef<Path>>(&self, dir_path: P) -> Vec<PathBuf> {
1135 let dir_path = dir_path.as_ref();
1136 let subdirs = self.files.list_subdirectories(dir_path);
1137
1138 subdirs
1140 .iter()
1141 .map(|name| {
1142 if dir_path == Path::new("") {
1143 PathBuf::from(name)
1144 } else {
1145 dir_path.join(name)
1146 }
1147 })
1148 .collect()
1149 }
1150
1151 pub fn find_files<P: AsRef<Path>>(&self, pattern: P) -> Vec<PathBuf> {
1153 let pattern_str = pattern.as_ref().to_string_lossy();
1154 let mut matches = Vec::new();
1155
1156 let glob_pattern = match glob::Pattern::new(&pattern_str) {
1158 Ok(pat) => pat,
1159 Err(_) => return matches, };
1161
1162 Self::find_files_recursive(&self.files, Path::new(""), &glob_pattern, &mut matches);
1164
1165 matches.sort();
1166 matches
1167 }
1168
1169 fn find_files_recursive(
1171 node: &FileTreeNode,
1172 current_path: &Path,
1173 pattern: &glob::Pattern,
1174 matches: &mut Vec<PathBuf>,
1175 ) {
1176 match node {
1177 FileTreeNode::File { .. } => {
1178 let path_str = current_path.to_string_lossy();
1179 if pattern.matches(&path_str) {
1180 matches.push(current_path.to_path_buf());
1181 }
1182 }
1183 FileTreeNode::Directory { files } => {
1184 for (name, child_node) in files {
1185 let child_path = if current_path == Path::new("") {
1186 PathBuf::from(name)
1187 } else {
1188 current_path.join(name)
1189 };
1190 Self::find_files_recursive(child_node, &child_path, pattern, matches);
1191 }
1192 }
1193 }
1194 }
1195}
1196
1197#[cfg(test)]
1198mod tests {
1199 use super::*;
1200 use std::fs;
1201 use tempfile::TempDir;
1202
1203 #[test]
1204 fn test_quillignore_parsing() {
1205 let ignore_content = r#"
1206# This is a comment
1207*.tmp
1208target/
1209node_modules/
1210.git/
1211"#;
1212 let ignore = QuillIgnore::from_content(ignore_content);
1213 assert_eq!(ignore.patterns.len(), 4);
1214 assert!(ignore.patterns.contains(&"*.tmp".to_string()));
1215 assert!(ignore.patterns.contains(&"target/".to_string()));
1216 }
1217
1218 #[test]
1219 fn test_quillignore_matching() {
1220 let ignore = QuillIgnore::new(vec![
1221 "*.tmp".to_string(),
1222 "target/".to_string(),
1223 "node_modules/".to_string(),
1224 ".git/".to_string(),
1225 ]);
1226
1227 assert!(ignore.is_ignored("test.tmp"));
1229 assert!(ignore.is_ignored("path/to/file.tmp"));
1230 assert!(!ignore.is_ignored("test.txt"));
1231
1232 assert!(ignore.is_ignored("target"));
1234 assert!(ignore.is_ignored("target/debug"));
1235 assert!(ignore.is_ignored("target/debug/deps"));
1236 assert!(!ignore.is_ignored("src/target.rs"));
1237
1238 assert!(ignore.is_ignored("node_modules"));
1239 assert!(ignore.is_ignored("node_modules/package"));
1240 assert!(!ignore.is_ignored("my_node_modules"));
1241 }
1242
1243 #[test]
1244 fn test_in_memory_file_system() {
1245 let temp_dir = TempDir::new().unwrap();
1246 let quill_dir = temp_dir.path();
1247
1248 fs::write(
1250 quill_dir.join("Quill.toml"),
1251 "[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"",
1252 )
1253 .unwrap();
1254 fs::write(quill_dir.join("plate.typ"), "test plate").unwrap();
1255
1256 let assets_dir = quill_dir.join("assets");
1257 fs::create_dir_all(&assets_dir).unwrap();
1258 fs::write(assets_dir.join("test.txt"), "asset content").unwrap();
1259
1260 let packages_dir = quill_dir.join("packages");
1261 fs::create_dir_all(&packages_dir).unwrap();
1262 fs::write(packages_dir.join("package.typ"), "package content").unwrap();
1263
1264 let quill = Quill::from_path(quill_dir).unwrap();
1266
1267 assert!(quill.file_exists("plate.typ"));
1269 assert!(quill.file_exists("assets/test.txt"));
1270 assert!(quill.file_exists("packages/package.typ"));
1271 assert!(!quill.file_exists("nonexistent.txt"));
1272
1273 let asset_content = quill.get_file("assets/test.txt").unwrap();
1275 assert_eq!(asset_content, b"asset content");
1276
1277 let asset_files = quill.list_directory("assets");
1279 assert_eq!(asset_files.len(), 1);
1280 assert!(asset_files.contains(&PathBuf::from("assets/test.txt")));
1281 }
1282
1283 #[test]
1284 fn test_quillignore_integration() {
1285 let temp_dir = TempDir::new().unwrap();
1286 let quill_dir = temp_dir.path();
1287
1288 fs::write(quill_dir.join(".quillignore"), "*.tmp\ntarget/\n").unwrap();
1290
1291 fs::write(
1293 quill_dir.join("Quill.toml"),
1294 "[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"",
1295 )
1296 .unwrap();
1297 fs::write(quill_dir.join("plate.typ"), "test template").unwrap();
1298 fs::write(quill_dir.join("should_ignore.tmp"), "ignored").unwrap();
1299
1300 let target_dir = quill_dir.join("target");
1301 fs::create_dir_all(&target_dir).unwrap();
1302 fs::write(target_dir.join("debug.txt"), "also ignored").unwrap();
1303
1304 let quill = Quill::from_path(quill_dir).unwrap();
1306
1307 assert!(quill.file_exists("plate.typ"));
1309 assert!(!quill.file_exists("should_ignore.tmp"));
1310 assert!(!quill.file_exists("target/debug.txt"));
1311 }
1312
1313 #[test]
1314 fn test_find_files_pattern() {
1315 let temp_dir = TempDir::new().unwrap();
1316 let quill_dir = temp_dir.path();
1317
1318 fs::write(
1320 quill_dir.join("Quill.toml"),
1321 "[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"",
1322 )
1323 .unwrap();
1324 fs::write(quill_dir.join("plate.typ"), "template").unwrap();
1325
1326 let assets_dir = quill_dir.join("assets");
1327 fs::create_dir_all(&assets_dir).unwrap();
1328 fs::write(assets_dir.join("image.png"), "png data").unwrap();
1329 fs::write(assets_dir.join("data.json"), "json data").unwrap();
1330
1331 let fonts_dir = assets_dir.join("fonts");
1332 fs::create_dir_all(&fonts_dir).unwrap();
1333 fs::write(fonts_dir.join("font.ttf"), "font data").unwrap();
1334
1335 let quill = Quill::from_path(quill_dir).unwrap();
1337
1338 let all_assets = quill.find_files("assets/*");
1340 assert!(all_assets.len() >= 3); let typ_files = quill.find_files("*.typ");
1343 assert_eq!(typ_files.len(), 1);
1344 assert!(typ_files.contains(&PathBuf::from("plate.typ")));
1345 }
1346
1347 #[test]
1348 fn test_new_standardized_toml_format() {
1349 let temp_dir = TempDir::new().unwrap();
1350 let quill_dir = temp_dir.path();
1351
1352 let toml_content = r#"[Quill]
1354name = "my-custom-quill"
1355backend = "typst"
1356plate_file = "custom_plate.typ"
1357description = "Test quill with new format"
1358author = "Test Author"
1359"#;
1360 fs::write(quill_dir.join("Quill.toml"), toml_content).unwrap();
1361 fs::write(
1362 quill_dir.join("custom_plate.typ"),
1363 "= Custom Template\n\nThis is a custom template.",
1364 )
1365 .unwrap();
1366
1367 let quill = Quill::from_path(quill_dir).unwrap();
1369
1370 assert_eq!(quill.name, "my-custom-quill");
1372
1373 assert!(quill.metadata.contains_key("backend"));
1375 if let Some(backend_val) = quill.metadata.get("backend") {
1376 if let Some(backend_str) = backend_val.as_str() {
1377 assert_eq!(backend_str, "typst");
1378 } else {
1379 panic!("Backend value is not a string");
1380 }
1381 }
1382
1383 assert!(quill.metadata.contains_key("description"));
1385 assert!(quill.metadata.contains_key("author"));
1386 assert!(!quill.metadata.contains_key("version")); assert!(quill.plate.unwrap().contains("Custom Template"));
1390 }
1391
1392 #[test]
1393 fn test_typst_packages_parsing() {
1394 let temp_dir = TempDir::new().unwrap();
1395 let quill_dir = temp_dir.path();
1396
1397 let toml_content = r#"
1398[Quill]
1399name = "test-quill"
1400backend = "typst"
1401plate_file = "plate.typ"
1402description = "Test quill for packages"
1403
1404[typst]
1405packages = ["@preview/bubble:0.2.2", "@preview/example:1.0.0"]
1406"#;
1407
1408 fs::write(quill_dir.join("Quill.toml"), toml_content).unwrap();
1409 fs::write(quill_dir.join("plate.typ"), "test").unwrap();
1410
1411 let quill = Quill::from_path(quill_dir).unwrap();
1412 let packages = quill.typst_packages();
1413
1414 assert_eq!(packages.len(), 2);
1415 assert_eq!(packages[0], "@preview/bubble:0.2.2");
1416 assert_eq!(packages[1], "@preview/example:1.0.0");
1417 }
1418
1419 #[test]
1420 fn test_template_loading() {
1421 let temp_dir = TempDir::new().unwrap();
1422 let quill_dir = temp_dir.path();
1423
1424 let toml_content = r#"[Quill]
1426name = "test-with-template"
1427backend = "typst"
1428plate_file = "plate.typ"
1429example_file = "example.md"
1430description = "Test quill with template"
1431"#;
1432 fs::write(quill_dir.join("Quill.toml"), toml_content).unwrap();
1433 fs::write(quill_dir.join("plate.typ"), "plate content").unwrap();
1434 fs::write(
1435 quill_dir.join("example.md"),
1436 "---\ntitle: Test\n---\n\nThis is a test template.",
1437 )
1438 .unwrap();
1439
1440 let quill = Quill::from_path(quill_dir).unwrap();
1442
1443 assert!(quill.example.is_some());
1445 let example = quill.example.unwrap();
1446 assert!(example.contains("title: Test"));
1447 assert!(example.contains("This is a test template"));
1448
1449 assert_eq!(quill.plate.unwrap(), "plate content");
1451 }
1452
1453 #[test]
1454 fn test_template_optional() {
1455 let temp_dir = TempDir::new().unwrap();
1456 let quill_dir = temp_dir.path();
1457
1458 let toml_content = r#"[Quill]
1460name = "test-without-template"
1461backend = "typst"
1462plate_file = "plate.typ"
1463description = "Test quill without template"
1464"#;
1465 fs::write(quill_dir.join("Quill.toml"), toml_content).unwrap();
1466 fs::write(quill_dir.join("plate.typ"), "plate content").unwrap();
1467
1468 let quill = Quill::from_path(quill_dir).unwrap();
1470
1471 assert_eq!(quill.example, None);
1473
1474 assert_eq!(quill.plate.unwrap(), "plate content");
1476 }
1477
1478 #[test]
1479 fn test_from_tree() {
1480 let mut root_files = HashMap::new();
1482
1483 let quill_toml = r#"[Quill]
1485name = "test-from-tree"
1486backend = "typst"
1487plate_file = "plate.typ"
1488description = "A test quill from tree"
1489"#;
1490 root_files.insert(
1491 "Quill.toml".to_string(),
1492 FileTreeNode::File {
1493 contents: quill_toml.as_bytes().to_vec(),
1494 },
1495 );
1496
1497 let plate_content = "= Test Template\n\nThis is a test.";
1499 root_files.insert(
1500 "plate.typ".to_string(),
1501 FileTreeNode::File {
1502 contents: plate_content.as_bytes().to_vec(),
1503 },
1504 );
1505
1506 let root = FileTreeNode::Directory { files: root_files };
1507
1508 let quill = Quill::from_tree(root, Some("test-from-tree".to_string())).unwrap();
1510
1511 assert_eq!(quill.name, "test-from-tree");
1513 assert_eq!(quill.plate.unwrap(), plate_content);
1514 assert!(quill.metadata.contains_key("backend"));
1515 assert!(quill.metadata.contains_key("description"));
1516 }
1517
1518 #[test]
1519 fn test_from_tree_with_template() {
1520 let mut root_files = HashMap::new();
1521
1522 let quill_toml = r#"[Quill]
1524name = "test-tree-template"
1525backend = "typst"
1526plate_file = "plate.typ"
1527example_file = "template.md"
1528description = "Test tree with template"
1529"#;
1530 root_files.insert(
1531 "Quill.toml".to_string(),
1532 FileTreeNode::File {
1533 contents: quill_toml.as_bytes().to_vec(),
1534 },
1535 );
1536
1537 root_files.insert(
1539 "plate.typ".to_string(),
1540 FileTreeNode::File {
1541 contents: b"plate content".to_vec(),
1542 },
1543 );
1544
1545 let template_content = "# {{ title }}\n\n{{ body }}";
1547 root_files.insert(
1548 "template.md".to_string(),
1549 FileTreeNode::File {
1550 contents: template_content.as_bytes().to_vec(),
1551 },
1552 );
1553
1554 let root = FileTreeNode::Directory { files: root_files };
1555
1556 let quill = Quill::from_tree(root, None).unwrap();
1558
1559 assert_eq!(quill.example, Some(template_content.to_string()));
1561 }
1562
1563 #[test]
1564 fn test_from_json() {
1565 let json_str = r#"{
1567 "metadata": {
1568 "name": "test-from-json"
1569 },
1570 "files": {
1571 "Quill.toml": {
1572 "contents": "[Quill]\nname = \"test-from-json\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill from JSON\"\n"
1573 },
1574 "plate.typ": {
1575 "contents": "= Test Plate\n\nThis is test content."
1576 }
1577 }
1578 }"#;
1579
1580 let quill = Quill::from_json(json_str).unwrap();
1582
1583 assert_eq!(quill.name, "test-from-json");
1585 assert!(quill.plate.unwrap().contains("Test Plate"));
1586 assert!(quill.metadata.contains_key("backend"));
1587 }
1588
1589 #[test]
1590 fn test_from_json_with_byte_array() {
1591 let json_str = r#"{
1593 "files": {
1594 "Quill.toml": {
1595 "contents": "[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"\n"
1596 },
1597 "plate.typ": {
1598 "contents": "test plate"
1599 }
1600 }
1601 }"#;
1602
1603 let quill = Quill::from_json(json_str).unwrap();
1605
1606 assert_eq!(quill.name, "test");
1608 assert_eq!(quill.plate.unwrap(), "test plate");
1609 }
1610
1611 #[test]
1612 fn test_from_json_missing_files() {
1613 let json_str = r#"{
1615 "metadata": {
1616 "name": "test"
1617 }
1618 }"#;
1619
1620 let result = Quill::from_json(json_str);
1621 assert!(result.is_err());
1622 assert!(result.unwrap_err().to_string().contains("files"));
1624 }
1625
1626 #[test]
1627 fn test_from_json_tree_structure() {
1628 let json_str = r#"{
1630 "files": {
1631 "Quill.toml": {
1632 "contents": "[Quill]\nname = \"test-tree-json\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test tree JSON\"\n"
1633 },
1634 "plate.typ": {
1635 "contents": "= Test Plate\n\nTree structure content."
1636 }
1637 }
1638 }"#;
1639
1640 let quill = Quill::from_json(json_str).unwrap();
1641
1642 assert_eq!(quill.name, "test-tree-json");
1643 assert!(quill.plate.unwrap().contains("Tree structure content"));
1644 assert!(quill.metadata.contains_key("backend"));
1645 }
1646
1647 #[test]
1648 fn test_from_json_nested_tree_structure() {
1649 let json_str = r#"{
1651 "files": {
1652 "Quill.toml": {
1653 "contents": "[Quill]\nname = \"nested-test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Nested test\"\n"
1654 },
1655 "plate.typ": {
1656 "contents": "plate"
1657 },
1658 "src": {
1659 "main.rs": {
1660 "contents": "fn main() {}"
1661 },
1662 "lib.rs": {
1663 "contents": "// lib"
1664 }
1665 }
1666 }
1667 }"#;
1668
1669 let quill = Quill::from_json(json_str).unwrap();
1670
1671 assert_eq!(quill.name, "nested-test");
1672 assert!(quill.file_exists("src/main.rs"));
1674 assert!(quill.file_exists("src/lib.rs"));
1675
1676 let main_rs = quill.get_file("src/main.rs").unwrap();
1677 assert_eq!(main_rs, b"fn main() {}");
1678 }
1679
1680 #[test]
1681 fn test_from_tree_structure_direct() {
1682 let mut root_files = HashMap::new();
1684
1685 root_files.insert(
1686 "Quill.toml".to_string(),
1687 FileTreeNode::File {
1688 contents:
1689 b"[Quill]\nname = \"direct-tree\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Direct tree test\"\n"
1690 .to_vec(),
1691 },
1692 );
1693
1694 root_files.insert(
1695 "plate.typ".to_string(),
1696 FileTreeNode::File {
1697 contents: b"plate content".to_vec(),
1698 },
1699 );
1700
1701 let mut src_files = HashMap::new();
1703 src_files.insert(
1704 "main.rs".to_string(),
1705 FileTreeNode::File {
1706 contents: b"fn main() {}".to_vec(),
1707 },
1708 );
1709
1710 root_files.insert(
1711 "src".to_string(),
1712 FileTreeNode::Directory { files: src_files },
1713 );
1714
1715 let root = FileTreeNode::Directory { files: root_files };
1716
1717 let quill = Quill::from_tree(root, None).unwrap();
1718
1719 assert_eq!(quill.name, "direct-tree");
1720 assert!(quill.file_exists("src/main.rs"));
1721 assert!(quill.file_exists("plate.typ"));
1722 }
1723
1724 #[test]
1725 fn test_from_json_with_metadata_override() {
1726 let json_str = r#"{
1728 "metadata": {
1729 "name": "override-name"
1730 },
1731 "files": {
1732 "Quill.toml": {
1733 "contents": "[Quill]\nname = \"toml-name\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"TOML name test\"\n"
1734 },
1735 "plate.typ": {
1736 "contents": "= plate"
1737 }
1738 }
1739 }"#;
1740
1741 let quill = Quill::from_json(json_str).unwrap();
1742 assert_eq!(quill.name, "toml-name");
1745 }
1746
1747 #[test]
1748 fn test_from_json_empty_directory() {
1749 let json_str = r#"{
1751 "files": {
1752 "Quill.toml": {
1753 "contents": "[Quill]\nname = \"empty-dir-test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Empty directory test\"\n"
1754 },
1755 "plate.typ": {
1756 "contents": "plate"
1757 },
1758 "empty_dir": {}
1759 }
1760 }"#;
1761
1762 let quill = Quill::from_json(json_str).unwrap();
1763 assert_eq!(quill.name, "empty-dir-test");
1764 assert!(quill.dir_exists("empty_dir"));
1765 assert!(!quill.file_exists("empty_dir"));
1766 }
1767
1768 #[test]
1769 fn test_dir_exists_and_list_apis() {
1770 let mut root_files = HashMap::new();
1771
1772 root_files.insert(
1774 "Quill.toml".to_string(),
1775 FileTreeNode::File {
1776 contents: b"[Quill]\nname = \"test\"\nbackend = \"typst\"\nplate_file = \"plate.typ\"\ndescription = \"Test quill\"\n"
1777 .to_vec(),
1778 },
1779 );
1780
1781 root_files.insert(
1783 "plate.typ".to_string(),
1784 FileTreeNode::File {
1785 contents: b"plate content".to_vec(),
1786 },
1787 );
1788
1789 let mut assets_files = HashMap::new();
1791 assets_files.insert(
1792 "logo.png".to_string(),
1793 FileTreeNode::File {
1794 contents: vec![137, 80, 78, 71],
1795 },
1796 );
1797 assets_files.insert(
1798 "icon.svg".to_string(),
1799 FileTreeNode::File {
1800 contents: b"<svg></svg>".to_vec(),
1801 },
1802 );
1803
1804 let mut fonts_files = HashMap::new();
1806 fonts_files.insert(
1807 "font.ttf".to_string(),
1808 FileTreeNode::File {
1809 contents: b"font data".to_vec(),
1810 },
1811 );
1812 assets_files.insert(
1813 "fonts".to_string(),
1814 FileTreeNode::Directory { files: fonts_files },
1815 );
1816
1817 root_files.insert(
1818 "assets".to_string(),
1819 FileTreeNode::Directory {
1820 files: assets_files,
1821 },
1822 );
1823
1824 root_files.insert(
1826 "empty".to_string(),
1827 FileTreeNode::Directory {
1828 files: HashMap::new(),
1829 },
1830 );
1831
1832 let root = FileTreeNode::Directory { files: root_files };
1833 let quill = Quill::from_tree(root, None).unwrap();
1834
1835 assert!(quill.dir_exists("assets"));
1837 assert!(quill.dir_exists("assets/fonts"));
1838 assert!(quill.dir_exists("empty"));
1839 assert!(!quill.dir_exists("nonexistent"));
1840 assert!(!quill.dir_exists("plate.typ")); assert!(quill.file_exists("plate.typ"));
1844 assert!(quill.file_exists("assets/logo.png"));
1845 assert!(quill.file_exists("assets/fonts/font.ttf"));
1846 assert!(!quill.file_exists("assets")); let root_files_list = quill.list_files("");
1850 assert_eq!(root_files_list.len(), 2); assert!(root_files_list.contains(&"Quill.toml".to_string()));
1852 assert!(root_files_list.contains(&"plate.typ".to_string()));
1853
1854 let assets_files_list = quill.list_files("assets");
1855 assert_eq!(assets_files_list.len(), 2); assert!(assets_files_list.contains(&"logo.png".to_string()));
1857 assert!(assets_files_list.contains(&"icon.svg".to_string()));
1858
1859 let root_subdirs = quill.list_subdirectories("");
1861 assert_eq!(root_subdirs.len(), 2); assert!(root_subdirs.contains(&"assets".to_string()));
1863 assert!(root_subdirs.contains(&"empty".to_string()));
1864
1865 let assets_subdirs = quill.list_subdirectories("assets");
1866 assert_eq!(assets_subdirs.len(), 1); assert!(assets_subdirs.contains(&"fonts".to_string()));
1868
1869 let empty_subdirs = quill.list_subdirectories("empty");
1870 assert_eq!(empty_subdirs.len(), 0);
1871 }
1872
1873 #[test]
1874 fn test_field_schemas_parsing() {
1875 let mut root_files = HashMap::new();
1876
1877 let quill_toml = r#"[Quill]
1879name = "taro"
1880backend = "typst"
1881plate_file = "plate.typ"
1882example_file = "taro.md"
1883description = "Test template for field schemas"
1884
1885[fields]
1886author = {description = "Author of document" }
1887ice_cream = {description = "favorite ice cream flavor"}
1888title = {description = "title of document" }
1889"#;
1890 root_files.insert(
1891 "Quill.toml".to_string(),
1892 FileTreeNode::File {
1893 contents: quill_toml.as_bytes().to_vec(),
1894 },
1895 );
1896
1897 let plate_content = "= Test Template\n\nThis is a test.";
1899 root_files.insert(
1900 "plate.typ".to_string(),
1901 FileTreeNode::File {
1902 contents: plate_content.as_bytes().to_vec(),
1903 },
1904 );
1905
1906 root_files.insert(
1908 "taro.md".to_string(),
1909 FileTreeNode::File {
1910 contents: b"# Template".to_vec(),
1911 },
1912 );
1913
1914 let root = FileTreeNode::Directory { files: root_files };
1915
1916 let quill = Quill::from_tree(root, Some("taro".to_string())).unwrap();
1918
1919 assert_eq!(quill.schema["properties"].as_object().unwrap().len(), 3);
1921 assert!(quill.schema["properties"]
1922 .as_object()
1923 .unwrap()
1924 .contains_key("author"));
1925 assert!(quill.schema["properties"]
1926 .as_object()
1927 .unwrap()
1928 .contains_key("ice_cream"));
1929 assert!(quill.schema["properties"]
1930 .as_object()
1931 .unwrap()
1932 .contains_key("title"));
1933
1934 let author_schema = quill.schema["properties"]["author"].as_object().unwrap();
1936 assert_eq!(author_schema["description"], "Author of document");
1937
1938 let ice_cream_schema = quill.schema["properties"]["ice_cream"].as_object().unwrap();
1940 assert_eq!(ice_cream_schema["description"], "favorite ice cream flavor");
1941
1942 let title_schema = quill.schema["properties"]["title"].as_object().unwrap();
1944 assert_eq!(title_schema["description"], "title of document");
1945 }
1946
1947 #[test]
1948 fn test_field_schema_struct() {
1949 let schema1 = FieldSchema::new("test_name".to_string(), "Test description".to_string());
1951 assert_eq!(schema1.description, "Test description");
1952 assert_eq!(schema1.r#type, None);
1953 assert_eq!(schema1.examples, None);
1954 assert_eq!(schema1.default, None);
1955
1956 let yaml_str = r#"
1958description: "Full field schema"
1959type: "string"
1960examples:
1961 - "Example value"
1962default: "Default value"
1963"#;
1964 let yaml_value: serde_yaml::Value = serde_yaml::from_str(yaml_str).unwrap();
1965 let quill_value = QuillValue::from_yaml(yaml_value).unwrap();
1966 let schema2 = FieldSchema::from_quill_value("test_name".to_string(), &quill_value).unwrap();
1967 assert_eq!(schema2.name, "test_name");
1968 assert_eq!(schema2.description, "Full field schema");
1969 assert_eq!(schema2.r#type, Some("string".to_string()));
1970 assert_eq!(
1971 schema2
1972 .examples
1973 .as_ref()
1974 .and_then(|v| v.as_array())
1975 .and_then(|arr| arr.first())
1976 .and_then(|v| v.as_str()),
1977 Some("Example value")
1978 );
1979 assert_eq!(
1980 schema2.default.as_ref().and_then(|v| v.as_str()),
1981 Some("Default value")
1982 );
1983 }
1984
1985 #[test]
1986 fn test_quill_without_plate_file() {
1987 let mut root_files = HashMap::new();
1989
1990 let quill_toml = r#"[Quill]
1992name = "test-no-plate"
1993backend = "typst"
1994description = "Test quill without plate file"
1995"#;
1996 root_files.insert(
1997 "Quill.toml".to_string(),
1998 FileTreeNode::File {
1999 contents: quill_toml.as_bytes().to_vec(),
2000 },
2001 );
2002
2003 let root = FileTreeNode::Directory { files: root_files };
2004
2005 let quill = Quill::from_tree(root, None).unwrap();
2007
2008 assert!(quill.plate.clone().is_none());
2010 assert_eq!(quill.name, "test-no-plate");
2011 }
2012
2013 #[test]
2014 fn test_quill_config_from_toml() {
2015 let toml_content = r#"[Quill]
2017name = "test-config"
2018backend = "typst"
2019description = "Test configuration parsing"
2020version = "1.0.0"
2021author = "Test Author"
2022plate_file = "plate.typ"
2023example_file = "example.md"
2024
2025[typst]
2026packages = ["@preview/bubble:0.2.2"]
2027
2028[fields]
2029title = {description = "Document title", type = "string"}
2030author = {description = "Document author"}
2031"#;
2032
2033 let config = QuillConfig::from_toml(toml_content).unwrap();
2034
2035 assert_eq!(config.name, "test-config");
2037 assert_eq!(config.backend, "typst");
2038 assert_eq!(config.description, "Test configuration parsing");
2039
2040 assert_eq!(config.version, Some("1.0.0".to_string()));
2042 assert_eq!(config.author, Some("Test Author".to_string()));
2043 assert_eq!(config.plate_file, Some("plate.typ".to_string()));
2044 assert_eq!(config.example_file, Some("example.md".to_string()));
2045
2046 assert!(config.typst_config.contains_key("packages"));
2048
2049 assert_eq!(config.fields.len(), 2);
2051 assert!(config.fields.contains_key("title"));
2052 assert!(config.fields.contains_key("author"));
2053
2054 let title_field = &config.fields["title"];
2055 assert_eq!(title_field.description, "Document title");
2056 assert_eq!(title_field.r#type, Some("string".to_string()));
2057 }
2058
2059 #[test]
2060 fn test_quill_config_missing_required_fields() {
2061 let toml_missing_name = r#"[Quill]
2063backend = "typst"
2064description = "Missing name"
2065"#;
2066 let result = QuillConfig::from_toml(toml_missing_name);
2067 assert!(result.is_err());
2068 assert!(result
2069 .unwrap_err()
2070 .to_string()
2071 .contains("Missing required 'name'"));
2072
2073 let toml_missing_backend = r#"[Quill]
2074name = "test"
2075description = "Missing backend"
2076"#;
2077 let result = QuillConfig::from_toml(toml_missing_backend);
2078 assert!(result.is_err());
2079 assert!(result
2080 .unwrap_err()
2081 .to_string()
2082 .contains("Missing required 'backend'"));
2083
2084 let toml_missing_description = r#"[Quill]
2085name = "test"
2086backend = "typst"
2087"#;
2088 let result = QuillConfig::from_toml(toml_missing_description);
2089 assert!(result.is_err());
2090 assert!(result
2091 .unwrap_err()
2092 .to_string()
2093 .contains("Missing required 'description'"));
2094 }
2095
2096 #[test]
2097 fn test_quill_config_empty_description() {
2098 let toml_empty_description = r#"[Quill]
2100name = "test"
2101backend = "typst"
2102description = " "
2103"#;
2104 let result = QuillConfig::from_toml(toml_empty_description);
2105 assert!(result.is_err());
2106 assert!(result
2107 .unwrap_err()
2108 .to_string()
2109 .contains("description' field in [Quill] section cannot be empty"));
2110 }
2111
2112 #[test]
2113 fn test_quill_config_missing_quill_section() {
2114 let toml_no_section = r#"[fields]
2116title = {description = "Title"}
2117"#;
2118 let result = QuillConfig::from_toml(toml_no_section);
2119 assert!(result.is_err());
2120 assert!(result
2121 .unwrap_err()
2122 .to_string()
2123 .contains("Missing required [Quill] section"));
2124 }
2125
2126 #[test]
2127 fn test_quill_from_config_metadata() {
2128 let mut root_files = HashMap::new();
2130
2131 let quill_toml = r#"[Quill]
2132name = "metadata-test"
2133backend = "typst"
2134description = "Test metadata flow"
2135author = "Test Author"
2136custom_field = "custom_value"
2137
2138[typst]
2139packages = ["@preview/bubble:0.2.2"]
2140"#;
2141 root_files.insert(
2142 "Quill.toml".to_string(),
2143 FileTreeNode::File {
2144 contents: quill_toml.as_bytes().to_vec(),
2145 },
2146 );
2147
2148 let root = FileTreeNode::Directory { files: root_files };
2149 let quill = Quill::from_tree(root, None).unwrap();
2150
2151 assert!(quill.metadata.contains_key("backend"));
2153 assert!(quill.metadata.contains_key("description"));
2154 assert!(quill.metadata.contains_key("author"));
2155
2156 assert!(quill.metadata.contains_key("custom_field"));
2158 assert_eq!(
2159 quill.metadata.get("custom_field").unwrap().as_str(),
2160 Some("custom_value")
2161 );
2162
2163 assert!(quill.metadata.contains_key("typst_packages"));
2165 }
2166
2167 #[test]
2168 fn test_extract_defaults_method() {
2169 let mut root_files = HashMap::new();
2171
2172 let quill_toml = r#"[Quill]
2173name = "defaults-test"
2174backend = "typst"
2175description = "Test defaults extraction"
2176
2177[fields]
2178title = {description = "Title"}
2179author = {description = "Author", default = "Anonymous"}
2180status = {description = "Status", default = "draft"}
2181"#;
2182
2183 root_files.insert(
2184 "Quill.toml".to_string(),
2185 FileTreeNode::File {
2186 contents: quill_toml.as_bytes().to_vec(),
2187 },
2188 );
2189
2190 let root = FileTreeNode::Directory { files: root_files };
2191 let quill = Quill::from_tree(root, None).unwrap();
2192
2193 let defaults = quill.extract_defaults();
2195
2196 assert_eq!(defaults.len(), 2);
2198 assert!(!defaults.contains_key("title")); assert!(defaults.contains_key("author"));
2200 assert!(defaults.contains_key("status"));
2201
2202 assert_eq!(defaults.get("author").unwrap().as_str(), Some("Anonymous"));
2204 assert_eq!(defaults.get("status").unwrap().as_str(), Some("draft"));
2205 }
2206
2207 #[test]
2208 fn test_field_order_preservation() {
2209 let toml_content = r#"[Quill]
2210name = "order-test"
2211backend = "typst"
2212description = "Test field order"
2213
2214[fields]
2215first = {description = "First field"}
2216second = {description = "Second field"}
2217third = {description = "Third field", ui = {group = "Test Group"}}
2218fourth = {description = "Fourth field"}
2219"#;
2220
2221 let config = QuillConfig::from_toml(toml_content).unwrap();
2222
2223 let first = config.fields.get("first").unwrap();
2227 assert_eq!(first.ui.as_ref().unwrap().order, Some(0));
2228
2229 let second = config.fields.get("second").unwrap();
2230 assert_eq!(second.ui.as_ref().unwrap().order, Some(1));
2231
2232 let third = config.fields.get("third").unwrap();
2233 assert_eq!(third.ui.as_ref().unwrap().order, Some(2));
2234 assert_eq!(
2235 third.ui.as_ref().unwrap().group,
2236 Some("Test Group".to_string())
2237 );
2238
2239 let fourth = config.fields.get("fourth").unwrap();
2240 assert_eq!(fourth.ui.as_ref().unwrap().order, Some(3));
2241 }
2242
2243 #[test]
2244 fn test_quill_with_all_ui_properties() {
2245 let toml_content = r#"[Quill]
2246name = "full-ui-test"
2247backend = "typst"
2248description = "Test all UI properties"
2249
2250[fields.author]
2251description = "The full name of the document author"
2252type = "str"
2253
2254[fields.author.ui]
2255group = "Author Info"
2256"#;
2257
2258 let config = QuillConfig::from_toml(toml_content).unwrap();
2259
2260 let author_field = &config.fields["author"];
2261 let ui = author_field.ui.as_ref().unwrap();
2262 assert_eq!(ui.group, Some("Author Info".to_string()));
2263 assert_eq!(ui.order, Some(0)); }
2265 #[test]
2266 fn test_field_schema_with_title_and_description() {
2267 let yaml = r#"
2269title: "Field Title"
2270description: "Detailed field description"
2271type: "string"
2272examples:
2273 - "Example value"
2274ui:
2275 group: "Test Group"
2276"#;
2277 let yaml_value: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
2278 let quill_value = QuillValue::from_yaml(yaml_value).unwrap();
2279 let schema = FieldSchema::from_quill_value("test_field".to_string(), &quill_value).unwrap();
2280
2281 assert_eq!(schema.title, Some("Field Title".to_string()));
2282 assert_eq!(schema.description, "Detailed field description");
2283
2284 assert_eq!(
2285 schema
2286 .examples
2287 .as_ref()
2288 .and_then(|v| v.as_array())
2289 .and_then(|arr| arr.first())
2290 .and_then(|v| v.as_str()),
2291 Some("Example value")
2292 );
2293
2294 let ui = schema.ui.as_ref().unwrap();
2295 assert_eq!(ui.group, Some("Test Group".to_string()));
2296 }
2297
2298 #[test]
2299 fn test_parse_card_field_type() {
2300 let yaml = r#"
2302type: "string"
2303title: "Simple Field"
2304description: "A simple string field"
2305"#;
2306 let yaml_value: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
2307 let quill_value = QuillValue::from_yaml(yaml_value).unwrap();
2308 let schema =
2309 FieldSchema::from_quill_value("simple_field".to_string(), &quill_value).unwrap();
2310
2311 assert_eq!(schema.name, "simple_field");
2312 assert_eq!(schema.r#type, Some("string".to_string()));
2313 assert_eq!(schema.title, Some("Simple Field".to_string()));
2314 assert_eq!(schema.description, "A simple string field");
2315 }
2316
2317 #[test]
2318 fn test_parse_card_with_fields_in_toml() {
2319 let toml_content = r#"[Quill]
2321name = "cards-fields-test"
2322backend = "typst"
2323description = "Test [cards.X.fields.Y] syntax"
2324
2325[cards.endorsements]
2326title = "Endorsements"
2327description = "Chain of endorsements"
2328
2329[cards.endorsements.fields.name]
2330type = "string"
2331title = "Endorser Name"
2332description = "Name of the endorsing official"
2333required = true
2334
2335[cards.endorsements.fields.org]
2336type = "string"
2337title = "Organization"
2338description = "Endorser's organization"
2339default = "Unknown"
2340"#;
2341
2342 let config = QuillConfig::from_toml(toml_content).unwrap();
2343
2344 assert!(config.cards.contains_key("endorsements"));
2346 let card = config.cards.get("endorsements").unwrap();
2347
2348 assert_eq!(card.name, "endorsements");
2349 assert_eq!(card.title, Some("Endorsements".to_string()));
2350 assert_eq!(card.description, "Chain of endorsements");
2351
2352 assert_eq!(card.fields.len(), 2);
2354
2355 let name_field = card.fields.get("name").unwrap();
2356 assert_eq!(name_field.r#type, Some("string".to_string()));
2357 assert_eq!(name_field.title, Some("Endorser Name".to_string()));
2358 assert!(name_field.required);
2359
2360 let org_field = card.fields.get("org").unwrap();
2361 assert_eq!(org_field.r#type, Some("string".to_string()));
2362 assert!(org_field.default.is_some());
2363 assert_eq!(
2364 org_field.default.as_ref().unwrap().as_str(),
2365 Some("Unknown")
2366 );
2367 }
2368
2369 #[test]
2370 fn test_field_schema_ignores_unknown_keys() {
2371 let yaml = r#"
2373type: "string"
2374description: "A string field"
2375items:
2376 sub_field:
2377 type: "string"
2378 description: "Nested field"
2379"#;
2380 let yaml_value: serde_yaml::Value = serde_yaml::from_str(yaml).unwrap();
2381 let quill_value = QuillValue::from_yaml(yaml_value).unwrap();
2382 let result = FieldSchema::from_quill_value("author".to_string(), &quill_value);
2384
2385 assert!(result.is_ok());
2387 let schema = result.unwrap();
2388 assert_eq!(schema.r#type, Some("string".to_string()));
2389 }
2390
2391 #[test]
2392 fn test_quill_config_with_cards_section() {
2393 let toml_content = r#"[Quill]
2394name = "cards-test"
2395backend = "typst"
2396description = "Test [cards] section"
2397
2398[fields.regular]
2399description = "Regular field"
2400type = "string"
2401
2402[cards.indorsements]
2403title = "Routing Indorsements"
2404description = "Chain of endorsements"
2405
2406[cards.indorsements.fields.name]
2407title = "Name"
2408type = "string"
2409description = "Name field"
2410"#;
2411
2412 let config = QuillConfig::from_toml(toml_content).unwrap();
2413
2414 assert!(config.fields.contains_key("regular"));
2416 let regular = config.fields.get("regular").unwrap();
2417 assert_eq!(regular.r#type, Some("string".to_string()));
2418
2419 assert!(config.cards.contains_key("indorsements"));
2421 let card = config.cards.get("indorsements").unwrap();
2422 assert_eq!(card.title, Some("Routing Indorsements".to_string()));
2423 assert_eq!(card.description, "Chain of endorsements");
2424 assert!(card.fields.contains_key("name"));
2425 }
2426
2427 #[test]
2428 fn test_quill_config_cards_empty_fields() {
2429 let toml_content = r#"[Quill]
2431name = "cards-empty-fields-test"
2432backend = "typst"
2433description = "Test cards without fields"
2434
2435[cards.myscope]
2436description = "My scope"
2437"#;
2438
2439 let config = QuillConfig::from_toml(toml_content).unwrap();
2440 let card = config.cards.get("myscope").unwrap();
2441 assert_eq!(card.name, "myscope");
2442 assert_eq!(card.description, "My scope");
2443 assert!(card.fields.is_empty());
2444 }
2445
2446 #[test]
2447 fn test_quill_config_card_collision() {
2448 let toml_content = r#"[Quill]
2450name = "collision-test"
2451backend = "typst"
2452description = "Test collision"
2453
2454[fields.conflict]
2455description = "Field"
2456type = "string"
2457
2458[cards.conflict]
2459description = "Card"
2460items = {}
2461"#;
2462
2463 let result = QuillConfig::from_toml(toml_content);
2464 assert!(result.is_err());
2465 assert!(result
2466 .unwrap_err()
2467 .to_string()
2468 .contains("conflicts with an existing field name"));
2469 }
2470
2471 #[test]
2472 fn test_quill_config_ordering_with_cards() {
2473 let toml_content = r#"[Quill]
2475name = "ordering-test"
2476backend = "typst"
2477description = "Test ordering"
2478
2479[fields.first]
2480description = "First"
2481
2482[cards.second]
2483description = "Second"
2484
2485[fields.zero]
2486description = "Zero"
2487"#;
2488
2489 let config = QuillConfig::from_toml(toml_content).unwrap();
2490
2491 let first = config.fields.get("first").unwrap();
2492 let zero = config.fields.get("zero").unwrap();
2493 let second = config.cards.get("second").unwrap(); let ord_first = first.ui.as_ref().unwrap().order.unwrap();
2497 let ord_zero = zero.ui.as_ref().unwrap().order.unwrap();
2498 let ord_second = second.ui.as_ref().unwrap().order.unwrap();
2499
2500 assert!(ord_first < ord_second);
2505 assert!(ord_zero < ord_second);
2506
2507 assert!(ord_first < ord_zero);
2509
2510 assert_eq!(ord_first, 0);
2511 assert_eq!(ord_zero, 1);
2512 assert_eq!(ord_second, 2);
2513 }
2514}