confers 0.2.2

A modern, type-safe configuration management library with validation, diff, and hot-reload support
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
// Copyright (c) 2025 Kirky.X
//
// Licensed under the MIT License
// See LICENSE file in the project root for full license information.

use crate::error::ConfigError;
use serde::Serialize;
use std::fs;

#[cfg(feature = "schema")]
use schemars::{schema_for, JsonSchema};

/// 模板生成级别 - 控制生成模板的详细程度
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GenerateLevel {
    /// 仅包含必要字段的最小模板
    Minimal,
    /// 包含所有字段和详细注释的完整模板
    Full,
    /// 带解释的文档样式模板
    Documentation,
}

impl GenerateLevel {
    /// 将级别字符串解析为 GenerateLevel 枚举
    pub fn parse(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "minimal" | "min" => GenerateLevel::Minimal,
            "doc" | "documentation" => GenerateLevel::Documentation,
            "full" => GenerateLevel::Full,
            _ => GenerateLevel::Full,
        }
    }
}

impl std::str::FromStr for GenerateLevel {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self::parse(s))
    }
}

pub struct GenerateCommand;

impl GenerateCommand {
    /// 为特定 Config 类型生成模板
    #[cfg(feature = "schema")]
    pub fn execute<T>(output: Option<&String>, level: &str) -> Result<(), ConfigError>
    where
        T: Serialize + Default + JsonSchema,
    {
        let defaults = T::default();
        let generate_level = GenerateLevel::parse(level);
        let content = match generate_level {
            GenerateLevel::Minimal => toml::to_string(&defaults)
                .map_err(|e| ConfigError::FormatDetectionFailed(e.to_string()))?,
            GenerateLevel::Documentation => generate_documentation_template::<T>(),
            GenerateLevel::Full => toml::to_string_pretty(&defaults)
                .map_err(|e| ConfigError::FormatDetectionFailed(e.to_string()))?,
        };
        Self::write_content(output, &content)
    }

    #[cfg(not(feature = "schema"))]
    pub fn execute<T>(output: Option<&String>, level: &str) -> Result<(), ConfigError>
    where
        T: Serialize + Default,
    {
        let defaults = T::default();
        let generate_level = GenerateLevel::parse(level);
        let content = match generate_level {
            GenerateLevel::Minimal => toml::to_string(&defaults)
                .map_err(|e| ConfigError::FormatDetectionFailed(e.to_string()))?,
            GenerateLevel::Documentation => generate_documentation_template::<T>(),
            GenerateLevel::Full => toml::to_string_pretty(&defaults)
                .map_err(|e| ConfigError::FormatDetectionFailed(e.to_string()))?,
        };
        Self::write_content(output, &content)
    }

    /// 生成通用占位符(用于独立 CLI)
    pub fn execute_placeholder(
        output: Option<&String>,
        level: &str,
        struct_name: Option<&String>,
        format: &str,
    ) -> Result<String, ConfigError> {
        let generate_level = GenerateLevel::parse(level);
        let mut toml_content = match generate_level {
            GenerateLevel::Minimal => Self::minimal_template(),
            GenerateLevel::Documentation => Self::documentation_template(),
            GenerateLevel::Full => Self::full_template(),
        };

        // If struct name is provided, customize the template
        if let Some(name) = struct_name {
            toml_content =
                toml_content.replace("name = \"example\"", &format!("name = \"{}\"", name));
            toml_content = toml_content.replace(
                "# Minimal Config Template",
                &format!("# {} Config Template", name),
            );
            toml_content = toml_content.replace(
                "# Full Config Template",
                &format!("# {} Config Template", name),
            );
            toml_content = toml_content.replace(
                "Configuration Template",
                &format!("{} Configuration Template", name),
            );
        }

        // Convert format
        let content = if format.eq_ignore_ascii_case("toml") {
            toml_content
        } else {
            let value: toml::Value = toml::from_str(&toml_content)
                .map_err(|e| ConfigError::ParseError(format!("Failed to parse template: {}", e)))?;

            match format.to_lowercase().as_str() {
                "json" => serde_json::to_string_pretty(&value)
                    .map_err(|e| ConfigError::SerializationError(e.to_string()))?,
                "yaml" | "yml" => serde_yaml::to_string(&value)
                    .map_err(|e| ConfigError::SerializationError(e.to_string()))?,
                "ini" => {
                    // Check if the value is flat enough for INI
                    // If it's too nested, serde_ini might fail or produce unexpected results.
                    // But for our templates, they are generally section-based (Map<String, Map<String, Value>>)
                    serde_ini::to_string(&value).map_err(|e| {
                        ConfigError::SerializationError(format!(
                            "INI serialization failed (structure might be too deep): {}",
                            e
                        ))
                    })?
                }
                _ => {
                    return Err(ConfigError::FormatDetectionFailed(format!(
                        "Unsupported format: {}",
                        format
                    )))
                }
            }
        };

        Self::write_content(output, &content)?;
        Ok(content)
    }

