nargo-document 0.0.0

Nargo documentation tool
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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fs::File, io::Read, path::Path};

/// 配置加载和验证相关的错误类型
#[derive(Debug)]
pub enum ConfigError {
    /// 文件读取错误
    FileReadError(std::io::Error),
    /// JSON 解析错误
    JsonParseError(serde_json::Error),
    /// TOML 解析错误
    TomlParseError(toml::de::Error),
    /// 配置验证错误
    ValidationError(String),
    /// 不支持的配置文件格式
    UnsupportedFormat(String),
}

impl std::error::Error for ConfigError {
    fn description(&self) -> &str {
        match self {
            ConfigError::FileReadError(_) => "Failed to read config file",
            ConfigError::JsonParseError(_) => "Failed to parse JSON config",
            ConfigError::TomlParseError(_) => "Failed to parse TOML config",
            ConfigError::ValidationError(_) => "Config validation error",
            ConfigError::UnsupportedFormat(_) => "Unsupported config file format",
        }
    }
}

impl std::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConfigError::FileReadError(err) => write!(f, "Failed to read config file: {}", err),
            ConfigError::JsonParseError(err) => write!(f, "Failed to parse JSON config: {}", err),
            ConfigError::TomlParseError(err) => write!(f, "Failed to parse TOML config: {}", err),
            ConfigError::ValidationError(msg) => write!(f, "Config validation error: {}", msg),
            ConfigError::UnsupportedFormat(fmt) => write!(f, "Unsupported config file format: {}", fmt),
        }
    }
}

impl From<std::io::Error> for ConfigError {
    fn from(err: std::io::Error) -> Self {
        ConfigError::FileReadError(err)
    }
}

impl From<serde_json::Error> for ConfigError {
    fn from(err: serde_json::Error) -> Self {
        ConfigError::JsonParseError(err)
    }
}

impl From<toml::de::Error> for ConfigError {
    fn from(err: toml::de::Error) -> Self {
        ConfigError::TomlParseError(err)
    }
}

/// 配置验证 trait
pub trait ConfigValidation {
    /// 验证配置的有效性
    ///
    /// # Errors
    ///
    /// 返回 `ConfigError::ValidationError` 如果配置无效
    fn validate(&self) -> Result<(), ConfigError>;
}

/// Nargo Document 配置 - 兼容 VuTeX 配置格式
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct Config {
    /// 站点标题
    pub title: Option<String>,
    /// 站点描述
    pub description: Option<String>,
    /// 基础路径
    pub base: Option<String>,
    /// 语言配置
    pub locales: HashMap<String, LocaleConfig>,
    /// 主题配置
    pub theme: ThemeConfig,
    /// 插件配置
    pub plugins: Vec<PluginConfig>,
    /// Markdown 配置
    pub markdown: MarkdownConfig,
    /// 构建配置
    pub build: BuildConfig,
}

impl Config {
    /// 从文件加载配置,根据文件扩展名自动选择解析器
    ///
    /// # Arguments
    ///
    /// * `path` - 配置文件的路径
    ///
    /// # Errors
    ///
    /// 返回 `ConfigError` 如果文件读取或解析失败
    pub fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Self, ConfigError> {
        let path = path.as_ref();
        let content = std::fs::read_to_string(path)?;

        match path.extension().and_then(|ext| ext.to_str()) {
            Some("json") => Self::load_from_json_str(&content),
            Some("toml") => Self::load_from_toml_str(&content),
            Some(ext) => Err(ConfigError::UnsupportedFormat(ext.to_string())),
            None => Err(ConfigError::UnsupportedFormat("no extension".to_string())),
        }
    }

    /// 从 JSON 字符串加载配置
    ///
    /// # Arguments
    ///
    /// * `json_str` - JSON 格式的配置字符串
    ///
    /// # Errors
    ///
    /// 返回 `ConfigError::JsonParseError` 如果 JSON 解析失败
    pub fn load_from_json_str(json_str: &str) -> Result<Self, ConfigError> {
        let config: Self = serde_json::from_str(json_str)?;
        config.validate()?;
        Ok(config)
    }

