nucleusflow 0.0.1

A powerful Rust library for content processing, enabling static site generation, document conversion, and templating.
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
// Copyright © 2024 NucleusFlow. All rights reserved.
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! # NucleusFlow Library
//!
//! NucleusFlow provides a suite of tools for processing, rendering, and generating
//! content for static sites or other document-based applications.
//! This library includes support for content transformation, template rendering, and output
//! generation with a configurable pipeline for flexible usage.
//!
//! For more information, visit the [NucleusFlow documentation](https://docs.rs/nucleusflow).

#![doc = include_str!("../README.md")]
#![doc(
    html_favicon_url = "https://kura.pro/nucleusflow/images/favicon.ico",
    html_logo_url = "https://kura.pro/nucleusflow/images/logos/nucleusflow.svg",
    html_root_url = "https://docs.rs/nucleusflow"
)]
#![crate_name = "nucleusflow"]
#![crate_type = "lib"]

use crate::core::error::{ProcessingError, Result};
use crate::core::traits::Generator;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};

/// Module containing core utilities, such as configuration and error handling.
pub mod core {
    /// Handles configuration of the NucleusFlow application.
    pub mod config;
    /// Contains error types and handling for NucleusFlow.
    pub mod error;
    /// Defines common traits for content processing, rendering, and generation.
    pub mod traits;
}

/// Provides command-line interface utilities.
pub mod cli;

/// Provides output generation utilities.
pub mod generators;

/// Provides processing pipeline utilities.
pub mod process;

/// Provides processors for content transformation.
pub mod processors;

/// Provides template rendering utilities.
pub mod template;

/// Trait for content processing implementations.
///
/// Implementations of this trait process content, transforming it based on
/// a given context.
pub trait ContentProcessor: Send + Sync + std::fmt::Debug {
    /// Processes the provided content with an optional context.
    ///
    /// # Arguments
    /// * `content` - The content to be processed.
    /// * `context` - An optional context for additional processing.
    ///
    /// # Returns
    /// * `Result<String>` - The processed content, or an error if processing fails.
    fn process(
        &self,
        content: &str,
        context: Option<&serde_json::Value>,
    ) -> Result<String>;

    /// Validates the content without processing.
    ///
    /// # Arguments
    /// * `content` - The content to be validated.
    ///
    /// # Returns
    /// * `Result<()>` - Indicates success if the content is valid, or an error if invalid.
    fn validate(&self, content: &str) -> Result<()>;
}

/// Trait for template rendering implementations.
///
/// This trait defines methods for rendering and validating templates.
pub trait TemplateRenderer: Send + Sync + std::fmt::Debug {
    /// Renders a template with the specified context.
    ///
    /// # Arguments
    /// * `template` - The template name or identifier.
    /// * `context` - The context data for rendering the template.
    ///
    /// # Returns
    /// * `Result<String>` - The rendered output, or an error if rendering fails.
    fn render(
        &self,
        template: &str,
        context: &serde_json::Value,
    ) -> Result<String>;

    /// Validates the template against the context.
    ///
    /// # Arguments
    /// * `template` - The template name or identifier.
    /// * `context` - The context data.
    ///
    /// # Returns
    /// * `Result<()>` - Indicates success if valid, or an error otherwise.
    fn validate(
        &self,
        template: &str,
        context: &serde_json::Value,
    ) -> Result<()>;
}

/// Concrete implementation of `ContentProcessor` that processes file content.
///
/// This processor transforms content to uppercase as a simple example.
#[derive(Debug)]
pub struct FileContentProcessor {
    /// The base path for content files.
    pub base_path: PathBuf,
}

impl FileContentProcessor {
    /// Creates a new `FileContentProcessor`.
    pub fn new(base_path: PathBuf) -> Self {
        Self { base_path }
    }
}

impl ContentProcessor for FileContentProcessor {
    fn process(
        &self,
        content: &str,
        _context: Option<&serde_json::Value>,
    ) -> Result<String> {
        Ok(content.to_uppercase())
    }

    fn validate(&self, _content: &str) -> Result<()> {
        Ok(())
    }
}

/// Concrete implementation of `TemplateRenderer` for rendering HTML templates.
#[derive(Debug)]
pub struct HtmlTemplateRenderer {
    /// The base path for template files.
    pub base_path: PathBuf,
}

impl HtmlTemplateRenderer {
    /// Creates a new `HtmlTemplateRenderer`.
    pub fn new(base_path: PathBuf) -> Self {
        Self { base_path }
    }
}

impl TemplateRenderer for HtmlTemplateRenderer {
    fn render(
        &self,
        _template: &str,
        context: &serde_json::Value,
    ) -> Result<String> {
        Ok(format!(
            "<html>{}</html>",
            context["content"].as_str().unwrap_or("")
        ))
    }

    fn validate(
        &self,
        _template: &str,
        _context: &serde_json::Value,
    ) -> Result<()> {
        Ok(())
    }
}

/// Concrete implementation of `Generator` for generating HTML files.
#[derive(Debug)]
pub struct HtmlOutputGenerator {
    /// The base path for output files.
    pub base_path: PathBuf,
}

impl HtmlOutputGenerator {
    /// Creates a new `HtmlOutputGenerator`.
    pub fn new(base_path: PathBuf) -> Self {
        Self { base_path }
    }
}

