juglans 0.1.0

Compiler and runtime for Juglans Workflow Language (JWL)
Documentation
// src/services/prompt_loader.rs
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use anyhow::{Result, anyhow};
use glob::glob;
use tracing::{info, warn};

/// 提示词注册表
#[derive(Debug, Clone)]
pub struct PromptRegistry {
    // slug -> template content
    templates: HashMap<String, String>,
}

impl PromptRegistry {
    pub fn new() -> Self {
        Self {
            templates: HashMap::new(),
        }
    }

    /// 加载配置文件中定义的路径列表
    pub fn load_from_paths(&mut self, patterns: &[String]) -> Result<()> {
        for pattern in patterns {
            // 处理每个路径模式 (支持 glob,如 ./prompts/*.jgprompt)
            let paths = glob(pattern).map_err(|e| anyhow!("Invalid glob pattern '{}': {}", pattern, e))?;

            for entry in paths {
                match entry {
                    Ok(path) => {
                        if path.is_file() {
                            self.load_file(&path)?;
                        }
                    }
                    Err(e) => warn!("Error reading glob entry: {}", e),
                }
            }
        }
        Ok(())
    }

    /// 读取单个文件并注册
    fn load_file(&mut self, path: &Path) -> Result<()> {
        // 1. 检查扩展名是否为 .jgprompt
        if path.extension().and_then(|s| s.to_str()) != Some("jgprompt") {
            // 如果不是指定后缀,可以选择忽略或警告,这里选择忽略非相关文件
            return Ok(());
        }

        // 2. 提取 Slug (文件名作为 Slug)
        // e.g., "prompts/market_analysis.jgprompt" -> "market_analysis"
        let slug = path.file_stem()
            .and_then(|s| s.to_str())
            .ok_or_else(|| anyhow!("Invalid filename: {:?}", path))?
            .to_string();

        // 3. 读取内容
        let content = fs::read_to_string(path)?;

        // 4. 注册
        info!("📝 Loaded Prompt: [{}] from {:?}", slug, path);
        self.templates.insert(slug, content);

        Ok(())
    }

    /// 获取提示词内容
    pub fn get(&self, slug: &str) -> Option<&String> {
        self.templates.get(slug)
    }
}