#![forbid(unsafe_code)]
#![cfg_attr(
test,
allow(
clippy::expect_used,
clippy::unwrap_used,
clippy::indexing_slicing,
clippy::useless_format,
clippy::clone_on_copy,
reason = "Tests legitimately need to unwrap fixture data and index into known-shape \
collections"
)
)]
use std::path::{Path, PathBuf};
use thiserror::Error;
pub mod auth;
pub mod auth_checker;
pub mod cli_error;
pub mod commit;
pub mod compatibility;
pub mod issue;
pub mod label;
pub mod output;
pub mod pipeline;
pub mod platform;
pub mod pr;
pub mod release;
pub mod review;
pub mod toon;
pub mod types;
pub use auth_checker::{AuthCheckResult, AuthChecker};
pub use cli_error::PlatformCliError;
pub use compatibility::{PlatformCompat, platform_compatibility, platform_requirement};
pub use output::{CliError, CliOutput};
#[allow(
clippy::module_name_repetitions,
reason = "Avoids collision with std::error::Error and thiserror::Error"
)]
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum CoreError {
#[error("io error: {0}")]
Io(#[from] std::io::Error),
#[error("serialization error: {0}")]
Serialization(#[from] serde_json::Error),
#[error("application error: {0}")]
App(String),
#[error("path error: {0}")]
Path(#[from] PathError),
#[error("platform error: {0}")]
Platform(String),
#[error(transparent)]
Cli(#[from] Box<PlatformCliError>),
}
impl From<PlatformCliError> for CoreError {
fn from(err: PlatformCliError) -> Self {
Self::Cli(Box::new(err))
}
}
pub type Result<T> = std::result::Result<T, CoreError>;
pub use auth::AuthStatus;
pub use commit::{CommitData, CommitDetail, CommitFile};
pub use label::{CreateLabelArgs, CreateMilestoneArgs, LabelData, MilestoneData};
pub use release::{CreateReleaseArgs, ReleaseData};
pub use review::{ReviewCommentData, ReviewData, ReviewState};
pub use types::{CommentData, MergeResult, MergeStrategy};
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Config {
name: String,
description: Option<String>,
}
impl Config {
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn description(&self) -> Option<&str> {
self.description.as_deref()
}
pub fn new(name: impl Into<String>) -> Result<Self> {
let name = name.into();
if name.is_empty() {
return Err(CoreError::App("config name must not be empty".into()));
}
Ok(Self {
name,
description: None,
})
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
}
#[derive(Debug, Clone)]
pub struct PathError {
pub path: PathBuf,
pub kind: PathErrorKind,
}
impl std::error::Error for PathError {}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum PathErrorKind {
Absolute,
ParentDirTraversal,
NullByte,
DeviceName,
InvalidChar {
ch: char,
},
DangerousChar {
ch: char,
},
ComponentTooLong {
max_bytes: usize,
actual_bytes: usize,
},
}
impl std::fmt::Display for PathError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.kind {
PathErrorKind::Absolute => {
write!(f, "absolute path not allowed: {}", self.path.display())
}
PathErrorKind::ParentDirTraversal => {
write!(f, "'..' not allowed: {}", self.path.display())
}
PathErrorKind::NullByte => write!(f, "null byte in path: {}", self.path.display()),
PathErrorKind::DeviceName => write!(
f,
"reserved device name not allowed: {}",
self.path.display()
),
PathErrorKind::InvalidChar { ch } => write!(
f,
"invalid character '{ch}' in path: {}",
self.path.display()
),
PathErrorKind::DangerousChar { ch } => write!(
f,
"dangerous Unicode character U+{:04X} in path: {}",
ch as u32,
self.path.display()
),
PathErrorKind::ComponentTooLong {
max_bytes,
actual_bytes,
} => {
write!(
f,
"path component too long (max {max_bytes}B, got {actual_bytes}B): {}",
self.path.display()
)
}
}
}
}
#[derive(Debug, Clone)]
pub struct SafePath(PathBuf);
impl SafePath {
pub fn new(path: impl AsRef<Path>) -> Result<Self> {
const MAX_COMPONENT_LEN: usize = 255;
let path = path.as_ref();
if path.is_absolute() {
return Err(PathError {
path: path.to_path_buf(),
kind: PathErrorKind::Absolute,
}
.into());
}
if path
.components()
.any(|c| c == std::path::Component::ParentDir)
{
return Err(PathError {
path: path.to_path_buf(),
kind: PathErrorKind::ParentDirTraversal,
}
.into());
}
if path.as_os_str().as_encoded_bytes().contains(&b'\0') {
return Err(PathError {
path: path.to_path_buf(),
kind: PathErrorKind::NullByte,
}
.into());
}
if path.as_os_str().as_encoded_bytes().contains(&b':') {
return Err(PathError {
path: path.to_path_buf(),
kind: PathErrorKind::InvalidChar { ch: ':' },
}
.into());
}
#[cfg(windows)]
{
if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
let upper = stem.to_uppercase();
if matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|| (upper.len() == 4
&& (upper.starts_with("COM") || upper.starts_with("LPT"))
&& upper[3..].parse::<u8>().is_ok())
{
return Err(PathError {
path: path.to_path_buf(),
kind: PathErrorKind::DeviceName,
}
.into());
}
}
}
for component in path.components() {
let len = component.as_os_str().len();
if len > MAX_COMPONENT_LEN {
return Err(PathError {
path: path.to_path_buf(),
kind: PathErrorKind::ComponentTooLong {
max_bytes: MAX_COMPONENT_LEN,
actual_bytes: len,
},
}
.into());
}
let s = component.as_os_str().to_string_lossy();
for ch in s.chars() {
if matches!(ch, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') {
return Err(PathError {
path: path.to_path_buf(),
kind: PathErrorKind::DangerousChar { ch },
}
.into());
}
}
}
Ok(Self(path.to_path_buf()))
}
#[must_use]
pub fn as_path(&self) -> &Path {
&self.0
}
}
impl AsRef<Path> for SafePath {
fn as_ref(&self) -> &Path {
&self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_config_new_with_valid_name() -> Result<()> {
let config = Config::new("test")?;
assert_eq!(config.name(), "test");
assert!(config.description().is_none());
Ok(())
}
#[test]
fn test_config_new_with_empty_name_errors() {
let err = Config::new("");
assert!(matches!(err, Err(CoreError::App(_))));
}
#[test]
fn test_config_with_description() -> Result<()> {
let config = Config::new("test")?.with_description("a test config");
assert_eq!(config.description(), Some("a test config"));
Ok(())
}
#[test]
fn test_io_error_conversion() {
let io_err = std::io::Error::other("test");
let core_err = CoreError::from(io_err);
assert!(matches!(core_err, CoreError::Io(_)));
}
#[test]
fn test_serialization_error_conversion() {
let io_err = std::io::Error::other("invalid json");
let serde_err = serde_json::Error::io(io_err);
let core_err = CoreError::from(serde_err);
assert!(matches!(core_err, CoreError::Serialization(_)));
}
#[test]
fn test_safe_path_accepts_relative() -> Result<()> {
let sp = SafePath::new("foo/bar.txt")?;
assert_eq!(sp.as_path(), Path::new("foo/bar.txt"));
Ok(())
}
#[test]
fn test_safe_path_rejects_absolute() {
#[cfg(unix)]
let absolute_path = "/etc/passwd";
#[cfg(windows)]
let absolute_path = r"C:\Windows\system32";
assert!(matches!(
SafePath::new(absolute_path),
Err(CoreError::Path(_))
));
}
#[test]
fn test_safe_path_rejects_parent_dir() {
assert!(matches!(
SafePath::new("../secret.txt"),
Err(CoreError::Path(_))
));
}
#[test]
fn test_safe_path_rejects_null_byte() {
assert!(matches!(
SafePath::new("foo\0bar.txt"),
Err(CoreError::Path(_))
));
}
#[test]
fn test_safe_path_rejects_colon() {
let err = SafePath::new("foo:bar.txt");
assert!(matches!(
err,
Err(CoreError::Path(PathError {
kind: PathErrorKind::InvalidChar { ch: ':' },
..
}))
));
}
#[test]
fn test_safe_path_rejects_bidi_control_chars() {
let path = format!("foo\u{202A}bar.txt");
let err = SafePath::new(path);
assert!(matches!(
err,
Err(CoreError::Path(PathError {
kind: PathErrorKind::DangerousChar { ch: '\u{202A}' },
..
}))
));
let path = format!("foo\u{2066}bar.txt");
let err = SafePath::new(path);
assert!(matches!(
err,
Err(CoreError::Path(PathError {
kind: PathErrorKind::DangerousChar { ch: '\u{2066}' },
..
}))
));
}
#[test]
fn test_safe_path_rejects_component_too_long() {
let long_component = "a".repeat(256);
let err = SafePath::new(&long_component);
assert!(matches!(
err,
Err(CoreError::Path(PathError {
kind: PathErrorKind::ComponentTooLong {
max_bytes: 255,
actual_bytes: 256
},
..
}))
));
}
#[test]
fn test_safe_path_accepts_max_component() -> Result<()> {
let max_component = "a".repeat(255);
let sp = SafePath::new(&max_component)?;
assert_eq!(sp.as_path().as_os_str().len(), 255);
Ok(())
}
#[test]
fn test_platform_error_variant() {
let err = CoreError::Platform("gh not found".into());
assert!(matches!(err, CoreError::Platform(_)));
let msg = format!("{err}");
assert!(msg.contains("platform error"));
assert!(msg.contains("gh not found"));
}
#[test]
fn test_cli_error_from_platform_cli_error() {
let platform_err = PlatformCliError {
user_message: "认证失败".into(),
raw_stderr: "raw".into(),
hint: None,
doc_link: None,
code: None,
platform: platform::Platform::GitHub,
};
let core_err: CoreError = platform_err.into();
assert!(matches!(core_err, CoreError::Cli(_)));
let msg = format!("{core_err}");
assert!(msg.contains("认证失败"));
}
}