    /// 从 TOML 字符串加载配置
    ///
    /// # Arguments
    ///
    /// * `toml_str` - TOML 格式的配置字符串
    ///
    /// # Errors
    ///
    /// 返回 `ConfigError::TomlParseError` 如果 TOML 解析失败
    pub fn load_from_toml_str(toml_str: &str) -> Result<Self, ConfigError> {
        let config: Self = toml::from_str(toml_str)?;
        config.validate()?;
        Ok(config)
    }

    /// 从目录中查找并加载配置文件
    ///
    /// 按以下顺序查找配置文件:
    /// 1. nargodoc.config.toml
    /// 2. nargodoc.config.json
    /// 3. vutex.config.toml (兼容)
    /// 4. vutex.config.json (兼容)
    ///
    /// # Arguments
    ///
    /// * `dir` - 要搜索的目录路径
    ///
    /// # Errors
    ///
    /// 返回 `ConfigError` 如果配置文件读取或解析失败
    pub fn load_from_dir<P: AsRef<Path>>(dir: P) -> Result<Self, ConfigError> {
        let dir = dir.as_ref();

        let toml_path = dir.join("nargodoc.config.toml");
        if toml_path.exists() {
            return Self::load_from_file(toml_path);
        }

        let json_path = dir.join("nargodoc.config.json");
        if json_path.exists() {
            return Self::load_from_file(json_path);
        }

        let vutex_toml_path = dir.join("vutex.config.toml");
        if vutex_toml_path.exists() {
            return Self::load_from_file(vutex_toml_path);
        }

        let vutex_json_path = dir.join("vutex.config.json");
        if vutex_json_path.exists() {
            return Self::load_from_file(vutex_json_path);
        }

        Ok(Self::default())
    }

    /// 将配置序列化为 JSON 字符串
    ///
    /// # Errors
    ///
    /// 返回 `serde_json::Error` 如果序列化失败
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// 将配置序列化为 TOML 字符串
    ///
    /// # Errors
    ///
    /// 返回 `toml::ser::Error` 如果序列化失败
    pub fn to_toml(&self) -> Result<String, toml::ser::Error> {
        toml::to_string_pretty(self)
    }

    /// 创建新的配置
    pub fn new() -> Self {
        Self::default()
    }

    /// 设置站点标题
    pub fn with_title(mut self, title: String) -> Self {
        self.title = Some(title);
        self
    }

    /// 设置站点描述
    pub fn with_description(mut self, description: String) -> Self {
        self.description = Some(description);
        self
    }

    /// 添加语言配置
    pub fn add_locale(mut self, lang: String, config: LocaleConfig) -> Self {
        self.locales.insert(lang, config);
        self
    }
}

impl ConfigValidation for Config {
    fn validate(&self) -> Result<(), ConfigError> {
        let default_count = self.locales.iter().filter(|(_, cfg)| cfg.default.unwrap_or(false)).count();
        if default_count > 1 {
            return Err(ConfigError::ValidationError(format!("Multiple default locales specified: found {} default locales", default_count)));
        }

        for (lang_code, locale) in &self.locales {
            if lang_code.is_empty() {
                return Err(ConfigError::ValidationError("Locale code cannot be empty".to_string()));
            }
            locale.validate()?;
        }

        self.theme.validate()?;

        for (i, plugin) in self.plugins.iter().enumerate() {
            if plugin.name.is_empty() {
                return Err(ConfigError::ValidationError(format!("Plugin at index {} has empty name", i)));
            }
        }

        self.markdown.validate()?;
        self.build.validate()?;

        Ok(())
    }
}

/// 语言配置
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct LocaleConfig {
    /// 语言标签
    pub label: String,
    /// 语言描述
    pub description: Option<String>,
    /// 语言链接
    pub link: Option<String>,
    /// 是否为默认语言
    pub default: Option<bool>,
    /// 导航栏配置(语言特定)
    pub nav: Option<Vec<NavItem>>,
    /// 侧边栏配置(语言特定)
    pub sidebar: Option<HashMap<String, Vec<SidebarItem>>>,
}

