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