Skip to main content

nargo_config/
lib.rs

1#![warn(missing_docs)]
2
3use nargo_types::Result;
4use serde::{Deserialize, Serialize};
5use std::path::PathBuf;
6
7/// Nargo 配置文件的默认名称
8pub const DEFAULT_CONFIG_FILE: &str = "Nargo.toml";
9
10/// Nargo 配置文件的可能扩展名
11pub const CONFIG_EXTENSIONS: &[&str] = &[".toml"];
12
13/// Nargo 框架的配置结构
14///
15/// 用于管理 Nargo 项目的编译、构建和运行时配置。
16#[derive(Debug, Clone, Serialize, Deserialize, Default)]
17pub struct NargoConfig {
18    /// 项目名称
19    pub name: Option<String>,
20
21    /// 项目版本
22    pub version: Option<String>,
23
24    /// 编译配置
25    pub build: Option<BuildConfig>,
26
27    /// 开发服务器配置
28    pub dev: Option<DevConfig>,
29
30    /// 插件配置
31    pub plugins: Option<Vec<PluginConfig>>,
32
33    /// 路径别名配置
34    pub aliases: Option<std::collections::HashMap<String, String>>,
35
36    /// 格式化配置
37    pub formatter: Option<serde_json::Value>,
38
39    ///  lint 配置
40    pub lint: Option<serde_json::Value>,
41}
42
43/// 编译配置
44#[derive(Debug, Clone, Serialize, Deserialize, Default)]
45pub struct BuildConfig {
46    /// 输出目录
47    pub out_dir: Option<PathBuf>,
48
49    /// 是否启用生产模式
50    pub prod: Option<bool>,
51
52    /// 是否启用源码映射
53    pub sourcemap: Option<bool>,
54
55    /// 目标浏览器配置
56    pub browserslist: Option<Vec<String>>,
57
58    /// 构建目标
59    pub targets: Option<Vec<String>>,
60}
61
62/// 开发服务器配置
63#[derive(Debug, Clone, Serialize, Deserialize, Default)]
64pub struct DevConfig {
65    /// 开发服务器端口
66    pub port: Option<u16>,
67
68    /// 开发服务器主机
69    pub host: Option<String>,
70
71    /// 是否启用热更新
72    pub hot: Option<bool>,
73
74    /// 代理配置
75    pub proxy: Option<std::collections::HashMap<String, String>>,
76}
77
78/// 插件配置
79#[derive(Debug, Clone, Serialize, Deserialize, Default)]
80pub struct PluginConfig {
81    /// 插件名称
82    pub name: String,
83
84    /// 插件选项
85    pub options: Option<serde_json::Value>,
86}
87
88/// 配置加载器
89///
90/// 负责从文件系统加载和解析 Nargo 配置文件。
91pub struct ConfigLoader {
92    /// 配置文件路径
93    pub config_path: PathBuf,
94}
95
96impl Default for ConfigLoader {
97    fn default() -> Self {
98        Self { config_path: PathBuf::from(DEFAULT_CONFIG_FILE) }
99    }
100}
101
102impl ConfigLoader {
103    /// 创建一个新的配置加载器
104    ///
105    /// # Arguments
106    ///
107    /// * `config_path` - 配置文件路径
108    ///
109    /// # Returns
110    ///
111    /// 配置加载器实例
112    pub fn new(config_path: PathBuf) -> Self {
113        Self { config_path }
114    }
115
116    /// 加载配置文件
117    ///
118    /// # Returns
119    ///
120    /// 配置结果
121    pub fn load(&self) -> Result<NargoConfig> {
122        use std::fs;
123
124        let extension = self.config_path.extension().unwrap_or_default().to_string_lossy().to_lowercase();
125        match extension.as_str() {
126            "toml" => {
127                let content = fs::read_to_string(&self.config_path).map_err(nargo_types::Error::io_error)?;
128                let config: NargoConfig = toml::from_str(&content).map_err(|e| nargo_types::Error::external_error("config".to_string(), format!("Invalid TOML config: {}", e), nargo_types::Span::default()))?;
129                Ok(config)
130            }
131            "json" => {
132                let content = fs::read_to_string(&self.config_path).map_err(nargo_types::Error::io_error)?;
133                let config: NargoConfig = serde_json::from_str(&content).map_err(|e| nargo_types::Error::external_error("config".to_string(), format!("Invalid JSON config: {}", e), nargo_types::Span::default()))?;
134                Ok(config)
135            }
136            _ => Err(nargo_types::Error::external_error("config".to_string(), format!("Unsupported config file extension: {}", extension), nargo_types::Span::default())),
137        }
138    }
139
140    /// 保存配置到文件
141    ///
142    /// # Arguments
143    ///
144    /// * `config` - 配置对象
145    ///
146    /// # Returns
147    ///
148    /// 保存结果
149    pub fn save(&self, config: &NargoConfig) -> Result<()> {
150        // 实际实现将根据文件扩展名选择相应的序列化器
151        Ok(())
152    }
153
154    /// 查找配置文件
155    ///
156    /// 在指定目录及其父目录中查找配置文件。
157    ///
158    /// # Arguments
159    ///
160    /// * `start_dir` - 开始查找的目录
161    ///
162    /// # Returns
163    ///
164    /// 找到的配置文件路径,或 None
165    pub fn find_config_file(start_dir: &PathBuf) -> Option<PathBuf> {
166        let mut current_dir = start_dir.clone();
167
168        loop {
169            let config_path = current_dir.join(DEFAULT_CONFIG_FILE);
170            if config_path.exists() {
171                return Some(config_path);
172            }
173
174            if !current_dir.pop() {
175                break;
176            }
177        }
178
179        None
180    }
181}
182
183pub mod types;
184pub use types::Dependency;
185
186/// Nargo 项目配置文件结构
187///
188/// 用于管理 Nargo 项目的依赖、脚本、注册表等配置。
189#[derive(Debug, Clone, Serialize, Deserialize, Default)]
190pub struct NargoToml {
191    /// 包配置
192    pub package: crate::types::PackageConfig,
193    /// 依赖项
194    pub dependencies: std::collections::HashMap<String, crate::types::Dependency>,
195    /// 开发依赖项
196    pub dev_dependencies: std::collections::HashMap<String, crate::types::Dependency>,
197    /// 构建依赖项
198    pub build_dependencies: std::collections::HashMap<String, crate::types::Dependency>,
199    /// 工作区配置
200    pub workspace: Option<crate::types::WorkspaceConfig>,
201    /// 特性定义
202    pub features: std::collections::HashMap<String, Vec<String>>,
203    /// 配置文件
204    pub profile: crate::types::ProfileConfig,
205    /// 目标配置
206    pub target: std::collections::HashMap<String, crate::types::TargetConfig>,
207    /// 脚本配置
208    pub scripts: std::collections::HashMap<String, crate::types::ScriptConfig>,
209    /// 注册表配置
210    pub registries: std::collections::HashMap<String, crate::types::RegistryEntry>,
211    /// 安全配置
212    pub security: crate::types::SecurityConfig,
213    ///  lint 配置
214    pub lint: crate::types::LintConfig,
215    /// 格式化配置
216    pub format: crate::types::FormatConfig,
217}
218
219impl NargoToml {
220    /// 验证配置的有效性
221    pub fn validate(&self) -> nargo_types::Result<()> {
222        // 实现验证逻辑
223        Ok(())
224    }
225
226    /// 获取依赖项
227    pub fn get_dependency(&self, name: &str) -> Option<&crate::types::Dependency> {
228        self.dependencies.get(name)
229    }
230}
231
232/// 核心 API 的统一导出
233pub mod prelude {
234    pub use crate::{types::*, BuildConfig, ConfigLoader, DevConfig, NargoConfig, NargoToml, PluginConfig, CONFIG_EXTENSIONS, DEFAULT_CONFIG_FILE};
235}