Skip to main content

gitflow_core/
lib.rs

1//! gf core library.
2//!
3//! Provides domain types, error handling, and core business logic.
4
5#![forbid(unsafe_code)]
6// Tests legitimately need to unwrap/expect fixture data and index into
7// collections to assert on known shapes; the workspace-wide prohibition
8// applies only to production code.
9#![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
42// Re-export types at the crate root for convenience.
43pub 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/// Application error type.
49///
50/// Library functions return this error type. Use `thiserror` for
51/// derive macros and proper error context.
52#[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    /// An I/O operation failed.
60    #[error("io error: {0}")]
61    Io(#[from] std::io::Error),
62
63    /// A serialization or deserialization failure.
64    #[error("serialization error: {0}")]
65    Serialization(#[from] serde_json::Error),
66
67    /// An application-level error for cases that don't warrant a dedicated variant.
68    /// This variant carries no stability guarantee and should not be matched on programmatically.
69    #[error("application error: {0}")]
70    App(String),
71
72    /// A path traversal or path validation failure.
73    #[error("path error: {0}")]
74    Path(#[from] PathError),
75
76    /// A platform operation error (CLI execution failure, parse error, auth failure, etc.).
77    #[error("platform error: {0}")]
78    Platform(String),
79
80    /// 底层平台 CLI 执行错误(结构化)。
81    ///
82    /// 包含中文用户消息和修复建议,原始 stderr 仅用于调试。
83    #[error(transparent)]
84    Cli(#[from] Box<PlatformCliError>),
85}
86
87/// Ergonomic conversion from [`PlatformCliError`] into [`CoreError::Cli`].
88///
89/// `thiserror`'s `#[from]` on `Box<T>` generates `From<Box<T>>`; this manual
90/// impl lets callers write `Err(platform_err.into())` without explicitly boxing.
91impl From<PlatformCliError> for CoreError {
92    fn from(err: PlatformCliError) -> Self {
93        Self::Cli(Box::new(err))
94    }
95}
96
97/// Core result type alias.
98pub type Result<T> = std::result::Result<T, CoreError>;
99
100// Re-export key domain types at the crate root for convenience.
101pub 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/// Example domain struct demonstrating CLAUDE.md conventions.
109///
110/// Implements `Debug`, uses `typed-builder` style for structs
111/// with many fields, and validates input at construction.
112#[derive(Debug, Clone)]
113#[non_exhaustive]
114pub struct Config {
115    name: String,
116    description: Option<String>,
117}
118
119impl Config {
120    /// Returns the configuration name.
121    #[must_use]
122    pub fn name(&self) -> &str {
123        &self.name
124    }
125
126    /// Returns the optional description.
127    #[must_use]
128    pub fn description(&self) -> Option<&str> {
129        self.description.as_deref()
130    }
131
132    /// Creates a new `Config` with the given name.
133    ///
134    /// # Errors
135    ///
136    /// Returns [`CoreError::App`] if `name` is empty.
137    ///
138    /// # Examples
139    ///
140    /// ```
141    /// use gitflow_core::Config;
142    /// let config = Config::new("my-app")?;
143    /// # Ok::<(), gitflow_core::CoreError>(())
144    /// ```
145    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    /// Sets the description and returns the updated config.
157    #[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/// A path validation error.
165#[derive(Debug, Clone)]
166pub struct PathError {
167    /// The path that caused the error.
168    pub path: PathBuf,
169    /// The kind of path error.
170    pub kind: PathErrorKind,
171}
172
173impl std::error::Error for PathError {}
174
175/// The kind of path validation error.
176#[derive(Debug, Clone)]
177#[non_exhaustive]
178pub enum PathErrorKind {
179    /// The path is absolute.
180    Absolute,
181    /// The path contains `..` components.
182    ParentDirTraversal,
183    /// The path contains a null byte.
184    NullByte,
185    /// The path contains a Windows reserved device name (CON, NUL, etc.).
186    DeviceName,
187    /// The path contains an invalid character.
188    InvalidChar {
189        /// The invalid character found.
190        ch: char,
191    },
192    /// The path contains a dangerous Unicode character.
193    DangerousChar {
194        /// The dangerous character found.
195        ch: char,
196    },
197    /// A path component exceeds the maximum allowed byte length.
198    ComponentTooLong {
199        /// The maximum allowed bytes per component.
200        max_bytes: usize,
201        /// The actual byte length of the offending component.
202        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/// A validated, safe filesystem path.
247///
248/// Rejects `..` components, absolute paths, and null bytes.
249/// Use this for all externally-supplied file path arguments.
250#[derive(Debug, Clone)]
251pub struct SafePath(PathBuf);
252
253impl SafePath {
254    /// Creates a new `SafePath` from a relative path string.
255    ///
256    /// # Errors
257    ///
258    /// Returns [`CoreError::Path`] if:
259    /// - The path contains `..` components
260    /// - The path is absolute
261    /// - The path contains null bytes
262    /// - The path contains a Windows reserved device name
263    /// - The path contains invalid characters (e.g., `:` for ADS)
264    /// - The path contains dangerous Unicode bidi control characters
265    /// - Any path component exceeds 255 bytes
266    ///
267    /// # Examples
268    ///
269    /// ```
270    /// use gitflow_core::SafePath;
271    /// let path = SafePath::new("foo/bar.txt")?;
272    /// assert_eq!(path.as_path(), std::path::Path::new("foo/bar.txt"));
273    /// # Ok::<(), gitflow_core::CoreError>(())
274    /// ```
275    pub fn new(path: impl AsRef<Path>) -> Result<Self> {
276        const MAX_COMPONENT_LEN: usize = 255;
277        let path = path.as_ref();
278
279        // Absolute path check
280        if path.is_absolute() {
281            return Err(PathError {
282                path: path.to_path_buf(),
283                kind: PathErrorKind::Absolute,
284            }
285            .into());
286        }
287
288        // Parent directory traversal check
289        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        // Null byte check
301        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        // Reject colon in path (Windows Alternate Data Streams)
310        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        // Reject Windows reserved device names (case-insensitive, any extension)
319        #[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        // Reject dangerous Unicode bidi control characters
338        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    /// Returns the inner path.
367    #[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        // U+202A (LEFT-TO-RIGHT EMBEDDING)
469        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        // U+2066 (LEFT-TO-RIGHT ISOLATE)
480        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        // `#[from]` should auto-convert PlatformCliError → CoreError (boxed).
535        let core_err: CoreError = platform_err.into();
536        assert!(matches!(core_err, CoreError::Cli(_)));
537        // `#[error(transparent)]` should delegate Display to the inner message.
538        let msg = format!("{core_err}");
539        assert!(msg.contains("认证失败"));
540    }
541}