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