office-rs 0.1.1

A Rust library for reading and writing XML Office files
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
use quick_xml::Error as XmlError;
use serde_json::Error as JsonError;
use std::collections::HashMap;
use std::error::Error;
use std::io;
use std::sync::atomic::{ AtomicU64, Ordering };
use std::sync::{ Mutex, OnceLock };
use std::time::{ SystemTime, UNIX_EPOCH };
use thiserror::Error;
use zip::result::ZipError;

/// 错误严重程度
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorSeverity {
    /// 警告,可以继续处理
    Warning,
    /// 错误,需要处理但不致命
    Error,
    /// 致命错误,必须停止
    Fatal,
}

/// 错误分类
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorCategory {
    /// 文件系统相关
    FileSystem,
    /// 网络相关
    Network,
    /// 解析相关
    Parsing,
    /// 验证相关
    Validation,
    /// 内部错误
    Internal,
}

/// 错误上下文信息
#[derive(Debug, Clone, Default)]
pub struct ErrorContext {
    pub file_path: Option<String>,
    pub line_number: Option<u32>,
    pub element_path: Option<String>,
    pub operation: Option<String>,
}

/// 错误码,便于程序化处理
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ErrorCode {
    // 文件系统错误 (1000-1999)
    FileNotFound = 1001,
    FilePermissionDenied = 1002,
    FileCorrupted = 1003,
    FileInvalidFormat = 1004,

    // IO错误 (1100-1199)
    IoError = 1100,
    ZipError = 1101,

    // 解析错误 (2000-2999)
    XmlParseError = 2001,
    JsonParseError = 2002,
    EncodingError = 2003,
    MissingElement = 2004,
    InvalidAttribute = 2005,
    UnsupportedVersion = 2006,
    InvalidNamespace = 2007,

    // Excel错误 (3000-3999)
    XlsxWorksheetNotFound = 3001,
    XlsxInvalidCellReference = 3002,
    XlsxInvalidFormula = 3003,
    XlsxInvalidStyleId = 3004,
    XlsxSharedStringIndexOutOfRange = 3005,

    // Word错误 (4000-4999)
    DocxStyleNotFound = 4001,
    DocxInvalidTableStructure = 4002,
    DocxInvalidParagraphFormat = 4003,
    DocxBookmarkNotFound = 4004,

    // PowerPoint错误 (5000-5999)
    PptxSlideNotFound = 5001,
    PptxLayoutNotFound = 5002,
    PptxInvalidShapeId = 5003,
    PptxInvalidAnimation = 5004,

    // 通用错误 (9000-9999)
    FormatError = 9001,
    UnsupportedFormat = 9002,
    StructureError = 9003,
    OtherError = 9999,

    // 通用分类错误码
    FileError = 1000,
    ParseError = 2000,
    XlsxError = 3000,
    DocxError = 4000,
    PptxError = 5000,
}

/// 错误恢复建议
#[derive(Debug, Clone)]
pub struct RecoverySuggestion {
    pub message: String,
    pub action: RecoveryAction,
}

#[derive(Debug, Clone)]
pub enum RecoveryAction {
    /// 重试操作
    Retry,
    /// 使用默认值
    UseDefault,
    /// 跳过当前元素
    SkipElement,
    /// 需要用户输入
    UserInput(String),
    /// 无法恢复
    None,
}