impl LocaleConfig {
    /// 创建新的语言配置
    pub fn new(label: String) -> Self {
        Self { label, description: None, link: None, default: None, nav: None, sidebar: None }
    }

    /// 设置为默认语言
    pub fn with_default(mut self, is_default: bool) -> Self {
        self.default = Some(is_default);
        self
    }

    /// 设置导航栏配置
    pub fn with_nav(mut self, nav: Vec<NavItem>) -> Self {
        self.nav = Some(nav);
        self
    }

    /// 设置侧边栏配置
    pub fn with_sidebar(mut self, sidebar: HashMap<String, Vec<SidebarItem>>) -> Self {
        self.sidebar = Some(sidebar);
        self
    }
}

impl ConfigValidation for LocaleConfig {
    fn validate(&self) -> Result<(), ConfigError> {
        if self.label.is_empty() {
            return Err(ConfigError::ValidationError("Locale label cannot be empty".to_string()));
        }

        if let Some(nav) = &self.nav {
            for (i, item) in nav.iter().enumerate() {
                item.validate().map_err(|e| ConfigError::ValidationError(format!("Nav item at index {}: {}", i, e)))?;
            }
        }

        if let Some(sidebar) = &self.sidebar {
            for (group_key, items) in sidebar {
                for (i, item) in items.iter().enumerate() {
                    item.validate().map_err(|e| ConfigError::ValidationError(format!("Sidebar item in group '{}' at index {}: {}", group_key, i, e)))?;
                }
            }
        }

        Ok(())
    }
}

/// 主题配置
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct ThemeConfig {
    /// 导航栏配置
    pub nav: Vec<NavItem>,
    /// 侧边栏配置
    pub sidebar: HashMap<String, Vec<SidebarItem>>,
    /// 社交链接
    pub social_links: Vec<SocialLink>,
    /// 页脚配置
    pub footer: Option<FooterConfig>,
    /// 自定义配置
    pub custom: HashMap<String, serde_json::Value>,
}

impl ThemeConfig {
    /// 创建新的主题配置
    pub fn new() -> Self {
        Self::default()
    }

    /// 添加导航栏项
    pub fn add_nav_item(mut self, item: NavItem) -> Self {
        self.nav.push(item);
        self
    }
}

impl ConfigValidation for ThemeConfig {
    fn validate(&self) -> Result<(), ConfigError> {
        for (i, item) in self.nav.iter().enumerate() {
            item.validate().map_err(|e| ConfigError::ValidationError(format!("Theme nav item at index {}: {}", i, e)))?;
        }

        for (group_key, items) in &self.sidebar {
            for (i, item) in items.iter().enumerate() {
                item.validate().map_err(|e| ConfigError::ValidationError(format!("Theme sidebar item in group '{}' at index {}: {}", group_key, i, e)))?;
            }
        }

        for (i, link) in self.social_links.iter().enumerate() {
            if link.platform.is_empty() {
                return Err(ConfigError::ValidationError(format!("Social link at index {} has empty platform name", i)));
            }
            if link.link.is_empty() {
                return Err(ConfigError::ValidationError(format!("Social link at index {} has empty URL", i)));
            }
        }

        Ok(())
    }
}

/// 导航栏项
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct NavItem {
    /// 显示文本
    pub text: String,
    /// 链接
    pub link: Option<String>,
    /// 子项
    pub items: Option<Vec<NavItem>>,
}

impl NavItem {
    /// 创建新的导航栏项
    pub fn new(text: String) -> Self {
        Self { text, link: None, items: None }
    }

    /// 设置链接
    pub fn with_link(mut self, link: String) -> Self {
        self.link = Some(link);
        self
    }

    /// 添加子项
    pub fn add_item(mut self, item: NavItem) -> Self {
        if self.items.is_none() {
            self.items = Some(Vec::new());
        }
        if let Some(items) = &mut self.items {
            items.push(item);
        }
        self
    }
}