    /// 最小模板 - 仅包含必要字段
    fn minimal_template() -> String {
        "# Minimal Config Template\n# Generated by confers\n\n[app]\nname = \"example\"\nversion = \"1.0.0\"\n".to_string()
    }

    /// 完整模板 - 包含所有字段和结构
    fn full_template() -> String {
        "# Full Config Template\n# Generated by confers\n\n# Basic configuration\n[app]\nname = \"example\"\nversion = \"1.0.0\"\n\n# Server settings\n[server]\nhost = \"localhost\"\nport = 8080\n\n# Database configuration\n[database]\nurl = \"postgres://localhost/mydb\"\npool_size = 10\n\n# Logging configuration\n[logging]\nlevel = \"info\"\nformat = \"json\"\n".to_string()
    }

    /// 文档模板 - 包含详细解释
    #[cfg(feature = "schema")]
    fn documentation_template() -> String {
        #[derive(Default, Serialize, JsonSchema)]
        struct GenericPlaceholder {
            name: String,
            version: String,
            description: String,
        }
        generate_documentation_template::<GenericPlaceholder>()
    }

    #[cfg(not(feature = "schema"))]
    fn documentation_template() -> String {
        generate_documentation_template::<()>()
    }

    fn write_content(output: Option<&String>, content: &str) -> Result<(), ConfigError> {
        if let Some(path) = output {
            fs::write(path, content)
                .map_err(|e| ConfigError::FormatDetectionFailed(e.to_string()))?;
        } else {
            println!("{}", content);
        }
        Ok(())
    }
}

/// 生成带详细注释的文档样式模板
#[cfg(feature = "schema")]
fn generate_documentation_template<T: Default + JsonSchema + serde::Serialize>() -> String {
    let defaults = T::default();
    let defaults_str = toml::to_string_pretty(&defaults)
        .map_err(|_| ConfigError::FormatDetectionFailed("Failed to serialize defaults".to_string()))
        .unwrap_or_default();

    let schema = schema_for!(T);
    let schema_value = serde_json::to_value(&schema)
        .map_err(|_| ConfigError::FormatDetectionFailed("Failed to serialize schema".to_string()))
        .unwrap_or_default();

    let struct_name = schema_value
        .get("title")
        .and_then(|t| t.as_str())
        .unwrap_or("Config");

    let mut doc = format!(
        r#"# Documentation Configuration Template for {}
# Generated by confers - Configuration Management Tool
# ============================================================
# This template includes detailed comments to help you understand
# each configuration option and its purpose.
# -----------------------------------------------------------

"#,
        struct_name
    );

    if let Some(properties) = schema_value.get("properties").and_then(|p| p.as_object()) {
        generate_property_documentation(properties, "", &mut doc);
    }

    doc.push_str(&format!(
        "\n# ============================================================\n# Default Values Reference\n# -----------------------------------------------------------\n{}\n# -----------------------------------------------------------\n",
        defaults_str
    ));

    doc
}

#[cfg(not(feature = "schema"))]
fn generate_documentation_template<T: Default + serde::Serialize>() -> String {
    let defaults = T::default();
    let defaults_str = toml::to_string_pretty(&defaults)
        .map_err(|_| ConfigError::FormatDetectionFailed("Failed to serialize defaults".to_string()))
        .unwrap_or_default();

    let mut doc = r#"# Configuration Template (Documentation Mode)
# Generated by confers - Configuration Management Tool
# ============================================================
# This template includes detailed comments to help you understand
# each configuration option and its purpose.

"#
    .to_string();

    doc.push_str(&format!(
        "# Default Values\n# -----------------------------------------------------------\n{}\n# -----------------------------------------------------------\n",
        defaults_str
    ));

    doc
}

