Skip to main content

vtcode_config/
output_styles.rs

1use anyhow::Result;
2use hashbrown::HashMap;
3use serde::{Deserialize, Serialize};
4use std::fs;
5use std::path::Path;
6
7#[derive(Debug, Clone, Serialize, Deserialize)]
8#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
9pub struct OutputStyleConfig {
10    #[serde(default = "default_output_style")]
11    pub active_style: String,
12}
13
14fn default_output_style() -> String {
15    "default".to_string()
16}
17
18impl Default for OutputStyleConfig {
19    fn default() -> Self {
20        Self { active_style: default_output_style() }
21    }
22}
23
24#[derive(Debug, Clone, Default, Serialize, Deserialize)]
25#[serde(rename_all = "kebab-case")]
26pub struct OutputStyleFileConfig {
27    name: String,
28    description: Option<String>,
29    #[serde(default)]
30    pub keep_coding_instructions: bool,
31}
32
33#[derive(Debug, Clone)]
34pub struct OutputStyle {
35    pub config: OutputStyleFileConfig,
36    pub content: String,
37}
38
39#[derive(Debug)]
40pub struct OutputStyleManager {
41    styles: HashMap<String, OutputStyle>,
42}
43
44impl Default for OutputStyleManager {
45    fn default() -> Self {
46        Self::new()
47    }
48}
49
50impl OutputStyleManager {
51    pub fn new() -> Self {
52        Self { styles: HashMap::new() }
53    }
54
55    pub fn load_from_directory<P: AsRef<Path>>(dir: P) -> Result<Self> {
56        let mut manager = Self::new();
57        let dir = dir.as_ref();
58
59        if !dir.exists() {
60            return Ok(manager);
61        }
62
63        for entry in fs::read_dir(dir)? {
64            let entry = entry?;
65            let path = entry.path();
66
67            if path.extension().and_then(|s| s.to_str()) == Some("md")
68                && let Ok(output_style) = Self::load_from_file(&path)
69            {
70                manager.styles.insert(output_style.config.name.clone(), output_style);
71            }
72        }
73
74        Ok(manager)
75    }
76
77    fn load_from_file<P: AsRef<Path>>(path: P) -> Result<OutputStyle> {
78        let content = fs::read_to_string(path)?;
79        Self::parse_output_style(&content)
80    }
81
82    fn parse_output_style(content: &str) -> Result<OutputStyle> {
83        // Look for frontmatter (between --- and ---)
84        if let Some(frontmatter_body) = content.strip_prefix("---\n")
85            && let Some(frontmatter_end) = frontmatter_body.find("\n---\n")
86        {
87            let frontmatter_content = &frontmatter_body[..frontmatter_end];
88            let config: OutputStyleFileConfig = serde_saphyr::from_str(frontmatter_content)?;
89
90            // Get the content after the frontmatter
91            let content_start = frontmatter_end + 5; // Skip past body + "\n---\n"
92            let actual_content = if content_start < frontmatter_body.len() {
93                &frontmatter_body[content_start..]
94            } else {
95                ""
96            };
97
98            Ok(OutputStyle { config, content: actual_content.to_string() })
99        } else {
100            // No frontmatter, create default config
101            Ok(OutputStyle {
102                config: OutputStyleFileConfig {
103                    name: "default".to_string(),
104                    description: Some("Default output style".to_string()),
105                    keep_coding_instructions: true,
106                },
107                content: content.to_string(),
108            })
109        }
110    }
111
112    pub fn get_style(&self, name: &str) -> Option<&OutputStyle> {
113        self.styles.get(name)
114    }
115
116    fn apply_style(&self, name: &str, base_prompt: &str) -> String {
117        if let Some(style) = self.get_style(name) {
118            if style.config.keep_coding_instructions {
119                // Combine base prompt with style content
120                format!("{}\n\n{}", base_prompt, style.content)
121            } else {
122                // Replace base prompt with style content
123                style.content.clone()
124            }
125        } else {
126            base_prompt.to_string()
127        }
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    use std::fs;
135    use tempfile::TempDir;
136
137    #[test]
138    fn test_parse_output_style_with_frontmatter() {
139        let content = r#"---
140name: Test Style
141description: A test output style
142keep-coding-instructions: false
143---
144
145# Test Output Style
146
147This is a test output style."#;
148
149        let style = OutputStyleManager::parse_output_style(content).unwrap();
150        assert_eq!(style.config.name, "Test Style");
151        assert_eq!(style.config.description, Some("A test output style".to_string()));
152        assert!(!style.config.keep_coding_instructions);
153        assert!(style.content.contains("This is a test output style"));
154    }
155
156    #[test]
157    fn test_parse_output_style_with_bare_frontmatter_fence() {
158        let style = OutputStyleManager::parse_output_style("---").unwrap();
159
160        assert_eq!(style.config.name, "default");
161        assert_eq!(style.content, "---");
162    }
163
164    #[test]
165    fn test_parse_output_style_without_frontmatter() {
166        let content = r#"This is a plain output style without frontmatter."#;
167
168        let style = OutputStyleManager::parse_output_style(content).unwrap();
169        assert_eq!(style.config.name, "default");
170        assert!(style.content.contains("This is a plain output style"));
171    }
172
173    #[test]
174    fn test_load_from_directory() {
175        let temp_dir = TempDir::new().unwrap();
176        let style_file = temp_dir.path().join("test_style.md");
177
178        fs::write(
179            &style_file,
180            r#"---
181name: Test Style
182description: A test output style
183keep-coding-instructions: true
184---
185
186# Test Output Style
187
188This is a test output style."#,
189        )
190        .unwrap();
191
192        let manager = OutputStyleManager::load_from_directory(temp_dir.path()).unwrap();
193        assert!(manager.get_style("Test Style").is_some());
194    }
195
196    #[test]
197    fn test_apply_style_with_keep_instructions() {
198        let content = r#"---
199name: Test Style
200description: A test output style
201keep-coding-instructions: true
202---
203
204## Custom Instructions
205
206Custom instructions here."#;
207
208        let style = OutputStyleManager::parse_output_style(content).unwrap();
209        let mut manager = OutputStyleManager::new();
210        manager.styles.insert("Test Style".to_string(), style);
211
212        let base_prompt = "Base system prompt";
213        let result = manager.apply_style("Test Style", base_prompt);
214
215        assert!(result.contains("Base system prompt"));
216        assert!(result.contains("Custom instructions here"));
217    }
218
219    #[test]
220    fn test_apply_style_without_keep_instructions() {
221        let content = r#"---
222name: Test Style
223description: A test output style
224keep-coding-instructions: false
225---
226
227## Custom Instructions
228
229Custom instructions here."#;
230
231        let style = OutputStyleManager::parse_output_style(content).unwrap();
232        let mut manager = OutputStyleManager::new();
233        manager.styles.insert("Test Style".to_string(), style);
234
235        let base_prompt = "Base system prompt";
236        let result = manager.apply_style("Test Style", base_prompt);
237
238        assert!(!result.contains("Base system prompt"));
239        assert!(result.contains("Custom instructions here"));
240    }
241}