/// 带上下文的文档错误类型
#[derive(Error, Debug)]
pub enum OfficeError {
    /// IO错误
    #[error("IO错误: {0}")]
    Io(#[from] io::Error),

    /// ZIP文件错误
    #[error("ZIP文件错误: {0}")]
    Zip(#[from] ZipError),

    /// XML解析错误
    #[error("XML解析错误: {0}")]
    Xml(#[from] XmlError),

    /// JSON序列化错误
    #[error("JSON错误: {0}")]
    Json(#[from] JsonError),

    /// 编码错误
    #[error("编码错误: {0}")]
    Encoding(#[from] std::string::FromUtf8Error),

    /// 文件相关错误
    #[error("文件错误: {0}")]
    File(#[from] FileError),

    /// 解析相关错误
    #[error("解析错误: {0}")]
    Parse(#[from] ParseError),

    /// Excel特定错误
    #[error("Excel错误: {0}")]
    Xlsx(#[from] XlsxError),

    /// Word特定错误
    #[error("Word错误: {0}")]
    Docx(#[from] DocxError),

    /// PowerPoint特定错误
    #[error("PowerPoint错误: {0}")]
    Pptx(#[from] PptxError),

    /// 格式错误
    #[error("格式错误: {0}")]
    Format(String),

    /// 不支持的文件类型
    #[error("不支持的文件类型: {0}")]
    UnsupportedFormat(String),

    /// 文档结构错误
    #[error("文档结构错误: {0}")]
    Structure(String),

    /// 其他错误
    #[error("其他错误: {0}")]
    Other(String),

    /// 带上下文的错误
    #[error("{error}\n上下文: {context:?}")]
    WithContext {
        error: Box<OfficeError>,
        context: ErrorContext,
    },
}

/// 文件相关错误
#[derive(Error, Debug)]
pub enum FileError {
    #[error("文件不存在: {path}")] NotFound {
        path: String,
    },

    #[error("文件权限不足: {path}")] PermissionDenied {
        path: String,
    },

    #[error("文件已损坏: {path}")] Corrupted {
        path: String,
    },

    #[error("文件格式不正确: {path}")] InvalidFormat {
        path: String,
    },
}

/// 解析相关错误
#[derive(Error, Debug)]
pub enum ParseError {
    #[error("缺少必需元素: {element}")] MissingElement {
        element: String,
    },

    #[error("无效的属性值: {attribute}={value}")] InvalidAttribute {
        attribute: String,
        value: String,
    },

    #[error("不支持的版本: {version}")] UnsupportedVersion {
        version: String,
    },

    #[error("无效的命名空间: {namespace}")] InvalidNamespace {
        namespace: String,
    },
}

/// Excel特定错误
#[derive(Error, Debug)]
pub enum XlsxError {
    #[error("工作表不存在: {name}")] WorksheetNotFound {
        name: String,
    },

    #[error("单元格引用无效: {reference}")] InvalidCellReference {
        reference: String,
    },

    #[error("公式语法错误: {formula}")] InvalidFormula {
        formula: String,
    },

    #[error("样式ID无效: {style_id}")] InvalidStyleId {
        style_id: String,
    },

    #[error("共享字符串索引超出范围: {index}")] SharedStringIndexOutOfRange {
        index: usize,
    },

    #[error("工作表创建失败: {name}")] WorksheetCreationFailed {
        name: String,
    },
}

/// Word特定错误
#[derive(Error, Debug)]
pub enum DocxError {
    #[error("样式不存在: {style_id}")] StyleNotFound {
        style_id: String,
    },

    #[error("表格结构无效")]
    InvalidTableStructure,

    #[error("段落格式错误: {reason}")] InvalidParagraphFormat {
        reason: String,
    },

    #[error("书签不存在: {bookmark}")] BookmarkNotFound {
        bookmark: String,
    },
}

/// PowerPoint特定错误
#[derive(Error, Debug)]
pub enum PptxError {
    #[error("幻灯片不存在: {slide_id}")] SlideNotFound {
        slide_id: String,
    },

    #[error("布局不存在: {layout_id}")] LayoutNotFound {
        layout_id: String,
    },

    #[error("形状ID无效: {shape_id}")] InvalidShapeId {
        shape_id: String,
    },

    #[error("动画配置错误: {reason}")] InvalidAnimation {
        reason: String,
    },
}

impl OfficeError {
    /// 创建带上下文的文件未找到错误
    pub fn file_not_found_with_context(path: String, context: ErrorContext) -> Self {
        Self::File(FileError::NotFound { path }).with_context(context)
    }

    /// 创建带上下文的解析错误
    pub fn parse_error_with_context(element: String, context: ErrorContext) -> Self {
        Self::Parse(ParseError::MissingElement { element }).with_context(context)
    }