impl Generator for HtmlOutputGenerator {
    fn generate(
        &self,
        content: &str,
        path: &Path,
        _options: Option<&serde_json::Value>,
    ) -> Result<()> {
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).map_err(|e| {
                ProcessingError::io_error(parent.to_path_buf(), e)
            })?;
        }
        let mut file = fs::File::create(path)?;
        file.write_all(content.as_bytes())?;
        Ok(())
    }

    fn validate(
        &self,
        path: &Path,
        _options: Option<&serde_json::Value>,
    ) -> Result<()> {
        if let Some(parent) = path.parent() {
            if !parent.exists() {
                fs::create_dir_all(parent).map_err(|e| {
                    ProcessingError::io_error(parent.to_path_buf(), e)
                })?;
            }
        }
        Ok(())
    }
}

/// Configuration settings for NucleusFlow.
#[derive(Debug, Clone)]
pub struct NucleusFlowConfig {
    /// The directory containing content files.
    pub content_dir: PathBuf,
    /// The directory for generated output files.
    pub output_dir: PathBuf,
    /// The directory containing template files.
    pub template_dir: PathBuf,
}

impl NucleusFlowConfig {
    /// Creates a new `NucleusFlowConfig` and validates directory paths.
    pub fn new<P: AsRef<Path>>(
        content_dir: P,
        output_dir: P,
        template_dir: P,
    ) -> Result<Self> {
        let content_dir = content_dir.as_ref().to_path_buf();
        let output_dir = output_dir.as_ref().to_path_buf();
        let template_dir = template_dir.as_ref().to_path_buf();

        for dir in [&content_dir, &template_dir] {
            if !dir.exists() || !dir.is_dir() {
                return Err(ProcessingError::configuration(
                    "Invalid directory",
                    Some(dir.clone()),
                    None,
                ));
            }
        }

        if !output_dir.exists() {
            fs::create_dir_all(&output_dir).map_err(|e| {
                ProcessingError::configuration(
                    format!("Failed to create output directory: {}", e),
                    Some(output_dir.clone()),
                    None,
                )
            })?;
        }

        Ok(Self {
            content_dir,
            output_dir,
            template_dir,
        })
    }
}

/// Main content processing pipeline for NucleusFlow.
#[derive(Debug)]
pub struct NucleusFlow {
    config: NucleusFlowConfig,
    content_processor: Box<dyn ContentProcessor>,
    template_renderer: Box<dyn TemplateRenderer>,
    output_generator: Box<dyn Generator>,
}

impl NucleusFlow {
    /// Creates a new instance of `NucleusFlow`.
    pub fn new(
        config: NucleusFlowConfig,
        content_processor: Box<dyn ContentProcessor>,
        template_renderer: Box<dyn TemplateRenderer>,
        output_generator: Box<dyn Generator>,
    ) -> Self {
        Self {
            config,
            content_processor,
            template_renderer,
            output_generator,
        }
    }

    /// Processes content files, transforms, renders, and generates HTML output.
    pub fn process(&self) -> Result<()> {
        for entry in fs::read_dir(&self.config.content_dir)? {
            let entry = entry?;
            let path = entry.path();

            if path.is_file() {
                self.process_file(&path)?;
            }
        }
        Ok(())
    }

    /// Processes a single file within the pipeline.
    ///
    /// # Arguments
    /// * `path` - The path to the file to be processed.
    ///
    /// # Returns
    /// * `Result<()>` - Indicates success, or an error if processing fails.
    fn process_file(&self, path: &Path) -> Result<()> {
        let content = fs::read_to_string(path)?;
        let processed =
            self.content_processor.process(&content, None)?;
        let context =
            serde_json::json!({ "content": processed, "path": path });

        let template_name = "default";
        let rendered =
            self.template_renderer.render(template_name, &context)?;

        let relative_path = path
            .strip_prefix(&self.config.content_dir)
            .map_err(|e| ProcessingError::ContentProcessing {
                details: format!(
                    "Failed to determine relative path: {}",
                    e
                ),
                source: None,
            })?;
        let output_path = self
            .config
            .output_dir
            .join(relative_path)
            .with_extension("html");

        self.output_generator.generate(
            &rendered,
            &output_path,
            None,
        )?;

        Ok(())
    }
}

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

    #[test]
    fn test_nucleus_flow_config_new() {
        let temp_dir = TempDir::new().unwrap();
        let content_path = temp_dir.path().join("content");
        let output_path = temp_dir.path().join("output");
        let template_path = temp_dir.path().join("templates");

        fs::create_dir(&content_path).unwrap();
        fs::create_dir(&template_path).unwrap();

        let config = NucleusFlowConfig::new(
            &content_path,
            &output_path,
            &template_path,
        )
        .unwrap();

        assert_eq!(config.content_dir, content_path);
        assert_eq!(config.output_dir, output_path);
        assert_eq!(config.template_dir, template_path);
    }

    #[test]
    fn test_nucleus_flow_process() -> Result<()> {
        let temp_dir = TempDir::new().unwrap();
        let content_path = temp_dir.path().join("content");
        let output_path = temp_dir.path().join("output");
        let template_path = temp_dir.path().join("templates");

        fs::create_dir(&content_path)?;
        fs::create_dir(&template_path)?;

        let test_content = "test content";
        let content_file = content_path.join("test.txt");
        fs::write(&content_file, test_content)?;

        let config = NucleusFlowConfig::new(
            &content_path,
            &output_path,
            &template_path,
        )?;

        let nucleus = NucleusFlow::new(
            config,
            Box::new(FileContentProcessor::new(content_path.clone())),
            Box::new(HtmlTemplateRenderer::new(template_path.clone())),
            Box::new(HtmlOutputGenerator::new(output_path.clone())),
        );

        nucleus.process()?;

        let output_file = output_path.join("test.html");
        assert!(output_file.exists());

        let output_content = fs::read_to_string(output_file)?;
        assert_eq!(output_content, "<html>TEST CONTENT</html>");

        Ok(())
    }
}