wsb 0.195.4199

Workspace - A tool suite for file operations, version management, and development workflow automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
use crate::prelude::*;
use std::fs;
use tera::{Context as TeraContext, Tera};

use crate::state::VersionInfo;
use crate::workspace_state::WorkspaceState;

/// Template configuration and metadata
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TemplateConfig {
    pub name: String,
    pub description: Option<String>,
    pub source_path: String,
    pub output_path: String,
    pub enabled: bool,
}

/// Template manager for state
pub struct TemplateManager {
    project_root: PathBuf,
    templates_dir: PathBuf,
    tera_engine: Tera,
    templates: HashMap<String, TemplateConfig>,
}

impl TemplateManager {
    /// Initialize template manager for a project
    pub fn new(workspace_state: &WorkspaceState) -> Result<Self> {
        let project_root = workspace_state.project_root.clone();
        let templates_dir = workspace_state.workspace_dir().join("templates");
        fs::create_dir_all(&templates_dir).context("Failed to create templates directory")?;

        // Initialize empty Tera engine
        let mut tera_engine = Tera::default();

        // Load template configurations
        let templates = Self::load_template_configs(&templates_dir)?;

        // Register templates with Tera
        for template_config in templates.values() {
            let template_path = templates_dir.join(&template_config.source_path);
            if template_path.exists() {
                let template_content = fs::read_to_string(&template_path).with_context(|| {
                    format!("Failed to read template: {}", template_path.display())
                })?;

                tera_engine
                    .add_raw_template(&template_config.name, &template_content)
                    .with_context(|| {
                        format!("Failed to register template: {}", template_config.name)
                    })?;
            }
        }

        Ok(Self {
            project_root,
            templates_dir,
            tera_engine,
            templates,
        })
    }

    /// Add a new template
    pub fn add_template(
        &mut self,
        name: &str,
        template_content: &str,
        output_path: &str,
        description: Option<String>,
    ) -> Result<()> {
        let template_filename = format!("{}.tera", name);
        let template_path = self.templates_dir.join(&template_filename);

        // Write template file
        fs::write(&template_path, template_content).with_context(|| {
            format!("Failed to write template file: {}", template_path.display())
        })?;

        // Create template config
        let template_config = TemplateConfig {
            name: name.to_string(),
            description,
            source_path: template_filename,
            output_path: output_path.to_string(),
            enabled: true,
        };

        // Register with Tera
        self.tera_engine
            .add_raw_template(name, template_content)
            .with_context(|| format!("Failed to register template: {}", name))?;

        // Store config
        self.templates.insert(name.to_string(), template_config);

        // Save configurations
        self.save_template_configs()?;

        Ok(())
    }