    /// 创建带上下文的Excel错误
    pub fn xlsx_error_with_context(name: String, context: ErrorContext) -> Self {
        Self::Xlsx(XlsxError::WorksheetNotFound { name }).with_context(context)
    }

    /// 记录错误到监控器
    pub fn record(&self) -> &Self {
        error_monitor().record_error(self);
        self
    }

    /// 创建错误并自动记录
    pub fn new_and_record(error: OfficeError) -> Self {
        error_monitor().record_error(&error);
        error
    }
    /// 获取错误严重程度
    pub fn severity(&self) -> ErrorSeverity {
        match self {
            Self::Io(_) => ErrorSeverity::Fatal,
            Self::Zip(_) => ErrorSeverity::Fatal,
            Self::Xml(_) => ErrorSeverity::Error,
            Self::Json(_) => ErrorSeverity::Error,
            Self::Encoding(_) => ErrorSeverity::Error,
            Self::File(FileError::NotFound { .. }) => ErrorSeverity::Fatal,
            Self::File(FileError::PermissionDenied { .. }) => ErrorSeverity::Fatal,
            Self::File(FileError::Corrupted { .. }) => ErrorSeverity::Fatal,
            Self::File(FileError::InvalidFormat { .. }) => ErrorSeverity::Error,
            Self::Parse(_) => ErrorSeverity::Error,
            Self::Xlsx(_) => ErrorSeverity::Error,
            Self::Docx(_) => ErrorSeverity::Error,
            Self::Pptx(_) => ErrorSeverity::Error,
            Self::Format(_) => ErrorSeverity::Error,
            Self::UnsupportedFormat(_) => ErrorSeverity::Fatal,
            Self::Structure(_) => ErrorSeverity::Warning,
            Self::Other(_) => ErrorSeverity::Error,
            Self::WithContext { error, .. } => error.severity(),
        }
    }

    /// 获取错误分类
    pub fn category(&self) -> ErrorCategory {
        match self {
            Self::Io(_) | Self::File(_) => ErrorCategory::FileSystem,
            Self::Zip(_) => ErrorCategory::FileSystem,
            Self::Xml(_) | Self::Json(_) | Self::Encoding(_) => ErrorCategory::Parsing,
            Self::Parse(_) => ErrorCategory::Parsing,
            Self::Xlsx(_) | Self::Docx(_) | Self::Pptx(_) => ErrorCategory::Validation,
            Self::Format(_) | Self::Structure(_) => ErrorCategory::Validation,
            Self::UnsupportedFormat(_) => ErrorCategory::Parsing,
            Self::Other(_) => ErrorCategory::Internal,
            Self::WithContext { error, .. } => error.category(),
        }
    }

