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 decision;
33pub mod doctor;
34pub mod evaluation;
35pub mod git_ops;
36pub mod issue;
37pub mod issue_quality;
38pub mod label;
39pub mod output;
40pub mod paging;
41pub mod pipeline;
42pub mod pipeline_failure;
43pub mod platform;
44pub mod pr;
45pub mod pr_precheck;
46pub mod query_filter;
47pub mod release;
48pub mod review;
49pub mod semantic_regression;
50pub mod session;
51pub mod skill_suggestion;
52pub mod toon;
53pub mod types;
54pub mod workflow_context;
55pub mod workflow_progress;
56pub mod workflow_recommendation;
57pub mod workflow_semantic;
58
59// Re-export types at the crate root for convenience.
60pub use auth_checker::{AuthCheckResult, AuthChecker};
61pub use cli_error::PlatformCliError;
62pub use compatibility::{PlatformCompat, platform_compatibility, platform_requirement};
63pub use doctor::{CheckItem, CheckStatus, DoctorReport, DoctorSummary, HealthCheck};
64pub use output::{CliError, CliOutput, PaginationMeta};
65pub use paging::{DEFAULT_LIST_LIMIT, FetchStrategy, Paged, fetch_capped};
66
67/// Application error type.
68///
69/// Library functions return this error type. Use `thiserror` for
70/// derive macros and proper error context.
71#[allow(
72    clippy::module_name_repetitions,
73    reason = "Avoids collision with std::error::Error and thiserror::Error"
74)]
75#[derive(Debug, Error)]
76#[non_exhaustive]
77pub enum CoreError {
78    /// An I/O operation failed.
79    #[error("io error: {0}")]
80    Io(#[from] std::io::Error),
81
82    /// A serialization or deserialization failure.
83    #[error("serialization error: {0}")]
84    Serialization(#[from] serde_json::Error),
85
86    /// An application-level error for cases that don't warrant a dedicated variant.
87    /// This variant carries no stability guarantee and should not be matched on programmatically.
88    #[error("application error: {0}")]
89    App(String),
90
91    /// A path traversal or path validation failure.
92    #[error("path error: {0}")]
93    Path(#[from] PathError),
94
95    /// A platform operation error (CLI execution failure, parse error, auth failure, etc.).
96    #[error("platform error: {0}")]
97    Platform(String),
98
99    /// 底层平台 CLI 执行错误(结构化)。
100    ///
101    /// 包含中文用户消息和修复建议,原始 stderr 仅用于调试。
102    #[error(transparent)]
103    Cli(#[from] Box<PlatformCliError>),
104}
105
106/// Ergonomic conversion from [`PlatformCliError`] into [`CoreError::Cli`].
107///
108/// `thiserror`'s `#[from]` on `Box<T>` generates `From<Box<T>>`; this manual
109/// impl lets callers write `Err(platform_err.into())` without explicitly boxing.
110impl From<PlatformCliError> for CoreError {
111    fn from(err: PlatformCliError) -> Self {
112        Self::Cli(Box::new(err))
113    }
114}
115
116/// Core result type alias.
117pub type Result<T> = std::result::Result<T, CoreError>;
118
119// Re-export key domain types at the crate root for convenience.
120pub use auth::{AuthStatus, HostAuthStatus};
121pub use commit::{CommitData, CommitDetail, CommitFile};
122pub use label::{CreateLabelArgs, CreateMilestoneArgs, LabelData, MilestoneData};
123pub use release::{CreateReleaseArgs, ReleaseData};
124pub use review::{ReviewCommentData, ReviewData, ReviewState};
125pub use session::Session;
126pub use types::{CommentData, MergeResult, MergeStrategy};
127
128/// Example domain struct demonstrating CLAUDE.md conventions.
129///
130/// Implements `Debug`, uses `typed-builder` style for structs
131/// with many fields, and validates input at construction.
132#[derive(Debug, Clone)]
133#[non_exhaustive]
134pub struct Config {
135    name: String,
136    description: Option<String>,
137}
138
139impl Config {
140    /// Returns the configuration name.
141    #[must_use]
142    pub fn name(&self) -> &str {
143        &self.name
144    }
145
146    /// Returns the optional description.
147    #[must_use]
148    pub fn description(&self) -> Option<&str> {
149        self.description.as_deref()
150    }
151
152    /// Creates a new `Config` with the given name.
153    ///
154    /// # Errors
155    ///
156    /// Returns [`CoreError::App`] if `name` is empty.
157    ///
158    /// # Examples
159    ///
160    /// ```
161    /// use gitflow_core::Config;
162    /// let config = Config::new("my-app")?;
163    /// # Ok::<(), gitflow_core::CoreError>(())
164    /// ```
165    pub fn new(name: impl Into<String>) -> Result<Self> {
166        let name = name.into();
167        if name.is_empty() {
168            return Err(CoreError::App("config name must not be empty".into()));
169        }
170        Ok(Self {
171            name,
172            description: None,
173        })
174    }
175
176    /// Sets the description and returns the updated config.
177    #[must_use]
178    pub fn with_description(mut self, description: impl Into<String>) -> Self {
179        self.description = Some(description.into());
180        self
181    }
182}
183
184/// A path validation error.
185#[derive(Debug, Clone)]
186pub struct PathError {
187    /// The path that caused the error.
188    pub path: PathBuf,
189    /// The kind of path error.
190    pub kind: PathErrorKind,
191}
192
193impl std::error::Error for PathError {}
194
195/// The kind of path validation error.
196#[derive(Debug, Clone)]
197#[non_exhaustive]
198pub enum PathErrorKind {
199    /// The path is absolute.
200    Absolute,
201    /// The path contains `..` components.
202    ParentDirTraversal,
203    /// The path contains a null byte.
204    NullByte,
205    /// The path contains a Windows reserved device name (CON, NUL, etc.).
206    DeviceName,
207    /// The path contains an invalid character.
208    InvalidChar {
209        /// The invalid character found.
210        ch: char,
211    },
212    /// The path contains a dangerous Unicode character.
213    DangerousChar {
214        /// The dangerous character found.
215        ch: char,
216    },
217    /// A path component exceeds the maximum allowed byte length.
218    ComponentTooLong {
219        /// The maximum allowed bytes per component.
220        max_bytes: usize,
221        /// The actual byte length of the offending component.
222        actual_bytes: usize,
223    },
224}
225
226impl std::fmt::Display for PathError {
227    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
228        match self.kind {
229            PathErrorKind::Absolute => {
230                write!(f, "absolute path not allowed: {}", self.path.display())
231            }
232            PathErrorKind::ParentDirTraversal => {
233                write!(f, "'..' not allowed: {}", self.path.display())
234            }
235            PathErrorKind::NullByte => write!(f, "null byte in path: {}", self.path.display()),
236            PathErrorKind::DeviceName => write!(
237                f,
238                "reserved device name not allowed: {}",
239                self.path.display()
240            ),
241            PathErrorKind::InvalidChar { ch } => write!(
242                f,
243                "invalid character '{ch}' in path: {}",
244                self.path.display()
245            ),
246            PathErrorKind::DangerousChar { ch } => write!(
247                f,
248                "dangerous Unicode character U+{:04X} in path: {}",
249                ch as u32,
250                self.path.display()
251            ),
252            PathErrorKind::ComponentTooLong {
253                max_bytes,
254                actual_bytes,
255            } => {
256                write!(
257                    f,
258                    "path component too long (max {max_bytes}B, got {actual_bytes}B): {}",
259                    self.path.display()
260                )
261            }
262        }
263    }
264}
265
266/// A validated, safe filesystem path.
267///
268/// Rejects `..` components, absolute paths, and null bytes.
269/// Use this for all externally-supplied file path arguments.
270#[derive(Debug, Clone)]
271pub struct SafePath(PathBuf);
272
273impl SafePath {
274    /// Creates a new `SafePath` from a relative path string.
275    ///
276    /// # Errors
277    ///
278    /// Returns [`CoreError::Path`] if:
279    /// - The path contains `..` components
280    /// - The path is absolute
281    /// - The path contains null bytes
282    /// - The path contains a Windows reserved device name
283    /// - The path contains invalid characters (e.g., `:` for ADS)
284    /// - The path contains dangerous Unicode bidi control characters
285    /// - Any path component exceeds 255 bytes
286    ///
287    /// # Examples
288    ///
289    /// ```
290    /// use gitflow_core::SafePath;
291    /// let path = SafePath::new("foo/bar.txt")?;
292    /// assert_eq!(path.as_path(), std::path::Path::new("foo/bar.txt"));
293    /// # Ok::<(), gitflow_core::CoreError>(())
294    /// ```
295    pub fn new(path: impl AsRef<Path>) -> Result<Self> {
296        Self::validate(path.as_ref(), false)
297    }
298
299    /// Creates a new `SafePath` from a path string, permitting absolute paths.
300    ///
301    /// Use this only for arguments where an absolute path is a legitimate,
302    /// intentional input from the invoking user (e.g. a CLI `--path` flag
303    /// naming an install directory), not for path fragments that get joined
304    /// onto a trusted base directory.
305    ///
306    /// All other [`SafePath::new`] checks still apply: `..` traversal, null
307    /// bytes, reserved device names, invalid characters, dangerous Unicode
308    /// bidi control characters, and per-component length are still rejected.
309    ///
310    /// # Errors
311    ///
312    /// See [`SafePath::new`] for the full list of rejected inputs (absolute
313    /// paths excepted).
314    pub fn new_allow_absolute(path: impl AsRef<Path>) -> Result<Self> {
315        Self::validate(path.as_ref(), true)
316    }
317
318    fn validate(path: &Path, allow_absolute: bool) -> Result<Self> {
319        const MAX_COMPONENT_LEN: usize = 255;
320
321        // Absolute path check
322        if !allow_absolute && path.is_absolute() {
323            return Err(PathError {
324                path: path.to_path_buf(),
325                kind: PathErrorKind::Absolute,
326            }
327            .into());
328        }
329
330        // Parent directory traversal check
331        if path
332            .components()
333            .any(|c| c == std::path::Component::ParentDir)
334        {
335            return Err(PathError {
336                path: path.to_path_buf(),
337                kind: PathErrorKind::ParentDirTraversal,
338            }
339            .into());
340        }
341
342        // Null byte check
343        if path.as_os_str().as_encoded_bytes().contains(&b'\0') {
344            return Err(PathError {
345                path: path.to_path_buf(),
346                kind: PathErrorKind::NullByte,
347            }
348            .into());
349        }
350
351        // Reject colon in path (Windows Alternate Data Streams), except inside
352        // a `Prefix` component (e.g. the `C:` drive letter of a legitimate
353        // Windows absolute path) — `C:\Users\...` is fine, `file.txt:stream`
354        // is an ADS injection attempt.
355        if path.components().any(|c| {
356            !matches!(c, std::path::Component::Prefix(_))
357                && c.as_os_str().as_encoded_bytes().contains(&b':')
358        }) {
359            return Err(PathError {
360                path: path.to_path_buf(),
361                kind: PathErrorKind::InvalidChar { ch: ':' },
362            }
363            .into());
364        }
365
366        // Reject Windows reserved device names (case-insensitive, any extension)
367        #[cfg(windows)]
368        {
369            if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
370                let upper = stem.to_uppercase();
371                if matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")
372                    || (upper.len() == 4
373                        && (upper.starts_with("COM") || upper.starts_with("LPT"))
374                        && upper[3..].parse::<u8>().is_ok())
375                {
376                    return Err(PathError {
377                        path: path.to_path_buf(),
378                        kind: PathErrorKind::DeviceName,
379                    }
380                    .into());
381                }
382            }
383        }
384
385        // Reject dangerous Unicode bidi control characters
386        for component in path.components() {
387            let len = component.as_os_str().len();
388            if len > MAX_COMPONENT_LEN {
389                return Err(PathError {
390                    path: path.to_path_buf(),
391                    kind: PathErrorKind::ComponentTooLong {
392                        max_bytes: MAX_COMPONENT_LEN,
393                        actual_bytes: len,
394                    },
395                }
396                .into());
397            }
398
399            let s = component.as_os_str().to_string_lossy();
400            for ch in s.chars() {
401                if matches!(ch, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}') {
402                    return Err(PathError {
403                        path: path.to_path_buf(),
404                        kind: PathErrorKind::DangerousChar { ch },
405                    }
406                    .into());
407                }
408            }
409        }
410
411        Ok(Self(path.to_path_buf()))
412    }
413
414    /// Returns the inner path.
415    #[must_use]
416    pub fn as_path(&self) -> &Path {
417        &self.0
418    }
419}
420
421impl AsRef<Path> for SafePath {
422    fn as_ref(&self) -> &Path {
423        &self.0
424    }
425}
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430
431    #[test]
432    fn test_config_new_with_valid_name() -> Result<()> {
433        let config = Config::new("test")?;
434        assert_eq!(config.name(), "test");
435        assert!(config.description().is_none());
436        Ok(())
437    }
438
439    #[test]
440    fn test_config_new_with_empty_name_errors() {
441        let err = Config::new("");
442        assert!(matches!(err, Err(CoreError::App(_))));
443    }
444
445    #[test]
446    fn test_config_with_description() -> Result<()> {
447        let config = Config::new("test")?.with_description("a test config");
448        assert_eq!(config.description(), Some("a test config"));
449        Ok(())
450    }
451
452    #[test]
453    fn test_io_error_conversion() {
454        let io_err = std::io::Error::other("test");
455        let core_err = CoreError::from(io_err);
456        assert!(matches!(core_err, CoreError::Io(_)));
457    }
458
459    #[test]
460    fn test_serialization_error_conversion() {
461        let io_err = std::io::Error::other("invalid json");
462        let serde_err = serde_json::Error::io(io_err);
463        let core_err = CoreError::from(serde_err);
464        assert!(matches!(core_err, CoreError::Serialization(_)));
465    }
466
467    #[test]
468    fn test_safe_path_accepts_relative() -> Result<()> {
469        let sp = SafePath::new("foo/bar.txt")?;
470        assert_eq!(sp.as_path(), Path::new("foo/bar.txt"));
471        Ok(())
472    }
473
474    #[test]
475    fn test_safe_path_rejects_absolute() {
476        #[cfg(unix)]
477        let absolute_path = "/etc/passwd";
478        #[cfg(windows)]
479        let absolute_path = r"C:\Windows\system32";
480        assert!(matches!(
481            SafePath::new(absolute_path),
482            Err(CoreError::Path(_))
483        ));
484    }
485
486    #[test]
487    fn test_safe_path_rejects_parent_dir() {
488        assert!(matches!(
489            SafePath::new("../secret.txt"),
490            Err(CoreError::Path(_))
491        ));
492    }
493
494    #[test]
495    fn test_safe_path_rejects_null_byte() {
496        assert!(matches!(
497            SafePath::new("foo\0bar.txt"),
498            Err(CoreError::Path(_))
499        ));
500    }
501
502    #[test]
503    fn test_safe_path_rejects_colon() {
504        let err = SafePath::new("foo:bar.txt");
505        assert!(matches!(
506            err,
507            Err(CoreError::Path(PathError {
508                kind: PathErrorKind::InvalidChar { ch: ':' },
509                ..
510            }))
511        ));
512    }
513
514    #[test]
515    #[cfg(windows)]
516    fn test_safe_path_allows_windows_drive_letter_colon() {
517        // The drive-letter colon in `C:\...` is a structural part of a
518        // Windows absolute path, not an Alternate Data Streams injection —
519        // `new_allow_absolute` must accept it.
520        let sp = SafePath::new_allow_absolute(r"C:\Users\runner\Temp\body.md");
521        assert!(
522            sp.is_ok(),
523            "drive-letter colon must not be rejected: {sp:?}"
524        );
525    }
526
527    #[test]
528    #[cfg(windows)]
529    fn test_safe_path_rejects_ads_colon_in_absolute_windows_path() {
530        // A colon inside a filename component (not the drive prefix) is a
531        // real Alternate Data Streams injection attempt and must still be
532        // rejected even when absolute paths are otherwise allowed.
533        let err = SafePath::new_allow_absolute(r"C:\Users\runner\Temp\body.md:evil");
534        assert!(matches!(
535            err,
536            Err(CoreError::Path(PathError {
537                kind: PathErrorKind::InvalidChar { ch: ':' },
538                ..
539            }))
540        ));
541    }
542
543    #[test]
544    fn test_safe_path_rejects_bidi_control_chars() {
545        // U+202A (LEFT-TO-RIGHT EMBEDDING)
546        let path = format!("foo\u{202A}bar.txt");
547        let err = SafePath::new(path);
548        assert!(matches!(
549            err,
550            Err(CoreError::Path(PathError {
551                kind: PathErrorKind::DangerousChar { ch: '\u{202A}' },
552                ..
553            }))
554        ));
555
556        // U+2066 (LEFT-TO-RIGHT ISOLATE)
557        let path = format!("foo\u{2066}bar.txt");
558        let err = SafePath::new(path);
559        assert!(matches!(
560            err,
561            Err(CoreError::Path(PathError {
562                kind: PathErrorKind::DangerousChar { ch: '\u{2066}' },
563                ..
564            }))
565        ));
566    }
567
568    #[test]
569    fn test_safe_path_rejects_component_too_long() {
570        let long_component = "a".repeat(256);
571        let err = SafePath::new(&long_component);
572        assert!(matches!(
573            err,
574            Err(CoreError::Path(PathError {
575                kind: PathErrorKind::ComponentTooLong {
576                    max_bytes: 255,
577                    actual_bytes: 256
578                },
579                ..
580            }))
581        ));
582    }
583
584    #[test]
585    fn test_safe_path_accepts_max_component() -> Result<()> {
586        let max_component = "a".repeat(255);
587        let sp = SafePath::new(&max_component)?;
588        assert_eq!(sp.as_path().as_os_str().len(), 255);
589        Ok(())
590    }
591
592    #[test]
593    fn test_safe_path_allow_absolute_accepts_absolute() -> Result<()> {
594        #[cfg(unix)]
595        let absolute_path = "/home/user/custom-skills";
596        #[cfg(windows)]
597        let absolute_path = r"C:\Users\user\custom-skills";
598        let sp = SafePath::new_allow_absolute(absolute_path)?;
599        assert_eq!(sp.as_path(), Path::new(absolute_path));
600        Ok(())
601    }
602
603    #[test]
604    fn test_safe_path_allow_absolute_accepts_relative() -> Result<()> {
605        let sp = SafePath::new_allow_absolute("foo/bar.txt")?;
606        assert_eq!(sp.as_path(), Path::new("foo/bar.txt"));
607        Ok(())
608    }
609
610    #[test]
611    fn test_safe_path_allow_absolute_rejects_parent_dir() {
612        assert!(matches!(
613            SafePath::new_allow_absolute("../secret.txt"),
614            Err(CoreError::Path(_))
615        ));
616        assert!(matches!(
617            SafePath::new_allow_absolute("/foo/../bar"),
618            Err(CoreError::Path(_))
619        ));
620    }
621
622    #[test]
623    fn test_safe_path_allow_absolute_rejects_null_byte() {
624        assert!(matches!(
625            SafePath::new_allow_absolute("foo\0bar.txt"),
626            Err(CoreError::Path(_))
627        ));
628    }
629
630    #[test]
631    fn test_platform_error_variant() {
632        let err = CoreError::Platform("gh not found".into());
633        assert!(matches!(err, CoreError::Platform(_)));
634        let msg = format!("{err}");
635        assert!(msg.contains("platform error"));
636        assert!(msg.contains("gh not found"));
637    }
638
639    #[test]
640    fn test_cli_error_from_platform_cli_error() {
641        let platform_err = PlatformCliError {
642            user_message: "认证失败".into(),
643            raw_stderr: "raw".into(),
644            hint: None,
645            doc_link: None,
646            code: None,
647            platform: platform::Platform::GitHub,
648        };
649        // `#[from]` should auto-convert PlatformCliError → CoreError (boxed).
650        let core_err: CoreError = platform_err.into();
651        assert!(matches!(core_err, CoreError::Cli(_)));
652        // `#[error(transparent)]` should delegate Display to the inner message.
653        let msg = format!("{core_err}");
654        assert!(msg.contains("认证失败"));
655    }
656}
657// Trigger E2E tests for documentation-only PR