gitflow-core 1.2.0

gf 核心库:Platform trait 抽象、跨平台适配器与 toon 输出。Core library: platform abstraction, adapters & toon output.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! gf core library.
//!
//! Provides domain types, error handling, and core business logic.

#![forbid(unsafe_code)]
// Tests legitimately need to unwrap/expect fixture data and index into
// collections to assert on known shapes; the workspace-wide prohibition
// applies only to production 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 cleanup;
pub mod cli_error;
pub mod commit;
pub mod compatibility;
pub mod git_ops;
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;

// Re-export types at the crate root for convenience.
pub use auth_checker::{AuthCheckResult, AuthChecker};
pub use cli_error::PlatformCliError;
pub use compatibility::{PlatformCompat, platform_compatibility, platform_requirement};
pub use output::{CliError, CliOutput};

/// Application error type.
///
/// Library functions return this error type. Use `thiserror` for
/// derive macros and proper error context.
#[allow(
    clippy::module_name_repetitions,
    reason = "Avoids collision with std::error::Error and thiserror::Error"
)]
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum CoreError {
    /// An I/O operation failed.
    #[error("io error: {0}")]
    Io(#[from] std::io::Error),

    /// A serialization or deserialization failure.
    #[error("serialization error: {0}")]
    Serialization(#[from] serde_json::Error),

    /// An application-level error for cases that don't warrant a dedicated variant.
    /// This variant carries no stability guarantee and should not be matched on programmatically.
    #[error("application error: {0}")]
    App(String),

    /// A path traversal or path validation failure.
    #[error("path error: {0}")]
    Path(#[from] PathError),

    /// A platform operation error (CLI execution failure, parse error, auth failure, etc.).
    #[error("platform error: {0}")]
    Platform(String),

    /// 底层平台 CLI 执行错误(结构化)。
    ///
    /// 包含中文用户消息和修复建议,原始 stderr 仅用于调试。
    #[error(transparent)]
    Cli(#[from] Box<PlatformCliError>),
}

/// Ergonomic conversion from [`PlatformCliError`] into [`CoreError::Cli`].
///
/// `thiserror`'s `#[from]` on `Box<T>` generates `From<Box<T>>`; this manual
/// impl lets callers write `Err(platform_err.into())` without explicitly boxing.
impl From<PlatformCliError> for CoreError {
    fn from(err: PlatformCliError) -> Self {
        Self::Cli(Box::new(err))
    }
}

/// Core result type alias.
pub type Result<T> = std::result::Result<T, CoreError>;

// Re-export key domain types at the crate root for convenience.
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};

/// Example domain struct demonstrating CLAUDE.md conventions.
///
/// Implements `Debug`, uses `typed-builder` style for structs
/// with many fields, and validates input at construction.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Config {
    name: String,
    description: Option<String>,
}

impl Config {
    /// Returns the configuration name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the optional description.
    #[must_use]
    pub fn description(&self) -> Option<&str> {
        self.description.as_deref()
    }

    /// Creates a new `Config` with the given name.
    ///
    /// # Errors
    ///
    /// Returns [`CoreError::App`] if `name` is empty.
    ///
    /// # Examples
    ///
    /// ```
    /// use gitflow_core::Config;
    /// let config = Config::new("my-app")?;
    /// # Ok::<(), gitflow_core::CoreError>(())
    /// ```
    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,
        })
    }

    /// Sets the description and returns the updated config.
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }
}

/// A path validation error.
#[derive(Debug, Clone)]
pub struct PathError {
    /// The path that caused the error.
    pub path: PathBuf,
    /// The kind of path error.
    pub kind: PathErrorKind,
}

impl std::error::Error for PathError {}

/// The kind of path validation error.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum PathErrorKind {
    /// The path is absolute.
    Absolute,
    /// The path contains `..` components.
    ParentDirTraversal,
    /// The path contains a null byte.
    NullByte,
    /// The path contains a Windows reserved device name (CON, NUL, etc.).
    DeviceName,
    /// The path contains an invalid character.
    InvalidChar {
        /// The invalid character found.
        ch: char,
    },
    /// The path contains a dangerous Unicode character.
    DangerousChar {
        /// The dangerous character found.
        ch: char,
    },
    /// A path component exceeds the maximum allowed byte length.
    ComponentTooLong {
        /// The maximum allowed bytes per component.
        max_bytes: usize,
        /// The actual byte length of the offending component.
        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()
                )
            }
        }
    }
}

/// A validated, safe filesystem path.
///
/// Rejects `..` components, absolute paths, and null bytes.
/// Use this for all externally-supplied file path arguments.
#[derive(Debug, Clone)]
pub struct SafePath(PathBuf);

impl SafePath {
    /// Creates a new `SafePath` from a relative path string.
    ///
    /// # Errors
    ///
    /// Returns [`CoreError::Path`] if:
    /// - The path contains `..` components
    /// - The path is absolute
    /// - The path contains null bytes
    /// - The path contains a Windows reserved device name
    /// - The path contains invalid characters (e.g., `:` for ADS)
    /// - The path contains dangerous Unicode bidi control characters
    /// - Any path component exceeds 255 bytes
    ///
    /// # Examples
    ///
    /// ```
    /// use gitflow_core::SafePath;
    /// let path = SafePath::new("foo/bar.txt")?;
    /// assert_eq!(path.as_path(), std::path::Path::new("foo/bar.txt"));
    /// # Ok::<(), gitflow_core::CoreError>(())
    /// ```
    pub fn new(path: impl AsRef<Path>) -> Result<Self> {
        const MAX_COMPONENT_LEN: usize = 255;
        let path = path.as_ref();

        // Absolute path check
        if path.is_absolute() {
            return Err(PathError {
                path: path.to_path_buf(),
                kind: PathErrorKind::Absolute,
            }
            .into());
        }

        // Parent directory traversal check
        if path
            .components()
            .any(|c| c == std::path::Component::ParentDir)
        {
            return Err(PathError {
                path: path.to_path_buf(),
                kind: PathErrorKind::ParentDirTraversal,
            }
            .into());
        }

        // Null byte check
        if path.as_os_str().as_encoded_bytes().contains(&b'\0') {
            return Err(PathError {
                path: path.to_path_buf(),
                kind: PathErrorKind::NullByte,
            }
            .into());
        }

        // Reject colon in path (Windows Alternate Data Streams)
        if path.as_os_str().as_encoded_bytes().contains(&b':') {
            return Err(PathError {
                path: path.to_path_buf(),
                kind: PathErrorKind::InvalidChar { ch: ':' },
            }
            .into());
        }

        // Reject Windows reserved device names (case-insensitive, any extension)
        #[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());
                }
            }
        }

        // Reject dangerous Unicode bidi control characters
        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()))
    }

    /// Returns the inner path.
    #[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() {
        // U+202A (LEFT-TO-RIGHT EMBEDDING)
        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}' },
                ..
            }))
        ));

        // U+2066 (LEFT-TO-RIGHT ISOLATE)
        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,
        };
        // `#[from]` should auto-convert PlatformCliError → CoreError (boxed).
        let core_err: CoreError = platform_err.into();
        assert!(matches!(core_err, CoreError::Cli(_)));
        // `#[error(transparent)]` should delegate Display to the inner message.
        let msg = format!("{core_err}");
        assert!(msg.contains("认证失败"));
    }
}