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