    /// 获取错误码
    pub fn error_code(&self) -> ErrorCode {
        match self {
            Self::Io(_) => ErrorCode::IoError,
            Self::Zip(_) => ErrorCode::ZipError,
            Self::Xml(_) => ErrorCode::XmlParseError,
            Self::Json(_) => ErrorCode::JsonParseError,
            Self::Encoding(_) => ErrorCode::EncodingError,
            Self::File(FileError::NotFound { .. }) => ErrorCode::FileNotFound,
            Self::File(FileError::PermissionDenied { .. }) => ErrorCode::FilePermissionDenied,
            Self::File(FileError::Corrupted { .. }) => ErrorCode::FileCorrupted,
            Self::File(FileError::InvalidFormat { .. }) => ErrorCode::FileInvalidFormat,
            Self::Parse(ParseError::MissingElement { .. }) => ErrorCode::MissingElement,
            Self::Parse(ParseError::InvalidAttribute { .. }) => ErrorCode::InvalidAttribute,
            Self::Parse(ParseError::UnsupportedVersion { .. }) => ErrorCode::UnsupportedVersion,
            Self::Parse(ParseError::InvalidNamespace { .. }) => ErrorCode::InvalidNamespace,
            Self::Xlsx(XlsxError::WorksheetNotFound { .. }) => ErrorCode::XlsxWorksheetNotFound,
            Self::Xlsx(XlsxError::InvalidCellReference { .. }) => {
                ErrorCode::XlsxInvalidCellReference
            }
            Self::Xlsx(XlsxError::InvalidFormula { .. }) => ErrorCode::XlsxInvalidFormula,
            Self::Xlsx(XlsxError::InvalidStyleId { .. }) => ErrorCode::XlsxInvalidStyleId,
            Self::Xlsx(XlsxError::SharedStringIndexOutOfRange { .. }) => {
                ErrorCode::XlsxSharedStringIndexOutOfRange
            }
            Self::Xlsx(XlsxError::WorksheetCreationFailed { .. }) => ErrorCode::XlsxError,
            Self::Docx(DocxError::StyleNotFound { .. }) => ErrorCode::DocxStyleNotFound,
            Self::Docx(DocxError::InvalidTableStructure) => ErrorCode::DocxInvalidTableStructure,
            Self::Docx(DocxError::InvalidParagraphFormat { .. }) => {
                ErrorCode::DocxInvalidParagraphFormat
            }
            Self::Docx(DocxError::BookmarkNotFound { .. }) => ErrorCode::DocxBookmarkNotFound,
            Self::Pptx(PptxError::SlideNotFound { .. }) => ErrorCode::PptxSlideNotFound,
            Self::Pptx(PptxError::LayoutNotFound { .. }) => ErrorCode::PptxLayoutNotFound,
            Self::Pptx(PptxError::InvalidShapeId { .. }) => ErrorCode::PptxInvalidShapeId,
            Self::Pptx(PptxError::InvalidAnimation { .. }) => ErrorCode::PptxInvalidAnimation,
            Self::Format(_) => ErrorCode::FormatError,
            Self::UnsupportedFormat(_) => ErrorCode::UnsupportedFormat,
            Self::Structure(_) => ErrorCode::StructureError,
            Self::Other(_) => ErrorCode::OtherError,
            Self::WithContext { error, .. } => error.error_code(),
        }
    }

    /// 判断错误是否可恢复
    pub fn is_recoverable(&self) -> bool {
        matches!(self.severity(), ErrorSeverity::Warning | ErrorSeverity::Error)
    }

    /// 添加错误上下文
    pub fn with_context(self, context: ErrorContext) -> Self {
        let error_with_context = Self::WithContext {
            error: Box::new(self),
            context,
        };
        // 记录带上下文的错误
        error_monitor().record_error(&error_with_context);
        error_with_context
    }

    /// 获取错误上下文
    pub fn context(&self) -> Option<&ErrorContext> {
        match self {
            Self::WithContext { context, .. } => Some(context),
            _ => None,
        }
    }

    /// 获取根错误(去除上下文包装)
    pub fn root_error(&self) -> &OfficeError {
        match self {
            Self::WithContext { error, .. } => error.root_error(),
            _ => self,
        }
    }

    /// 获取错误恢复建议
    pub fn recovery_suggestion(&self) -> Option<RecoverySuggestion> {
        match self.root_error() {
            Self::File(FileError::NotFound { path }) =>
                Some(RecoverySuggestion {
                    message: format!("检查文件路径是否正确: {}", path),
                    action: RecoveryAction::UserInput("请提供正确的文件路径".to_string()),
                }),
            Self::File(FileError::PermissionDenied { path }) =>
                Some(RecoverySuggestion {
                    message: format!("检查文件权限: {}", path),
                    action: RecoveryAction::UserInput("请确保有足够的文件访问权限".to_string()),
                }),
            Self::Xlsx(XlsxError::WorksheetNotFound { name }) =>
                Some(RecoverySuggestion {
                    message: format!("工作表 '{}' 不存在,可以使用默认工作表", name),
                    action: RecoveryAction::UseDefault,
                }),
            Self::Xlsx(XlsxError::InvalidCellReference { reference }) =>
                Some(RecoverySuggestion {
                    message: format!("单元格引用 '{}' 无效,跳过此单元格", reference),
                    action: RecoveryAction::SkipElement,
                }),
            Self::Docx(DocxError::StyleNotFound { style_id }) =>
                Some(RecoverySuggestion {
                    message: format!("样式 '{}' 不存在,使用默认样式", style_id),
                    action: RecoveryAction::UseDefault,
                }),
            Self::Pptx(PptxError::SlideNotFound { slide_id }) =>
                Some(RecoverySuggestion {
                    message: format!("幻灯片 '{}' 不存在,跳过此幻灯片", slide_id),
                    action: RecoveryAction::SkipElement,
                }),
            Self::Structure(_) =>
                Some(RecoverySuggestion {
                    message: "文档结构异常,但可以继续处理".to_string(),
                    action: RecoveryAction::SkipElement,
                }),
            Self::Io(_) | Self::Zip(_) | Self::UnsupportedFormat(_) =>
                Some(RecoverySuggestion {
                    message: "致命错误,无法恢复".to_string(),
                    action: RecoveryAction::None,
                }),
            _ =>
                Some(RecoverySuggestion {
                    message: "可以重试操作".to_string(),
                    action: RecoveryAction::Retry,
                }),
        }
    }

