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