Skip to main content

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    /// CR-20260902-001(UV-046 C1/C3):执行含 Error fact 时不再返回退出码 0。
60    /// CI/自动化管道以退出码判定成败,Error fact 静默成功会让"确定性执行"
61    /// 的核心承诺在自动化场景下失效。fact log 仍正常写出供审计。
62    #[error("Execution completed with {count} Error fact(s); fact log written for audit (exit code 3)")]
63    ExecutionHadErrors {
64        /// Error 事实数量
65        count: usize,
66    },
67
68    /// 通用错误(兜底)
69    #[error("{0}")]
70    Other(String),
71}
72
73impl CliError {
74    /// 从任意字符串创建通用错误
75    ///
76    /// # 示例
77    /// ```
78    /// use evorule_cli::CliError;
79    ///
80    /// let err = CliError::other("something went wrong");
81    /// assert_eq!(err.to_string(), "something went wrong");
82    /// ```
83    pub fn other(msg: impl Into<String>) -> Self {
84        Self::Other(msg.into())
85    }
86}
87
88/// 退出码映射
89///
90/// 约定:
91/// - 0:成功
92/// - 1:通用错误(默认)
93/// - 2:规则加载错误(目录不存在、无 .json)
94/// - 3:执行完成但产生 Error 事实(CR-20260902-001:不再静默成功)
95impl CliError {
96    /// 返回该错误对应的退出码
97    ///
98    /// # 约定
99    /// - 0:成功
100    /// - 1:通用错误(默认)
101    /// - 2:规则加载错误(目录不存在、无 .json)
102    /// - 3:执行完成但产生 Error 事实(CR-20260902-001)
103    ///
104    /// # 示例
105    /// ```
106    /// use evorule_cli::CliError;
107    ///
108    /// // 规则目录缺失 → 退出码 2
109    /// let dir_err = CliError::RulesDirNotFound("/nonexistent".into());
110    /// assert_eq!(dir_err.exit_code(), 2);
111    ///
112    /// // 执行含 Error fact → 退出码 3
113    /// let exec_err = CliError::ExecutionHadErrors { count: 1 };
114    /// assert_eq!(exec_err.exit_code(), 3);
115    ///
116    /// // 通用错误 → 退出码 1
117    /// assert_eq!(CliError::other("boom").exit_code(), 1);
118    /// ```
119    pub fn exit_code(&self) -> i32 {
120        match self {
121            CliError::RulesDirNotFound(_) | CliError::NoRulesFound(_) => 2,
122            CliError::ExecutionHadErrors { .. } => 3,
123            _ => 1,
124        }
125    }
126}
127
128#[cfg(test)]
129mod tests {
130    #![allow(clippy::unwrap_used)]
131    use super::*;
132
133    #[test]
134    fn test_exit_code_mapping() {
135        assert_eq!(CliError::RulesDirNotFound("x".into()).exit_code(), 2);
136        assert_eq!(CliError::NoRulesFound("x".into()).exit_code(), 2);
137        assert_eq!(CliError::ExecutionHadErrors { count: 1 }.exit_code(), 3);
138        assert_eq!(CliError::Other("x".into()).exit_code(), 1);
139        assert_eq!(
140            CliError::Io(std::io::Error::new(std::io::ErrorKind::NotFound, "x")).exit_code(),
141            1
142        );
143    }
144
145    #[test]
146    fn test_from_io_error() {
147        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file missing");
148        let cli_err: CliError = io_err.into();
149        assert!(matches!(cli_err, CliError::Io(_)));
150    }
151
152    #[test]
153    fn test_display_includes_context() {
154        let err = CliError::FactLogParse {
155            line: 42,
156            reason: "missing type field".into(),
157        };
158        let msg = format!("{}", err);
159        assert!(msg.contains("42"));
160        assert!(msg.contains("missing type field"));
161    }
162}