1#![forbid(unsafe_code)]
6#![cfg_attr(
10 test,
11 allow(
12 clippy::expect_used,
13 clippy::unwrap_used,
14 clippy::indexing_slicing,
15 clippy::useless_format,
16 clippy::clone_on_copy,
17 reason = "Tests legitimately need to unwrap fixture data and index into known-shape \
18 collections"
19 )
20)]
21
22use std::path::{Path, PathBuf};
23
24use thiserror::Error;
25
26pub mod auth;
27pub mod auth_checker;
28pub mod cleanup;
29pub mod cli_error;
30pub mod commit;
31pub mod compatibility;
32pub mod git_ops;
33pub mod issue;
34pub mod label;
35pub mod output;
36pub mod pipeline;
37pub mod platform;
38pub mod pr;
39pub mod release;
40pub mod review;
41pub mod toon;
42pub mod types;
43
44pub use auth_checker::{AuthCheckResult, AuthChecker};
46pub use cli_error::PlatformCliError;
47pub use compatibility::{PlatformCompat, platform_compatibility, platform_requirement};
48pub use output::{CliError, CliOutput};
49
50#[allow(
55 clippy::module_name_repetitions,
56 reason = "Avoids collision with std::error::Error and thiserror::Error"
57)]
58#[derive(Debug, Error)]
59#[non_exhaustive]
60pub enum CoreError {
61 #[error("io error: {0}")]
63 Io(#[from] std::io::Error),
64
65 #[error("serialization error: {0}")]
67 Serialization(#[from] serde_json::Error),
68
69 #[error("application error: {0}")]
72 App(String),
73
74 #[error("path error: {0}")]
76 Path(#[from] PathError),
77
78 #[error("platform error: {0}")]
80 Platform(String),
81
82 #[error(transparent)]
86 Cli(#[from] Box<PlatformCliError>),
87}
88
89impl From<PlatformCliError> for CoreError {
94 fn from(err: PlatformCliError) -> Self {
95 Self::Cli(Box::new(err))
96 }
97}
98
99pub type Result<T> = std::result::Result<T, CoreError>;
101
102pub use auth::AuthStatus;
104pub use commit::{CommitData, CommitDetail, CommitFile};
105pub use label::{CreateLabelArgs, CreateMilestoneArgs, LabelData, MilestoneData};
106pub use release::{CreateReleaseArgs, ReleaseData};
107pub use review::{ReviewCommentData, ReviewData, ReviewState};
108pub use types::{CommentData, MergeResult, MergeStrategy};
109
110#[derive(Debug, Clone)]
115#[non_exhaustive]
116pub struct Config {
117 name: String,
118 description: Option<String>,
119}
120
121impl Config {
122 #[must_use]
124 pub fn name(&self) -> &str {
125 &self.name
126 }
127
128 #[must_use]
130 pub fn description(&self) -> Option<&str> {
131 self.description.as_deref()
132 }
133
134 pub fn new(name: impl Into<String>) -> Result<Self> {
148 let name = name.into();
149 if name.is_empty() {
150 return Err(CoreError::App("config name must not be empty".into()));
151 }
152 Ok(Self {
153 name,
154 description: None,
155 })
156 }
157
158 #[must_use]
160 pub fn with_description(mut self, description: impl Into<String>) -> Self {
161 self.description = Some(description.into());
162 self
163 }
164}
165
166#[derive(Debug, Clone)]
168pub struct PathError {
169 pub path: PathBuf,
171 pub kind: PathErrorKind,
173}
174
175impl std::error::Error for PathError {}
176
177#[derive(Debug, Clone)]
179#[non_exhaustive]
180pub enum PathErrorKind {
181 Absolute,
183 ParentDirTraversal,
185 NullByte,
187 DeviceName,
189 InvalidChar {
191 ch: char,
193 },
194 DangerousChar {
196 ch: char,
198 },
199 ComponentTooLong {
201 max_bytes: usize,
203 actual_bytes: usize,
205 },
206}
207
208impl std::fmt::Display for PathError {
209 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
210 match self.kind {
211 PathErrorKind::Absolute => {
212 write!(f, "absolute path not allowed: {}", self.path.display())
213 }
214 PathErrorKind::ParentDirTraversal => {
215 write!(f, "'..' not allowed: {}", self.path.display())
216 }
217 PathErrorKind::NullByte => write!(f, "null byte in path: {}", self.path.display()),
218 PathErrorKind::DeviceName => write!(
219 f,
220 "reserved device name not allowed: {}",
221 self.path.display()
222 ),
223 PathErrorKind::InvalidChar { ch } => write!(
224 f,
225 "invalid character '{ch}' in path: {}",
226 self.path.display()
227 ),
228 PathErrorKind::DangerousChar { ch } => write!(
229 f,
230 "dangerous Unicode character U+{:04X} in path: {}",
231 ch as u32,
232 self.path.display()
233 ),
234 PathErrorKind::ComponentTooLong {
235 max_bytes,
236 actual_bytes,
237 } => {
238 write!(
239 f,
240 "path component too long (max {max_bytes}B, got {actual_bytes}B): {}",
241 self.path.display()
242 )
243 }
244 }
245 }
246}
247
248#[derive(Debug, Clone)]
253pub struct SafePath(PathBuf);
254
255impl SafePath {
256 pub fn new(path: impl AsRef<Path>) -> Result<Self> {
278 const MAX_COMPONENT_LEN: usize = 255;
279 let path = path.as_ref();
280
281 if path.is_absolute() {
283 return Err(PathError {
284 path: path.to_path_buf(),
285 kind: PathErrorKind::Absolute,
286 }
287 .into());
288 }
289
290 if path
292 .components()
293 .any(|c| c == std::path::Component::ParentDir)
294 {
295 return Err(PathError {
296 path: path.to_path_buf(),
297 kind: PathErrorKind::ParentDirTraversal,
298 }
299 .into());
300 }
301
302 if path.as_os_str().as_encoded_bytes().contains(&b'\0') {
304 return Err(PathError {
305 path: path.to_path_buf(),
306 kind: PathErrorKind::NullByte,
307 }
308 .into());
309 }
310
311 if path.as_os_str().as_encoded_bytes().contains(&b':') {
313 return Err(PathError {
314 path: path.to_path_buf(),
315 kind: PathErrorKind::InvalidChar { ch: ':' },
316 }
317 .into());
318 }
319
320 #[cfg(windows)]
322 {
323 if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
324 let upper = stem.to_uppercase();
325 if matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")
326 || (upper.len() == 4
327 && (upper.starts_with("COM") || upper.starts_with("LPT"))
328 && upper[3..].parse::<u8>().is_ok())
329 {
330 return Err(PathError {
331 path: path.to_path_buf(),
332 kind: PathErrorKind::DeviceName,
333 }
334 .into());
335 }
336 }
337 }
338
339 for component in path.components() {
341 let len = component.as_os_str().len();
342 if len > MAX_COMPONENT_LEN {
343 return Err(PathError {
344 path: path.to_path_buf(),
345 kind: PathErrorKind::ComponentTooLong {
346 max_bytes: MAX_COMPONENT_LEN,
347 actual_bytes: len,
348 },
349 }
350 .into());
351 }
352
353 let s = component.as_os_str().to_string_lossy();
354 for ch in s.chars() {
355 if matches!(ch, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') {
356 return Err(PathError {
357 path: path.to_path_buf(),
358 kind: PathErrorKind::DangerousChar { ch },
359 }
360 .into());
361 }
362 }
363 }
364
365 Ok(Self(path.to_path_buf()))
366 }
367
368 #[must_use]
370 pub fn as_path(&self) -> &Path {
371 &self.0
372 }
373}
374
375impl AsRef<Path> for SafePath {
376 fn as_ref(&self) -> &Path {
377 &self.0
378 }
379}
380
381#[cfg(test)]
382mod tests {
383 use super::*;
384
385 #[test]
386 fn test_config_new_with_valid_name() -> Result<()> {
387 let config = Config::new("test")?;
388 assert_eq!(config.name(), "test");
389 assert!(config.description().is_none());
390 Ok(())
391 }
392
393 #[test]
394 fn test_config_new_with_empty_name_errors() {
395 let err = Config::new("");
396 assert!(matches!(err, Err(CoreError::App(_))));
397 }
398
399 #[test]
400 fn test_config_with_description() -> Result<()> {
401 let config = Config::new("test")?.with_description("a test config");
402 assert_eq!(config.description(), Some("a test config"));
403 Ok(())
404 }
405
406 #[test]
407 fn test_io_error_conversion() {
408 let io_err = std::io::Error::other("test");
409 let core_err = CoreError::from(io_err);
410 assert!(matches!(core_err, CoreError::Io(_)));
411 }
412
413 #[test]
414 fn test_serialization_error_conversion() {
415 let io_err = std::io::Error::other("invalid json");
416 let serde_err = serde_json::Error::io(io_err);
417 let core_err = CoreError::from(serde_err);
418 assert!(matches!(core_err, CoreError::Serialization(_)));
419 }
420
421 #[test]
422 fn test_safe_path_accepts_relative() -> Result<()> {
423 let sp = SafePath::new("foo/bar.txt")?;
424 assert_eq!(sp.as_path(), Path::new("foo/bar.txt"));
425 Ok(())
426 }
427
428 #[test]
429 fn test_safe_path_rejects_absolute() {
430 #[cfg(unix)]
431 let absolute_path = "/etc/passwd";
432 #[cfg(windows)]
433 let absolute_path = r"C:\Windows\system32";
434 assert!(matches!(
435 SafePath::new(absolute_path),
436 Err(CoreError::Path(_))
437 ));
438 }
439
440 #[test]
441 fn test_safe_path_rejects_parent_dir() {
442 assert!(matches!(
443 SafePath::new("../secret.txt"),
444 Err(CoreError::Path(_))
445 ));
446 }
447
448 #[test]
449 fn test_safe_path_rejects_null_byte() {
450 assert!(matches!(
451 SafePath::new("foo\0bar.txt"),
452 Err(CoreError::Path(_))
453 ));
454 }
455
456 #[test]
457 fn test_safe_path_rejects_colon() {
458 let err = SafePath::new("foo:bar.txt");
459 assert!(matches!(
460 err,
461 Err(CoreError::Path(PathError {
462 kind: PathErrorKind::InvalidChar { ch: ':' },
463 ..
464 }))
465 ));
466 }
467
468 #[test]
469 fn test_safe_path_rejects_bidi_control_chars() {
470 let path = format!("foo\u{202A}bar.txt");
472 let err = SafePath::new(path);
473 assert!(matches!(
474 err,
475 Err(CoreError::Path(PathError {
476 kind: PathErrorKind::DangerousChar { ch: '\u{202A}' },
477 ..
478 }))
479 ));
480
481 let path = format!("foo\u{2066}bar.txt");
483 let err = SafePath::new(path);
484 assert!(matches!(
485 err,
486 Err(CoreError::Path(PathError {
487 kind: PathErrorKind::DangerousChar { ch: '\u{2066}' },
488 ..
489 }))
490 ));
491 }
492
493 #[test]
494 fn test_safe_path_rejects_component_too_long() {
495 let long_component = "a".repeat(256);
496 let err = SafePath::new(&long_component);
497 assert!(matches!(
498 err,
499 Err(CoreError::Path(PathError {
500 kind: PathErrorKind::ComponentTooLong {
501 max_bytes: 255,
502 actual_bytes: 256
503 },
504 ..
505 }))
506 ));
507 }
508
509 #[test]
510 fn test_safe_path_accepts_max_component() -> Result<()> {
511 let max_component = "a".repeat(255);
512 let sp = SafePath::new(&max_component)?;
513 assert_eq!(sp.as_path().as_os_str().len(), 255);
514 Ok(())
515 }
516
517 #[test]
518 fn test_platform_error_variant() {
519 let err = CoreError::Platform("gh not found".into());
520 assert!(matches!(err, CoreError::Platform(_)));
521 let msg = format!("{err}");
522 assert!(msg.contains("platform error"));
523 assert!(msg.contains("gh not found"));
524 }
525
526 #[test]
527 fn test_cli_error_from_platform_cli_error() {
528 let platform_err = PlatformCliError {
529 user_message: "认证失败".into(),
530 raw_stderr: "raw".into(),
531 hint: None,
532 doc_link: None,
533 code: None,
534 platform: platform::Platform::GitHub,
535 };
536 let core_err: CoreError = platform_err.into();
538 assert!(matches!(core_err, CoreError::Cli(_)));
539 let msg = format!("{core_err}");
541 assert!(msg.contains("认证失败"));
542 }
543}