    /// Remove a template
    pub fn remove_template(&mut self, name: &str) -> Result<bool> {
        if let Some(template_config) = self.templates.remove(name) {
            let template_path = self.templates_dir.join(&template_config.source_path);

            // Remove template file if it exists
            if template_path.exists() {
                fs::remove_file(&template_path).with_context(|| {
                    format!(
                        "Failed to remove template file: {}",
                        template_path.display()
                    )
                })?;
            }

            // Remove from Tera (note: Tera doesn't have a remove method, so we reconstruct)
            self.rebuild_tera_engine()?;

            // Save updated configurations
            self.save_template_configs()?;

            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// List all templates
    pub fn list_templates(&self) -> Vec<&TemplateConfig> {
        self.templates.values().collect()
    }

    /// Get a specific template
    pub fn get_template(&self, name: &str) -> Option<&TemplateConfig> {
        self.templates.get(name)
    }

    /// Enable or disable a template
    pub fn set_template_enabled(&mut self, name: &str, enabled: bool) -> Result<bool> {
        if let Some(template_config) = self.templates.get_mut(name) {
            template_config.enabled = enabled;
            self.save_template_configs()?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Render all enabled templates
    pub fn render_all_templates(
        &self,
        version_info: &VersionInfo,
        project_name: Option<&str>,
    ) -> Result<Vec<String>> {
        let mut rendered_files = Vec::new();
        let context = self.create_template_context(version_info, project_name);

        for template_config in self.templates.values() {
            if template_config.enabled {
                match self.render_template(template_config, &context) {
                    Ok(output_path) => {
                        rendered_files.push(output_path);
                    }
                    Err(e) => {
                        warn!(
                            "Failed to render template '{}': {}",
                            template_config.name,
                            e
                        );
                    }
                }
            }
        }

        Ok(rendered_files)
    }

    /// Render a specific template
    pub fn render_template(
        &self,
        template_config: &TemplateConfig,
        context: &TeraContext,
    ) -> Result<String> {
        let rendered_content = self
            .tera_engine
            .render(&template_config.name, context)
            .with_context(|| format!("Failed to render template: {}", template_config.name))?;

        // Write to output file
        let output_path = if Path::new(&template_config.output_path).is_absolute() {
            PathBuf::from(&template_config.output_path)
        } else {
            self.project_root.join(&template_config.output_path)
        };

        // Create parent directories if needed
        if let Some(parent) = output_path.parent() {
            fs::create_dir_all(parent).with_context(|| {
                format!("Failed to create output directory: {}", parent.display())
            })?;
        }

        fs::write(&output_path, rendered_content).with_context(|| {
            format!(
                "Failed to write rendered template to: {}",
                output_path.display()
            )
        })?;

        Ok(output_path.display().to_string())
    }

    /// Create template context with all available variables
    fn create_template_context(
        &self,
        version_info: &VersionInfo,
        project_name: Option<&str>,
    ) -> TeraContext {
        let mut context = TeraContext::new();

        // Project information
        let mut project = HashMap::new();
        project.insert("version".to_string(), version_info.full_version.clone());
        project.insert(
            "major_version".to_string(),
            version_info.major_version.clone(),
        );
        project.insert(
            "minor_version".to_string(),
            version_info.minor_version.to_string(),
        );
        project.insert(
            "patch_version".to_string(),
            version_info.patch_version.to_string(),
        );

        if let Some(name) = project_name {
            project.insert("name".to_string(), name.to_string());
        }

        context.insert("project", &project);

        // Date and time
        let now = chrono::Local::now();
        let mut datetime = HashMap::new();
        datetime.insert("iso".to_string(), now.to_rfc3339());
        datetime.insert("date".to_string(), now.format("%Y-%m-%d").to_string());
        datetime.insert("time".to_string(), now.format("%H:%M:%S").to_string());
        datetime.insert("year".to_string(), now.format("%Y").to_string());
        datetime.insert("month".to_string(), now.format("%m").to_string());
        datetime.insert("day".to_string(), now.format("%d").to_string());

        context.insert("datetime", &datetime);

        context
    }

    /// Load template configurations from disk
    fn load_template_configs(templates_dir: &Path) -> Result<HashMap<String, TemplateConfig>> {
        let config_file = templates_dir.join("templates.json");

        if !config_file.exists() {
            return Ok(HashMap::new());
        }

        let content =
            fs::read_to_string(&config_file).context("Failed to read template configurations")?;

        let configs: HashMap<String, TemplateConfig> =
            serde_json::from_str(&content).context("Failed to parse template configurations")?;

        Ok(configs)
    }

    /// Save template configurations to disk
    fn save_template_configs(&self) -> Result<()> {
        let config_file = self.templates_dir.join("templates.json");
        let content = serde_json::to_string_pretty(&self.templates)
            .context("Failed to serialize template configurations")?;

        fs::write(&config_file, content).context("Failed to write template configurations")?;

        Ok(())
    }

    /// Rebuild Tera engine after template removal
    fn rebuild_tera_engine(&mut self) -> Result<()> {
        self.tera_engine = Tera::default();

        for template_config in self.templates.values() {
            let template_path = self.templates_dir.join(&template_config.source_path);
            if template_path.exists() {
                let template_content = fs::read_to_string(&template_path).with_context(|| {
                    format!("Failed to read template: {}", template_path.display())
                })?;

                self.tera_engine
                    .add_raw_template(&template_config.name, &template_content)
                    .with_context(|| {
                        format!("Failed to register template: {}", template_config.name)
                    })?;
            }
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn create_test_state(temp_dir: &Path) -> WorkspaceState {
        WorkspaceState::initialize(temp_dir, None).unwrap()
    }

    #[test]
    fn test_template_manager_creation() {
        let temp_dir = TempDir::new().unwrap();
        let state = create_test_state(temp_dir.path());

        let manager = TemplateManager::new(&state).unwrap();
        assert!(manager.templates_dir.exists());
        assert_eq!(manager.list_templates().len(), 0);
    }

    #[test]
    fn test_add_and_remove_template() {
        let temp_dir = TempDir::new().unwrap();
        let state = create_test_state(temp_dir.path());
        let mut manager = TemplateManager::new(&state).unwrap();

        let template_content = "# {{ project.name }} v{{ project.version }}\n\nRelease notes for version {{ project.version }}.";
        let output_path = "RELEASE_NOTES.md";

        // Add template
        manager
            .add_template(
                "release_notes",
                template_content,
                output_path,
                Some("Release notes template".to_string()),
            )
            .unwrap();

        assert_eq!(manager.list_templates().len(), 1);
        let template = manager.get_template("release_notes").unwrap();
        assert_eq!(template.name, "release_notes");
        assert_eq!(template.output_path, output_path);
        assert!(template.enabled);

        // Remove template
        let removed = manager.remove_template("release_notes").unwrap();
        assert!(removed);
        assert_eq!(manager.list_templates().len(), 0);

        // Try to remove non-existent template
        let removed = manager.remove_template("non_existent").unwrap();
        assert!(!removed);
    }

    #[test]
    fn test_enable_disable_template() {
        let temp_dir = TempDir::new().unwrap();
        let state = create_test_state(temp_dir.path());
        let mut manager = TemplateManager::new(&state).unwrap();

        let template_content = "Version: {{ project.version }}";
        manager
            .add_template("version", template_content, "VERSION.txt", None)
            .unwrap();

        // Disable template
        let result = manager.set_template_enabled("version", false).unwrap();
        assert!(result);

        let template = manager.get_template("version").unwrap();
        assert!(!template.enabled);

        // Enable template
        let result = manager.set_template_enabled("version", true).unwrap();
        assert!(result);

        let template = manager.get_template("version").unwrap();
        assert!(template.enabled);

        // Try to modify non-existent template
        let result = manager.set_template_enabled("non_existent", true).unwrap();
        assert!(!result);
    }

    #[test]
    fn test_template_context_creation() {
        let temp_dir = TempDir::new().unwrap();
        let state = create_test_state(temp_dir.path());
        let manager = TemplateManager::new(&state).unwrap();

        let version_info = VersionInfo {
            major_version: "v1.0".to_string(),
            minor_version: 5,
            patch_version: 100,
            full_version: "1.0.5.100".to_string(),
        };

        let context = manager.create_template_context(&version_info, Some("test-project"));

        // Verify context contains expected values
        let project = context.get("project").unwrap();
        assert!(project.is_object());

        let datetime = context.get("datetime").unwrap();
        assert!(datetime.is_object());
    }

    #[test]
    fn test_render_template() {
        let temp_dir = TempDir::new().unwrap();
        let state = create_test_state(temp_dir.path());
        let mut manager = TemplateManager::new(&state).unwrap();

        let template_content = "# {{ project.name | default(value='Unknown') }} v{{ project.version }}\n\nReleased on {{ datetime.date }}\n\n## Changes\n- Version bump to {{ project.version }}";
        let output_path = temp_dir.path().join("CHANGELOG.md");

        manager
            .add_template(
                "changelog",
                template_content,
                output_path.to_str().unwrap(),
                None,
            )
            .unwrap();

        let version_info = VersionInfo {
            major_version: "v1.0".to_string(),
            minor_version: 5,
            patch_version: 100,
            full_version: "1.0.5.100".to_string(),
        };

        let rendered_files = manager
            .render_all_templates(&version_info, Some("test-project"))
            .unwrap();

        assert_eq!(rendered_files.len(), 1);
        assert!(output_path.exists());

        let rendered_content = fs::read_to_string(&output_path).unwrap();
        assert!(rendered_content.contains("# test-project v1.0.5.100"));
        assert!(rendered_content.contains("Version bump to 1.0.5.100"));
    }

    #[test]
    fn test_template_persistence() {
        let temp_dir = TempDir::new().unwrap();
        let state = create_test_state(temp_dir.path());

        // Create manager and add template
        {
            let mut manager = TemplateManager::new(&state).unwrap();
            manager
                .add_template(
                    "test",
                    "{{ project.version }}",
                    "version.txt",
                    Some("Test template".to_string()),
                )
                .unwrap();
        }

        // Create new manager and verify template persisted
        {
            let manager = TemplateManager::new(&state).unwrap();
            assert_eq!(manager.list_templates().len(), 1);

            let template = manager.get_template("test").unwrap();
            assert_eq!(template.description, Some("Test template".to_string()));
        }
    }
}