#[cfg(feature = "schema")]
fn generate_property_documentation(
    properties: &serde_json::Map<String, serde_json::Value>,
    prefix: &str,
    doc: &mut String,
) {
    for (prop_name, prop_schema) in properties {
        let full_name = if prefix.is_empty() {
            prop_name.clone()
        } else {
            format!("{}.{}", prefix, prop_name)
        };

        if let Some(obj_props) = prop_schema.get("properties").and_then(|p| p.as_object()) {
            doc.push_str(&format!("# [{}]\n", full_name));
            if let Some(desc) = prop_schema.get("description").and_then(|d| d.as_str()) {
                doc.push_str(&format!("# {}\n", desc));
            }
            doc.push_str("#\n");
            generate_property_documentation(obj_props, &full_name, doc);
            doc.push('\n');
        } else {
            let type_str = prop_schema
                .get("type")
                .and_then(|t| t.as_str())
                .unwrap_or("unknown");

            if let Some(desc) = prop_schema.get("description").and_then(|d| d.as_str()) {
                doc.push_str(&format!("# {}\n", desc));
            }

            let default_val = prop_schema
                .get("default")
                .map(|v| format!(" (default: {})", v));

            let enum_vals = prop_schema
                .get("enum")
                .and_then(|e| e.as_array())
                .map(|vals| {
                    let vals_str: Vec<String> = vals
                        .iter()
                        .filter_map(|v| v.as_str().map(|s| format!("'{}'", s)))
                        .collect();
                    format!(" (options: {})", vals_str.join(", "))
                });

            let example = match type_str {
                "string" | "integer" | "number" | "boolean" => {
                    format!("{} = \"{}\"", prop_name, "<value>")
                }
                _ => format!("{} = <{}>", prop_name, type_str),
            };

            if let Some(dv) = default_val {
                doc.push_str(&format!("{}{}\n", example, dv));
            } else if let Some(ev) = enum_vals {
                doc.push_str(&format!("{}{}\n", example, ev));
            } else {
                doc.push_str(&format!("{}\n", example));
            }
            doc.push('\n');
        }
    }
}

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

    #[cfg(feature = "schema")]
    mod with_schema {
        use super::*;
        use schemars::JsonSchema;

        #[derive(Debug, Default, Serialize, JsonSchema)]
        struct TestConfig {
            name: String,
            port: u16,
            #[schemars(skip)]
            secret: String,
        }

        #[test]
        fn test_documentation_with_schema() {
            let result = GenerateCommand::execute::<TestConfig>(None, "documentation");
            assert!(result.is_ok());

            let result = GenerateCommand::execute::<TestConfig>(None, "doc");
            assert!(result.is_ok());
        }
    }

    #[test]
    fn test_generate_level_parsing() {
        assert_eq!(GenerateLevel::parse("minimal"), GenerateLevel::Minimal);
        assert_eq!(GenerateLevel::parse("min"), GenerateLevel::Minimal);
        assert_eq!(GenerateLevel::parse("doc"), GenerateLevel::Documentation);
        assert_eq!(
            GenerateLevel::parse("documentation"),
            GenerateLevel::Documentation
        );
        assert_eq!(GenerateLevel::parse("full"), GenerateLevel::Full);
        assert_eq!(GenerateLevel::parse("unknown"), GenerateLevel::Full);
        assert_eq!(GenerateLevel::parse("FULL"), GenerateLevel::Full);
        assert_eq!(GenerateLevel::parse("DOC"), GenerateLevel::Documentation);
    }

    #[test]
    fn test_generate_command_minimal() {
        let result = GenerateCommand::execute_placeholder(None, "minimal", None, "toml");
        assert!(result.is_ok());
        let content = result.unwrap();
        assert!(content.contains("name = \"example\""));
        assert!(content.contains("# Minimal Config Template"));
    }

    #[test]
    fn test_generate_command_full() {
        let result = GenerateCommand::execute_placeholder(None, "full", None, "toml");
        assert!(result.is_ok());
        let content = result.unwrap();
        assert!(content.contains("[server]"));
        assert!(content.contains("[database]"));
        assert!(content.contains("# Full Config Template"));
    }

    #[test]
    fn test_generate_command_documentation_fallback() {
        let result = GenerateCommand::execute_placeholder(None, "doc", None, "toml");
        assert!(result.is_ok());
        let content = result.unwrap();
        assert!(content.contains("Configuration Template"));
        assert!(content.contains("Generated by confers"));
    }

    #[test]
    fn test_generate_level_affects_output() {
        let minimal = GenerateCommand::execute_placeholder(None, "minimal", None, "toml").unwrap();
        let full = GenerateCommand::execute_placeholder(None, "full", None, "toml").unwrap();
        let doc = GenerateCommand::execute_placeholder(None, "doc", None, "toml").unwrap();

        assert_ne!(minimal, full);
        assert_ne!(full, doc);
        assert_ne!(minimal, doc);

        assert!(minimal.contains("Minimal"));
        assert!(full.contains("Full"));
        assert!(doc.contains("Documentation"));
    }
}