impl ConfigValidation for NavItem {
    fn validate(&self) -> Result<(), ConfigError> {
        if self.text.is_empty() {
            return Err(ConfigError::ValidationError("Nav item text cannot be empty".to_string()));
        }

        if let Some(items) = &self.items {
            for (i, item) in items.iter().enumerate() {
                item.validate().map_err(|e| ConfigError::ValidationError(format!("Sub-item at index {}: {}", i, e)))?;
            }
        }

        Ok(())
    }
}

/// 侧边栏项
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SidebarItem {
    /// 显示文本
    pub text: String,
    /// 链接
    pub link: Option<String>,
    /// 子项
    pub items: Option<Vec<SidebarItem>>,
    /// 是否折叠
    pub collapsed: Option<bool>,
}

impl SidebarItem {
    /// 创建新的侧边栏项
    pub fn new(text: String) -> Self {
        Self { text, link: None, items: None, collapsed: None }
    }

    /// 设置链接
    pub fn with_link(mut self, link: String) -> Self {
        self.link = Some(link);
        self
    }
}

impl ConfigValidation for SidebarItem {
    fn validate(&self) -> Result<(), ConfigError> {
        if self.text.is_empty() {
            return Err(ConfigError::ValidationError("Sidebar item text cannot be empty".to_string()));
        }

        if let Some(items) = &self.items {
            for (i, item) in items.iter().enumerate() {
                item.validate().map_err(|e| ConfigError::ValidationError(format!("Sub-item at index {}: {}", i, e)))?;
            }
        }

        Ok(())
    }
}

/// 社交链接
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SocialLink {
    /// 平台名称
    pub platform: String,
    /// 链接
    pub link: String,
}

/// 页脚配置
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct FooterConfig {
    /// 版权信息
    pub copyright: Option<String>,
    /// 页脚消息
    pub message: Option<String>,
}

/// 插件配置
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PluginConfig {
    /// 插件名称
    pub name: String,
    /// 插件配置
    pub options: HashMap<String, serde_json::Value>,
}

/// Markdown 配置
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct MarkdownConfig {
    /// 是否启用行号
    pub line_numbers: bool,
    /// 代码主题
    pub code_theme: Option<String>,
    /// 自定义配置
    pub custom: HashMap<String, serde_json::Value>,
}

impl ConfigValidation for MarkdownConfig {
    fn validate(&self) -> Result<(), ConfigError> {
        Ok(())
    }
}

/// 构建配置
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct BuildConfig {
    /// 输出目录
    pub out_dir: Option<String>,
    /// 源目录
    pub src_dir: Option<String>,
    /// 是否启用清理
    pub clean: bool,
    /// 是否启用压缩
    pub minify: bool,
}

impl ConfigValidation for BuildConfig {
    fn validate(&self) -> Result<(), ConfigError> {
        Ok(())
    }
}

/// 兼容旧版 HXO Document 的 Locale 结构
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct LegacyLocale {
    pub label: String,
    pub lang: String,
    pub link: String,
    pub theme_config: Option<ThemeConfig>,
}

/// 兼容旧版 HXO Document 的 Footer 结构
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct LegacyFooter {
    pub message: String,
    pub copyright: String,
}

/// 兼容旧版 HXO Document 的 MarkdownTheme 结构
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct LegacyMarkdownTheme {
    pub light: String,
    pub dark: String,
}

/// 兼容旧版 HXO Document 的 MarkdownConfig 结构
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct LegacyMarkdownConfig {
    pub theme: Option<LegacyMarkdownTheme>,
    pub shiki_setup: Option<serde_json::Value>,
}

/// 兼容旧版 HXO Document 的 BuildConfig 结构
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct LegacyBuildConfig {
    pub out_dir: Option<String>,
    pub base: Option<String>,
}

/// 兼容旧版 HXO Document 的配置结构
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct LegacyConfig {
    pub title: String,
    pub description: String,
    pub locales: Option<Vec<LegacyLocale>>,
    pub theme: Option<String>,
    pub theme_config: Option<ThemeConfig>,
    pub markdown: Option<LegacyMarkdownConfig>,
    pub build: Option<LegacyBuildConfig>,
}