1use std::collections::{BTreeMap, BTreeSet};
2use std::fs;
3use std::io::ErrorKind;
4use std::path::{Path, PathBuf};
5
6use semver::Version;
7use serde_json::Value;
8use sha2::{Digest, Sha256};
9use unicode_casefold::UnicodeCaseFold;
10use walkdir::WalkDir;
11
12use crate::{
13 FolderbaseError, PlannedTemplateAddition, Result, TemplateAnswerType, TemplateAnswerValue,
14 TemplateArtifactKind, TemplateDescriptor, TemplatePackage, TemplateRenderPlan,
15};
16
17const BUILTIN_TEMPLATES: [(&str, &str, &str); 8] = [
18 (
19 "folderbase.person",
20 "0.2.0",
21 include_str!("../assets/templates/0.2/person/template.json"),
22 ),
23 (
24 "folderbase.organization",
25 "0.2.0",
26 include_str!("../assets/templates/0.2/organization/template.json"),
27 ),
28 (
29 "folderbase.engagement",
30 "0.2.0",
31 include_str!("../assets/templates/0.2/engagement/template.json"),
32 ),
33 (
34 "folderbase.project",
35 "0.2.1",
36 include_str!("../assets/templates/0.2/project-0.2.1/template.json"),
37 ),
38 (
39 "folderbase.project",
40 "0.2.2",
41 include_str!("../assets/templates/0.2/project-0.2.2/template.json"),
42 ),
43 (
44 "folderbase.customer",
45 "0.2.0",
46 include_str!("../assets/templates/0.2/customer/template.json"),
47 ),
48 (
49 "folderbase.temporary",
50 "0.2.0",
51 include_str!("../assets/templates/0.2/temporary/template.json"),
52 ),
53 (
54 "folderbase.custom",
55 "0.2.0",
56 include_str!("../assets/templates/0.2/custom/template.json"),
57 ),
58];
59
60pub fn load_builtin_template(id: &str, version: &str) -> Result<TemplatePackage> {
65 let path = PathBuf::from(format!("<built-in:{id}@{version}>"));
66 let source = BUILTIN_TEMPLATES
67 .iter()
68 .find_map(|(candidate_id, candidate_version, source)| {
69 (*candidate_id == id && *candidate_version == version).then_some(*source)
70 })
71 .ok_or_else(|| FolderbaseError::InvalidRecord {
72 path: path.clone(),
73 message: format!("unknown built-in template {id}@{version}"),
74 })?;
75 let package: TemplatePackage =
76 serde_json::from_str(source).map_err(|source| FolderbaseError::json(&path, source))?;
77 validate_runtime_package(&path, &package)?;
78 if package.id != id || package.version != version {
79 return Err(FolderbaseError::InvalidRecord {
80 path,
81 message: format!(
82 "built-in template identity mismatch: requested {id}@{version}, embedded {}@{}",
83 package.id, package.version
84 ),
85 });
86 }
87 Ok(package)
88}
89
90pub fn list_templates(registry_root: &Path) -> Result<Vec<TemplateDescriptor>> {
91 if !registry_root.is_dir() {
92 return Err(FolderbaseError::InvalidRoot(registry_root.to_path_buf()));
93 }
94
95 let package_paths = package_paths(registry_root)?;
96
97 let mut templates = package_paths
98 .into_iter()
99 .map(|path| read_descriptor(&path))
100 .collect::<Result<Vec<_>>>()?;
101 templates.sort_by(|left, right| {
102 (&left.id, &left.version, &left.name).cmp(&(&right.id, &right.version, &right.name))
103 });
104 Ok(templates)
105}
106
107pub fn load_template(registry_root: &Path, id: &str, version: &str) -> Result<TemplatePackage> {
108 if !registry_root.is_dir() {
109 return Err(FolderbaseError::InvalidRoot(registry_root.to_path_buf()));
110 }
111
112 let mut matches = package_paths(registry_root)?
113 .into_iter()
114 .map(|path| read_package(&path))
115 .collect::<Result<Vec<_>>>()?
116 .into_iter()
117 .filter(|package| package.id == id && package.version == version)
118 .collect::<Vec<_>>();
119
120 if matches.len() != 1 {
121 return Err(FolderbaseError::InvalidRecord {
122 path: registry_root.to_path_buf(),
123 message: format!(
124 "expected exactly one template {id}@{version}, found {}",
125 matches.len()
126 ),
127 });
128 }
129 Ok(matches.remove(0))
130}
131
132pub fn render_template(
133 package: &TemplatePackage,
134 destination_root: &Path,
135 answers: &BTreeMap<String, TemplateAnswerValue>,
136) -> Result<TemplateRenderPlan> {
137 validate_destination_root(destination_root)?;
138 validate_runtime_package(destination_root, package)?;
139
140 validate_answers(package, answers, destination_root)?;
141
142 let mut additions = Vec::new();
143 let mut existing_paths = Vec::new();
144 for artifact in &package.artifacts {
145 if inspect_destination(destination_root, &artifact.target)? == DestinationState::Existing {
146 existing_paths.push(artifact.target.clone());
147 continue;
148 }
149 let content = match artifact.kind {
150 TemplateArtifactKind::Directory => None,
151 TemplateArtifactKind::Text => Some(render_content(
152 artifact.content.as_deref().unwrap_or_default(),
153 package,
154 answers,
155 destination_root,
156 )?),
157 };
158 additions.push(PlannedTemplateAddition {
159 path: artifact.target.clone(),
160 kind: artifact.kind,
161 content,
162 });
163 }
164 additions.sort_by(|left, right| left.path.cmp(&right.path));
165 existing_paths.sort();
166
167 Ok(TemplateRenderPlan {
168 template_id: package.id.clone(),
169 template_version: package.version.clone(),
170 additions,
171 existing_paths,
172 })
173}
174
175pub(crate) fn render_template_for_capability_destination(
182 package: &TemplatePackage,
183 destination_label: &Path,
184 answers: &BTreeMap<String, TemplateAnswerValue>,
185) -> Result<TemplateRenderPlan> {
186 validate_runtime_package(destination_label, package)?;
187 validate_answers(package, answers, destination_label)?;
188
189 let mut additions = Vec::new();
190 for artifact in &package.artifacts {
191 let content = match artifact.kind {
192 TemplateArtifactKind::Directory => None,
193 TemplateArtifactKind::Text => Some(render_content(
194 artifact.content.as_deref().unwrap_or_default(),
195 package,
196 answers,
197 destination_label,
198 )?),
199 };
200 additions.push(PlannedTemplateAddition {
201 path: artifact.target.clone(),
202 kind: artifact.kind,
203 content,
204 });
205 }
206 additions.sort_by(|left, right| left.path.cmp(&right.path));
207
208 Ok(TemplateRenderPlan {
209 template_id: package.id.clone(),
210 template_version: package.version.clone(),
211 additions,
212 existing_paths: Vec::new(),
213 })
214}
215
216pub fn template_package_sha256(package: &TemplatePackage) -> Result<String> {
217 let source = PathBuf::from("<template-package>");
218 validate_runtime_package(&source, package)?;
219 let value =
220 serde_json::to_value(package).map_err(|error| FolderbaseError::json(&source, error))?;
221 let mut bytes = Vec::new();
222 write_canonical_json(&value, &mut bytes);
223 Ok(format!("{:x}", Sha256::digest(bytes)))
224}
225
226fn write_canonical_json(value: &Value, output: &mut Vec<u8>) {
227 match value {
228 Value::Null => output.extend_from_slice(b"null"),
229 Value::Bool(value) => {
230 output.extend_from_slice(if *value { b"true" } else { b"false" });
231 }
232 Value::Number(value) => output.extend_from_slice(value.to_string().as_bytes()),
233 Value::String(value) => output.extend_from_slice(
234 serde_json::to_string(value)
235 .expect("JSON string serialization is infallible")
236 .as_bytes(),
237 ),
238 Value::Array(values) => {
239 output.push(b'[');
240 for (index, value) in values.iter().enumerate() {
241 if index > 0 {
242 output.push(b',');
243 }
244 write_canonical_json(value, output);
245 }
246 output.push(b']');
247 }
248 Value::Object(values) => {
249 output.push(b'{');
250 let mut entries = values.iter().collect::<Vec<_>>();
251 entries.sort_by(|(left, _), (right, _)| left.as_bytes().cmp(right.as_bytes()));
252 for (index, (key, value)) in entries.into_iter().enumerate() {
253 if index > 0 {
254 output.push(b',');
255 }
256 output.extend_from_slice(
257 serde_json::to_string(key)
258 .expect("JSON object key serialization is infallible")
259 .as_bytes(),
260 );
261 output.push(b':');
262 write_canonical_json(value, output);
263 }
264 output.push(b'}');
265 }
266 }
267}
268
269fn read_descriptor(path: &Path) -> Result<TemplateDescriptor> {
270 let package = read_package(path)?;
271 Ok(TemplateDescriptor {
272 id: package.id,
273 version: package.version,
274 name: package.name,
275 })
276}
277
278fn package_paths(registry_root: &Path) -> Result<Vec<PathBuf>> {
279 let mut paths = Vec::new();
280 for entry in WalkDir::new(registry_root).follow_links(false) {
281 let entry = entry.map_err(|error| {
282 let path = error
283 .path()
284 .map(Path::to_path_buf)
285 .unwrap_or_else(|| registry_root.to_path_buf());
286 if let Some(source) = error.into_io_error() {
287 FolderbaseError::io(path, source)
288 } else {
289 FolderbaseError::InvalidRecord {
290 path,
291 message: "template registry traversal failed".to_owned(),
292 }
293 }
294 })?;
295 if entry.file_type().is_file() && entry.file_name() == "template.json" {
296 paths.push(entry.into_path());
297 }
298 }
299 paths.sort();
300 Ok(paths)
301}
302
303fn validate_answers(
304 package: &TemplatePackage,
305 answers: &BTreeMap<String, TemplateAnswerValue>,
306 error_path: &Path,
307) -> Result<()> {
308 let questions = package
309 .questions
310 .iter()
311 .map(|question| (question.id.as_str(), question))
312 .collect::<BTreeMap<_, _>>();
313 let unknown = answers
314 .keys()
315 .find(|id| !questions.contains_key(id.as_str()));
316 if let Some(id) = unknown {
317 return invalid_template(error_path, format!("unknown template answer: {id}"));
318 }
319 for question in &package.questions {
320 let Some(answer) = answers.get(&question.id) else {
321 if question.required {
322 return invalid_template(
323 error_path,
324 format!("missing required template answer: {}", question.id),
325 );
326 }
327 continue;
328 };
329 let correct_type = matches!(
330 (question.answer_type, answer),
331 (TemplateAnswerType::Text, TemplateAnswerValue::Text(_))
332 | (TemplateAnswerType::Boolean, TemplateAnswerValue::Boolean(_))
333 );
334 if !correct_type {
335 return invalid_template(
336 error_path,
337 format!("wrong type for template answer: {}", question.id),
338 );
339 }
340 if question.required
341 && matches!(answer, TemplateAnswerValue::Text(value) if value.trim().is_empty())
342 {
343 return invalid_template(
344 error_path,
345 format!("blank required template answer: {}", question.id),
346 );
347 }
348 }
349 Ok(())
350}
351
352fn render_content(
353 content: &str,
354 package: &TemplatePackage,
355 answers: &BTreeMap<String, TemplateAnswerValue>,
356 error_path: &Path,
357) -> Result<String> {
358 let question_ids = package
359 .questions
360 .iter()
361 .map(|question| question.id.as_str())
362 .collect::<BTreeSet<_>>();
363 let mut rendered = String::with_capacity(content.len());
364 for segment in parse_content(content, error_path)? {
365 match segment {
366 ContentSegment::Literal(literal) => rendered.push_str(literal),
367 ContentSegment::Placeholder(id) => {
368 if !question_ids.contains(id) {
369 return invalid_template(
370 error_path,
371 format!("unknown template placeholder: {id}"),
372 );
373 }
374 let Some(answer) = answers.get(id) else {
375 return invalid_template(
376 error_path,
377 format!("missing template answer for placeholder: {id}"),
378 );
379 };
380 match answer {
381 TemplateAnswerValue::Text(value) => rendered.push_str(value),
382 TemplateAnswerValue::Boolean(value) => {
383 rendered.push_str(if *value { "true" } else { "false" })
384 }
385 }
386 }
387 }
388 }
389 Ok(rendered)
390}
391
392fn invalid_template<T>(path: &Path, message: impl Into<String>) -> Result<T> {
393 Err(FolderbaseError::InvalidRecord {
394 path: path.to_path_buf(),
395 message: message.into(),
396 })
397}
398
399fn read_package(path: &Path) -> Result<TemplatePackage> {
400 let bytes = fs::read(path).map_err(|source| FolderbaseError::io(path, source))?;
401 let package: TemplatePackage =
402 serde_json::from_slice(&bytes).map_err(|source| FolderbaseError::json(path, source))?;
403 validate_runtime_package(path, &package)?;
404 Ok(package)
405}
406
407pub(crate) fn validate_runtime_package(path: &Path, package: &TemplatePackage) -> Result<()> {
408 if !supported_protocol_version(&package.protocol_version) {
409 return invalid_template(
410 path,
411 format!(
412 "unsupported template protocol {} (supported: valid SemVer 0.2.x)",
413 package.protocol_version
414 ),
415 );
416 }
417 if !valid_package_id(&package.id) {
418 return invalid_template(path, format!("invalid template package id: {}", package.id));
419 }
420 let package_version =
421 Version::parse(&package.version).map_err(|_| FolderbaseError::InvalidRecord {
422 path: path.to_path_buf(),
423 message: format!("invalid template package version: {}", package.version),
424 })?;
425 if package.name.trim().is_empty() {
426 return invalid_template(path, "template name is empty");
427 }
428 validate_extensions(path, "template package", package.extensions.keys())?;
429 let mut question_ids = BTreeSet::new();
430 for question in &package.questions {
431 validate_extensions(path, "template question", question.extensions.keys())?;
432 if !valid_question_id(&question.id) {
433 return invalid_template(
434 path,
435 format!("invalid template question id: {}", question.id),
436 );
437 }
438 if !question_ids.insert(question.id.as_str()) {
439 return invalid_template(
440 path,
441 format!("duplicate template question id: {}", question.id),
442 );
443 }
444 if question.prompt.trim().is_empty() {
445 return invalid_template(
446 path,
447 format!("template question prompt is empty: {}", question.id),
448 );
449 }
450 }
451 validate_upgrade_graph(path, package, &package_version)?;
452 for edge in &package.upgrade_edges {
453 validate_extensions(path, "template upgrade edge", edge.extensions.keys())?;
454 }
455
456 let mut targets = BTreeSet::new();
457 for artifact in &package.artifacts {
458 validate_extensions(path, "template artifact", artifact.extensions.keys())?;
459 if !safe_artifact_target(&artifact.target) {
460 return invalid_template(
461 path,
462 format!("unsafe artifact target: {}", artifact.target.display()),
463 );
464 }
465 let target_text = artifact
466 .target
467 .to_str()
468 .expect("safe_artifact_target accepted only UTF-8");
469 let folded = target_text.case_fold().collect::<String>();
470 if !targets.insert(folded) {
471 return invalid_template(
472 path,
473 format!("duplicate artifact target: {}", artifact.target.display()),
474 );
475 }
476 if artifact.install != "create_if_missing" {
477 return invalid_template(path, "unsupported artifact installation mode");
478 }
479 match (artifact.kind, artifact.content.as_ref()) {
480 (TemplateArtifactKind::Text, None) => {
481 return invalid_template(path, "text artifact is missing inline content");
482 }
483 (TemplateArtifactKind::Directory, Some(_)) => {
484 return invalid_template(path, "directory artifact cannot contain text");
485 }
486 _ => {}
487 }
488 if let Some(content) = artifact.content.as_deref() {
489 for segment in parse_content(content, path)? {
490 if let ContentSegment::Placeholder(placeholder) = segment
491 && !question_ids.contains(placeholder)
492 {
493 return invalid_template(
494 path,
495 format!("unknown template placeholder: {placeholder}"),
496 );
497 }
498 }
499 }
500 }
501 Ok(())
502}
503
504fn validate_upgrade_graph(
505 path: &Path,
506 package: &TemplatePackage,
507 package_version: &Version,
508) -> Result<()> {
509 let mut graph = BTreeMap::<String, Vec<String>>::new();
510 let mut parsed_edges = Vec::new();
511 for edge in &package.upgrade_edges {
512 let from = Version::parse(&edge.from).map_err(|_| FolderbaseError::InvalidRecord {
513 path: path.to_path_buf(),
514 message: format!("invalid upgrade edge version: {}", edge.from),
515 })?;
516 let to = Version::parse(&edge.to).map_err(|_| FolderbaseError::InvalidRecord {
517 path: path.to_path_buf(),
518 message: format!("invalid upgrade edge version: {}", edge.to),
519 })?;
520 graph
521 .entry(edge.from.clone())
522 .or_default()
523 .push(edge.to.clone());
524 parsed_edges.push((edge, from, to));
525 }
526 if graph_has_cycle(&graph) {
527 return invalid_template(path, "template upgrade graph contains a cycle");
528 }
529 for (edge, from, to) in parsed_edges {
530 if from >= to {
531 return invalid_template(
532 path,
533 format!(
534 "upgrade edge does not advance: {} -> {}",
535 edge.from, edge.to
536 ),
537 );
538 }
539 if to != *package_version {
540 return invalid_template(
541 path,
542 format!(
543 "upgrade edge does not terminate at package version: {} -> {}",
544 edge.from, edge.to
545 ),
546 );
547 }
548 }
549 Ok(())
550}
551
552fn graph_has_cycle(graph: &BTreeMap<String, Vec<String>>) -> bool {
553 fn visit<'a>(
554 node: &'a str,
555 graph: &'a BTreeMap<String, Vec<String>>,
556 visiting: &mut BTreeSet<&'a str>,
557 visited: &mut BTreeSet<&'a str>,
558 ) -> bool {
559 if visited.contains(node) {
560 return false;
561 }
562 if !visiting.insert(node) {
563 return true;
564 }
565 if graph.get(node).is_some_and(|neighbors| {
566 neighbors
567 .iter()
568 .any(|neighbor| visit(neighbor, graph, visiting, visited))
569 }) {
570 return true;
571 }
572 visiting.remove(node);
573 visited.insert(node);
574 false
575 }
576
577 let mut visiting = BTreeSet::new();
578 let mut visited = BTreeSet::new();
579 graph
580 .keys()
581 .any(|node| visit(node, graph, &mut visiting, &mut visited))
582}
583
584fn validate_extensions<'a>(
585 path: &Path,
586 location: &str,
587 keys: impl Iterator<Item = &'a String>,
588) -> Result<()> {
589 if let Some(key) = keys.into_iter().find(|key| !key.starts_with("x-")) {
590 return invalid_template(path, format!("unknown {location} property: {key}"));
591 }
592 Ok(())
593}
594
595fn valid_question_id(id: &str) -> bool {
596 let mut characters = id.chars();
597 let Some(first) = characters.next() else {
598 return false;
599 };
600 (first.is_ascii_lowercase() || first.is_ascii_digit())
601 && characters.all(|character| {
602 character.is_ascii_lowercase()
603 || character.is_ascii_digit()
604 || matches!(character, '_' | '-')
605 })
606}
607
608#[derive(Debug, PartialEq, Eq)]
609enum ContentSegment<'a> {
610 Literal(&'a str),
611 Placeholder(&'a str),
612}
613
614fn parse_content<'a>(content: &'a str, error_path: &Path) -> Result<Vec<ContentSegment<'a>>> {
615 let mut segments = Vec::new();
616 let mut remaining = content;
617 while let Some(start) = remaining.find("${") {
618 if start > 0 {
619 segments.push(ContentSegment::Literal(&remaining[..start]));
620 }
621 let after_open = &remaining[start + 2..];
622 let Some(end) = after_open.find('}') else {
623 return invalid_template(error_path, "unterminated template placeholder");
624 };
625 let id = &after_open[..end];
626 if !valid_question_id(id) {
627 return invalid_template(error_path, format!("invalid template placeholder: {id}"));
628 }
629 segments.push(ContentSegment::Placeholder(id));
630 remaining = &after_open[end + 1..];
631 }
632 if !remaining.is_empty() {
633 segments.push(ContentSegment::Literal(remaining));
634 }
635 Ok(segments)
636}
637
638fn safe_artifact_target(target: &Path) -> bool {
639 use std::path::Component;
640
641 let Some(text) = target.to_str() else {
642 return false;
643 };
644 if text.is_empty()
645 || target.is_absolute()
646 || text.contains('\\')
647 || text.contains("//")
648 || text.ends_with('/')
649 || (text.as_bytes().get(1) == Some(&b':')
650 && text.as_bytes().first().is_some_and(u8::is_ascii_alphabetic))
651 {
652 return false;
653 }
654 target
655 .components()
656 .all(|component| matches!(component, Component::Normal(_)))
657}
658
659fn supported_protocol_version(version: &str) -> bool {
660 Version::parse(version).is_ok_and(|version| version.major == 0 && version.minor == 2)
661}
662
663fn valid_package_id(id: &str) -> bool {
664 let mut characters = id.chars();
665 let Some(first) = characters.next() else {
666 return false;
667 };
668 (first.is_ascii_lowercase() || first.is_ascii_digit())
669 && characters.all(|character| {
670 character.is_ascii_lowercase()
671 || character.is_ascii_digit()
672 || matches!(character, '.' | '_' | '-')
673 })
674}
675
676fn validate_destination_root(destination_root: &Path) -> Result<()> {
677 let metadata = fs::symlink_metadata(destination_root)
678 .map_err(|source| FolderbaseError::io(destination_root, source))?;
679 if metadata.file_type().is_symlink() {
680 return invalid_template(destination_root, "destination root is a symlink");
681 }
682 if !metadata.is_dir() {
683 return Err(FolderbaseError::InvalidRoot(destination_root.to_path_buf()));
684 }
685 Ok(())
686}
687
688#[derive(Debug, Clone, Copy, PartialEq, Eq)]
689enum DestinationState {
690 Absent,
691 Existing,
692}
693
694fn inspect_destination(root: &Path, relative: &Path) -> Result<DestinationState> {
695 let mut current = root.to_path_buf();
696 let component_count = relative.components().count();
697 for (index, component) in relative.components().enumerate() {
698 current.push(component.as_os_str());
699 match fs::symlink_metadata(¤t) {
700 Ok(metadata) => {
701 if metadata.file_type().is_symlink() {
702 return invalid_template(
703 ¤t,
704 format!(
705 "template destination contains a symlink: {}",
706 relative.display()
707 ),
708 );
709 }
710 if index + 1 < component_count && !metadata.is_dir() {
711 return invalid_template(
712 ¤t,
713 format!(
714 "template destination ancestor is not a directory: {}",
715 relative.display()
716 ),
717 );
718 }
719 if index + 1 == component_count {
720 return Ok(DestinationState::Existing);
721 }
722 }
723 Err(source) if source.kind() == ErrorKind::NotFound => {
724 return Ok(DestinationState::Absent);
725 }
726 Err(source) => return Err(FolderbaseError::io(¤t, source)),
727 }
728 }
729 Ok(DestinationState::Absent)
730}