knife-util 0.2.0

一个为 knife 项目提供通用工具和功能的 Rust 库
Documentation
# knife-util


[![Crates.io](https://img.shields.io/crates/v/knife-util.svg)](https://crates.io/crates/knife-util)
[![Documentation](https://docs.rs/knife-util/badge.svg)](https://docs.rs/knife-util)
[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE)

一个为 knife 项目提供通用工具和功能的 Rust 库,专注于 JSON 数据处理、路径管理和配置转换。

## 功能特性


### 🔧 错误处理

- **统一错误类型**:提供 `AppError` 统一错误处理机制
- **错误链追踪**:支持错误源追踪和堆栈信息
- **上下文信息**:可添加自定义错误上下文
- **自动转换**:支持与 `std::io::Error` 等标准错误类型互转

### 🔄 JSON 合并

- **深度合并**:支持嵌套对象的递归合并
- **类型转换**:自动处理字符串、数字、布尔值之间的转换
- **覆盖机制**:支持 `_override_` 字段强制覆盖
- **数组拼接**:智能合并数组内容
- **Trait 支持**:为基本类型和集合类型提供合并 trait

### 📁 路径工具

- **智能检测**:自动识别开发/生产环境
- **工作目录**:根据环境自动获取正确的工作目录
- **路径构建**:基于工作目录构建相对路径

### ⚙️ TOML 工具

- **双向转换**:TOML 与 JSON 之间的无缝转换
- **文件支持**:直接读取 TOML 文件并转换为 JSON
- **类型保持**:保持数据类型的完整性

## 快速开始


### 安装


在 `Cargo.toml` 中添加依赖:

```toml
[dependencies]
knife-util = "0.2.0"
```

### 使用示例


#### JSON 合并


```rust
use knife_util::{AppError, merge_json};
use serde_json::json;

fn main() -> Result<(), AppError> {
    let target = json!({
        "user": {"name": "Alice", "age": 30},
        "settings": {"theme": "light"}
    });
    
    let source = json!({
        "user": {"email": "alice@example.com"},
        "settings": {"language": "en"}
    });
    
    let merged = merge_json(&target, &source)?;
    println!("合并结果: {}", serde_json::to_string_pretty(&merged).unwrap());
    Ok(())
}
```

#### 使用覆盖机制


```rust
use knife_util::merge_json;
use serde_json::json;

let target = json!({"age": 25});
let source = json!({
    "age": 30,
    "age._override_": 35  // 强制覆盖为 35
});

let result = merge_json(&target, &source).unwrap();
assert_eq!(result["age"], 35);
```

#### 路径工具


```rust
use knife_util::{AppError, get_work_dir, build_work_path, is_dev_mode};

fn main() -> Result<(), AppError> {
    // 获取工作目录
    let work_dir = get_work_dir()?;
    println!("工作目录: {:?}", work_dir);
    
    // 检查环境
    if is_dev_mode() {
        println!("当前在开发模式");
    }
    
    // 构建配置文件路径
    let config_path = build_work_path("config/app.toml")?;
    println!("配置文件路径: {:?}", config_path);
    
    Ok(())
}
```

#### TOML 转换


```rust
use knife_util::{AppError, toml_to_json, json_to_toml};
use serde_json::json;

fn main() -> Result<(), AppError> {
    // TOML 到 JSON
    let toml_str = r#"
        title = "My App"
        [database]
        host = "localhost"
        port = 5432
    "#;
    
    let json_value = toml_to_json(toml_str)?;
    println!("JSON: {}", serde_json::to_string_pretty(&json_value).unwrap());
    
    // JSON 到 TOML
    let json_data = json!({
        "app": {"name": "MyApp", "version": "1.0.0"},
        "database": {"host": "localhost", "port": 5432}
    });
    
    let toml_str = json_to_toml(&json_data)?;
    println!("TOML:\n{}", toml_str);
    
    Ok(())
}
```

#### 错误处理


```rust
use knife_util::AppError;
use std::fs;

fn read_config() -> Result<String, AppError> {
    let content = fs::read_to_string("config.toml")?; // 自动转换为 AppError
    Ok(content)
}

fn main() -> Result<(), AppError> {
    match read_config() {
        Ok(content) => println!("配置内容: {}", content),
        Err(e) => {
            println!("错误: {}", e);
            if let Some(detail) = e.message_detail() {
                println!("详细信息: {}", detail);
            }
        }
    }
    Ok(())
}
```

## API 文档


### 核心 Trait


- `MergeJsonTrait`: JSON 数据合并 trait
- `MergeFromTrait`: 同类型对象合并 trait

### 主要函数


#### JSON 合并

- `merge_json(target, source)`: 深度合并两个 JSON 值

#### 路径工具

- `get_work_dir()`: 获取工作目录
- `is_dev_mode()`: 检查是否为开发模式
- `build_work_path(path)`: 构建工作路径

#### TOML 工具

- `toml_to_json(toml_str)`: TOML 字符串转 JSON
- `toml_file_to_json(file_path)`: TOML 文件转 JSON
- `json_to_toml(json_value)`: JSON 转 TOML 字符串

#### 错误处理

- `AppError::new(code, message)`: 创建新错误
- `AppError::from_error(code, message, err)`: 从其他错误创建
- `AppError::with_attribute(key, value)`: 添加上下文信息

## 开发环境


### 环境要求

- Rust 1.70+
- Cargo

### 运行测试


```bash
cargo test
```

### 生成文档


```bash
cargo doc --open
```

## 许可证


本项目采用 Apache-2.0 许可证。详见 [LICENSE](LICENSE) 文件。

## 贡献


欢迎提交 Issue 和 Pull Request!

## 更新日志


详见 [CHANGELOG.md](CHANGELOG.md)