evorule_cli/error.rs
1// SPDX-License-Identifier: AGPL-3.0-or-later
2// Copyright (C) 2026 EvoRule Project
3// This file is part of EvoRule, licensed under GNU Affero General Public License v3 or later.
4//! CLI 错误类型
5//!
6//! 统一的错误枚举,覆盖 I/O、JSON、规则加载、payload 解析、fact log 解析、
7//! TCB 执行、WAL 序列化等场景。所有子命令返回 `Result<(), CliError>`,
8//! main.rs 根据错误类型决定退出码。
9
10use thiserror::Error;
11
12/// CLI 错误
13///
14/// 设计原则:
15/// - 每个变体携带足够上下文(路径、行号、原因),便于用户定位问题
16/// - `#[from]` 自动转换 std::io::Error / serde_json::Error / WalError
17/// - Display 输出人类可读的中文/英文混合消息(与现有 CLI 风格一致)
18#[derive(Debug, Error)]
19pub enum CliError {
20 /// 文件系统 I/O 错误
21 #[error("I/O error: {0}")]
22 Io(#[from] std::io::Error),
23
24 /// JSON 序列化/反序列化错误
25 #[error("JSON error: {0}")]
26 Json(#[from] serde_json::Error),
27
28 /// tier1 WAL 序列化错误(fact_from_json 失败等)
29 #[error("WAL error: {0}")]
30 Wal(#[from] evorule_reactor::WalError),
31
32 /// 规则目录不存在
33 #[error("Rules directory does not exist: {0}")]
34 RulesDirNotFound(String),
35
36 /// 规则目录中无 .json 文件
37 #[error("No .json files found in {0}")]
38 NoRulesFound(String),
39
40 /// 初始 payload JSON 解析失败
41 #[error("Invalid payload JSON: {0}")]
42 InvalidPayload(String),
43
44 /// fact log 解析错误(指定行号和原因)
45 #[error("Fact log parse error at line {line}: {reason}")]
46 FactLogParse {
47 /// 出错的行号(1-based)
48 line: usize,
49 /// 错误原因
50 reason: String,
51 },
52
53 /// 哈希链验证失败
54 #[error("Hash chain verification failed: {0}")]
55 HashChain(String),
56
57 /// 执行完成但产生 Error 事实(规则执行失败)
58 ///
59 ///(C1/C3):执行含 Error fact 时不再返回退出码 0。
60 /// CI/自动化管道以退出码判定成败,Error fact 静默成功会让"确定性执行"
61 /// 的核心承诺在自动化场景下失效。fact log 仍正常写出供审计。
62 #[error(
63 "Execution completed with {count} Error fact(s); fact log written for audit (exit code 3)"
64 )]
65 ExecutionHadErrors {
66 /// Error 事实数量
67 count: usize,
68 },
69
70 /// 通用错误(兜底)
71 #[error("{0}")]
72 Other(String),
73}
74
75impl CliError {
76 /// 从任意字符串创建通用错误
77 ///
78 /// # 示例
79 /// ```
80 /// use evorule_cli::CliError;
81 ///
82 /// let err = CliError::other("something went wrong");
83 /// assert_eq!(err.to_string(), "something went wrong");
84 /// ```
85 pub fn other(msg: impl Into<String>) -> Self {
86 Self::Other(msg.into())
87 }
88}
89
90/// 退出码映射
91///
92/// 约定:
93/// - 0:成功
94/// - 1:通用错误(默认)
95/// - 2:规则加载错误(目录不存在、无 .json)
96/// - 3:执行完成但产生 Error 事实(:不再静默成功)
97impl CliError {
98 /// 返回该错误对应的退出码
99 ///
100 /// # 约定
101 /// - 0:成功
102 /// - 1:通用错误(默认)
103 /// - 2:规则加载错误(目录不存在、无 .json)
104 /// - 3:执行完成但产生 Error 事实()
105 ///
106 /// # 示例
107 /// ```
108 /// use evorule_cli::CliError;
109 ///
110 /// // 规则目录缺失 → 退出码 2
111 /// let dir_err = CliError::RulesDirNotFound("/nonexistent".into());
112 /// assert_eq!(dir_err.exit_code(), 2);
113 ///
114 /// // 执行含 Error fact → 退出码 3
115 /// let exec_err = CliError::ExecutionHadErrors { count: 1 };
116 /// assert_eq!(exec_err.exit_code(), 3);
117 ///
118 /// // 通用错误 → 退出码 1
119 /// assert_eq!(CliError::other("boom").exit_code(), 1);
120 /// ```
121 pub fn exit_code(&self) -> i32 {
122 match self {
123 CliError::RulesDirNotFound(_) | CliError::NoRulesFound(_) => 2,
124 CliError::ExecutionHadErrors { .. } => 3,
125 _ => 1,
126 }
127 }
128}
129
130#[cfg(test)]
131mod tests {
132 #![allow(clippy::unwrap_used)]
133 use super::*;
134
135 #[test]
136 fn test_exit_code_mapping() {
137 assert_eq!(CliError::RulesDirNotFound("x".into()).exit_code(), 2);
138 assert_eq!(CliError::NoRulesFound("x".into()).exit_code(), 2);
139 assert_eq!(CliError::ExecutionHadErrors { count: 1 }.exit_code(), 3);
140 assert_eq!(CliError::Other("x".into()).exit_code(), 1);
141 assert_eq!(
142 CliError::Io(std::io::Error::new(std::io::ErrorKind::NotFound, "x")).exit_code(),
143 1
144 );
145 }
146
147 #[test]
148 fn test_from_io_error() {
149 let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
150 let cli_err: CliError = io_err.into();
151 assert!(matches!(cli_err, CliError::Io(_)));
152 }
153
154 #[test]
155 fn test_display_includes_context() {
156 let err = CliError::FactLogParse {
157 line: 42,
158 reason: "missing type field".into(),
159 };
160 let msg = format!("{}", err);
161 assert!(msg.contains("42"));
162 assert!(msg.contains("missing type field"));
163 }
164}