    /// 获取错误链
    pub fn error_chain(&self) -> Vec<&dyn std::error::Error> {
        let mut chain = vec![self as &dyn std::error::Error];
        let mut source = self.source();
        while let Some(err) = source {
            chain.push(err);
            source = err.source();
        }
        chain
    }

    /// 获取根因错误
    pub fn root_cause(&self) -> &dyn std::error::Error {
        self.error_chain().into_iter().last().unwrap()
    }
}

/// 错误统计信息
#[derive(Debug, Clone)]
pub struct ErrorStats {
    pub error_code: ErrorCode,
    pub count: u64,
    pub first_occurrence: u64, // Unix timestamp
    pub last_occurrence: u64, // Unix timestamp
    pub severity: ErrorSeverity,
    pub category: ErrorCategory,
}

/// 错误监控器
#[derive(Debug)]
pub struct ErrorMonitor {
    stats: Mutex<HashMap<ErrorCode, ErrorStats>>,
    total_errors: AtomicU64,
}

impl ErrorMonitor {
    pub fn new() -> Self {
        Self {
            stats: Mutex::new(HashMap::new()),
            total_errors: AtomicU64::new(0),
        }
    }

    /// 记录错误
    pub fn record_error(&self, error: &OfficeError) {
        let error_code = error.error_code();
        let severity = error.severity();
        let category = error.category();
        let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();

        self.total_errors.fetch_add(1, Ordering::Relaxed);

        let mut stats = self.stats.lock().unwrap();
        let entry = stats.entry(error_code).or_insert(ErrorStats {
            error_code,
            count: 0,
            first_occurrence: now,
            last_occurrence: now,
            severity,
            category,
        });

        entry.count += 1;
        entry.last_occurrence = now;
    }

    /// 获取错误统计
    pub fn get_stats(&self) -> Vec<ErrorStats> {
        let stats = self.stats.lock().unwrap();
        stats.values().cloned().collect()
    }

    /// 获取总错误数
    pub fn total_errors(&self) -> u64 {
        self.total_errors.load(Ordering::Relaxed)
    }

    /// 获取最常见的错误
    pub fn most_common_errors(&self, limit: usize) -> Vec<ErrorStats> {
        let mut stats = self.get_stats();
        stats.sort_by(|a, b| b.count.cmp(&a.count));
        stats.into_iter().take(limit).collect()
    }

    /// 清除统计信息
    pub fn clear_stats(&self) {
        let mut stats = self.stats.lock().unwrap();
        stats.clear();
        self.total_errors.store(0, Ordering::Relaxed);
    }
}

/// 全局错误监控器
static ERROR_MONITOR: OnceLock<ErrorMonitor> = OnceLock::new();

/// 获取全局错误监控器
pub fn error_monitor() -> &'static ErrorMonitor {
    ERROR_MONITOR.get_or_init(|| ErrorMonitor::new())
}

/// 简化的结果类型
pub type Result<T> = std::result::Result<T, OfficeError>;