gitflow-cli 2.1.0

跨平台 Git 工程化工作流编排框架:统一封装 GitHub / GitLab / GitCode 三大平台,配合 AI Agent Skills,覆盖从需求到发布的完整工程循环。
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
//! 共享输出格式化模块。
//!
//! 提供统一的 [`print_output`] 函数,支持 JSON(默认)、Text、TOON 和 Auto 格式。
//! - JSON: 美化 JSON(默认,机器消费)
//! - Text: 人类友好的表格/键值对格式
//! - TOON: Token-Oriented Object Notation,紧凑格式(LLM 消费)
//! - Auto: 根据数据结构自动选择 JSON 或 TOON

use crate::OutputFormat;

/// 将可序列化的值按指定格式打印到 stdout。
///
/// # Errors
///
/// 返回错误当:
/// - JSON 序列化失败。
/// - Text/TOON 格式化时内部转换失败。
pub fn print_output<T: serde::Serialize>(value: &T, format: &OutputFormat) -> miette::Result<()> {
    match format {
        OutputFormat::Json => print_json(value),
        OutputFormat::Text => print_text(value),
        OutputFormat::Toon => print_toon(value),
        OutputFormat::Auto => print_auto(value),
    }
}

/// 构造截断警告文案;未截断时返回 `None`。
///
/// 抽成纯函数以便单元测试——实际写 stderr 的动作在
/// [`print_list_output`] 中,本身不含逻辑。
#[must_use]
pub fn truncation_warning(meta: &gitflow_core::PaginationMeta) -> Option<String> {
    if !meta.truncated {
        return None;
    }
    Some(format!(
        "⚠️  结果被截断:返回 {returned} 条,还有更多未取回。用 --limit <N> 提高上限。",
        returned = meta.returned
    ))
}

/// 打印列表类命令的输出:数据走 stdout,截断警告走 stderr。
///
/// 警告走 stderr 而非 stdout,以保证 stdout 仍可直接喂给 `jq`。
///
/// # Errors
///
/// 序列化或格式化失败时返回错误。
pub fn print_list_output<T: serde::Serialize>(
    items: T,
    meta: gitflow_core::PaginationMeta,
    platform: &str,
    command: &str,
    format: &OutputFormat,
) -> miette::Result<()> {
    let warning = truncation_warning(&meta);
    let output = gitflow_core::CliOutput::success_paged(items, meta, platform, command);
    print_output(&output, format)?;
    if let Some(warning) = warning {
        eprintln!("{warning}");
    }
    Ok(())
}

/// JSON 格式输出。
fn print_json<T: serde::Serialize>(value: &T) -> miette::Result<()> {
    let json = serde_json::to_string_pretty(value)
        .map_err(|e| miette::miette!("Failed to serialize output to JSON: {e}"))?;
    println!("{json}");
    Ok(())
}

/// TOON 格式输出。
fn print_toon<T: serde::Serialize>(value: &T) -> miette::Result<()> {
    let json_value = serde_json::to_value(value)
        .map_err(|e| miette::miette!("Failed to serialize value for TOON output: {e}"))?;
    let toon = gitflow_core::toon::encode(&json_value)
        .map_err(|e| miette::miette!("Failed to encode TOON output: {e}"))?;
    println!("{toon}");
    Ok(())
}

/// 自动选择格式输出。
///
/// 根据数据结构分析选择 JSON 或 TOON:
/// - 小数据 (< 200 字符) → JSON
/// - 均匀数组 (≥5 元素) → TOON
/// - 深度嵌套 (> 3 层) → TOON
/// - 其他 → JSON
fn print_auto<T: serde::Serialize>(value: &T) -> miette::Result<()> {
    let json_value = serde_json::to_value(value)
        .map_err(|e| miette::miette!("Failed to serialize value for auto output: {e}"))?;
    let shape = gitflow_core::toon::analyze(&json_value);
    let strategy = gitflow_core::toon::select_strategy(&shape);

    match strategy {
        gitflow_core::toon::ToonStrategy::Toon => {
            let toon = gitflow_core::toon::encode(&json_value)
                .map_err(|e| miette::miette!("Failed to encode TOON output: {e}"))?;
            println!("{toon}");
        }
        gitflow_core::toon::ToonStrategy::Json => {
            let json = serde_json::to_string_pretty(&json_value)
                .map_err(|e| miette::miette!("Failed to serialize output to JSON: {e}"))?;
            println!("{json}");
        }
    }
    Ok(())
}

/// Text 格式输出。先将值序列化为 [`serde_json::Value`],再根据结构选择格式化策略。
fn print_text<T: serde::Serialize>(value: &T) -> miette::Result<()> {
    let v = serde_json::to_value(value)
        .map_err(|e| miette::miette!("Failed to serialize value for text output: {e}"))?;
    match &v {
        serde_json::Value::Array(arr) => {
            print_text_array(arr);
        }
        serde_json::Value::Object(obj) => {
            print_text_object(obj);
        }
        serde_json::Value::Null => {
            println!("(空)");
        }
        other => {
            // 标量值直接打印
            println!("{other}");
        }
    }
    Ok(())
}

/// 数组 → 表格格式。
///
/// 自动检测数组中每个元素的公共字段作为列名。
/// 空数组打印 "(空)"。
fn print_text_array(arr: &[serde_json::Value]) {
    if arr.is_empty() {
        println!("(空)");
        return;
    }

    // 收集所有可能的列名(按首次出现顺序)
    let mut columns: Vec<String> = Vec::new();
    for item in arr {
        if let serde_json::Value::Object(obj) = item {
            for key in obj.keys() {
                let col = key.clone();
                if !columns.contains(&col) {
                    columns.push(col);
                }
            }
        }
    }

    if columns.is_empty() {
        // 数组元素不是对象(如字符串数组),按列表打印
        for (i, item) in arr.iter().enumerate() {
            println!("  {}. {}", i + 1, format_value(item));
        }
        return;
    }

    // 计算列宽
    let mut col_widths: Vec<usize> = columns.iter().map(String::len).collect();
    for item in arr {
        if let serde_json::Value::Object(obj) = item {
            for (ci, col) in columns.iter().enumerate() {
                if let Some(val) = obj.get(col) {
                    let display = format_value(val);
                    if let Some(w) = col_widths.get_mut(ci) {
                        *w = (*w).max(display.chars().count());
                    }
                }
            }
        }
    }

    // 打印表头
    let header: Vec<String> = columns
        .iter()
        .enumerate()
        .map(|(i, c)| pad_right(c, *col_widths.get(i).unwrap_or(&0)))
        .collect();
    println!("{}", header.join(" │ "));

    // 打印分隔线
    let sep: Vec<String> = col_widths.iter().map(|w| "─".repeat(*w)).collect();
    println!("{}", sep.join("─┼─"));

    // 打印数据行
    for item in arr {
        let row: Vec<String> = columns
            .iter()
            .enumerate()
            .map(|(ci, col)| {
                if let serde_json::Value::Object(obj) = item {
                    let val = obj.get(col).map_or(String::new(), format_value);
                    pad_right(&val, *col_widths.get(ci).unwrap_or(&0))
                } else {
                    String::new()
                }
            })
            .collect();
        println!("{}", row.join(" │ "));
    }
}

/// 对象 → 键值对格式。
fn print_text_object(obj: &serde_json::Map<String, serde_json::Value>) {
    if obj.is_empty() {
        println!("(空)");
        return;
    }

    // 计算最大键宽
    let max_key_len = obj.keys().map(|k| k.chars().count()).max().unwrap_or(0);

    for (key, val) in obj {
        let display = format_value(val);
        if display.contains('\n') {
            // 多行值:键单独一行,值缩进
            println!("{key}:");
            for line in display.lines() {
                println!("  {line}");
            }
        } else {
            println!("  {key:>max_key_len$}: {display}");
        }
    }
}

/// 将 [`serde_json::Value`] 转为人类友好的字符串。
fn format_value(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::Null => String::from("-"),
        serde_json::Value::Bool(b) => b.to_string(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Array(arr) => {
            let items: Vec<String> = arr.iter().map(format_value).collect();
            items.join(", ")
        }
        serde_json::Value::Object(_) => String::from("{…}"),
    }
}

/// 右填充字符串到指定宽度(按字符数,非字节数)。
fn pad_right(s: &str, width: usize) -> String {
    let char_count = s.chars().count();
    if char_count >= width {
        s.to_string()
    } else {
        format!("{}{}", s, " ".repeat(width - char_count))
    }
}

#[cfg(test)]
#[allow(
    clippy::expect_used,
    clippy::unwrap_used,
    clippy::panic,
    reason = "允许在测试中使用 expect/unwrap/panic"
)]
mod tests {
    use gitflow_core::PaginationMeta;
    use serde::Serialize;

    use super::*;

    #[test]
    fn test_should_not_warn_when_not_truncated() {
        let meta = PaginationMeta {
            truncated: false,
            returned: 33,
            limit: 1000,
        };
        assert_eq!(truncation_warning(&meta), None);
    }

    #[test]
    fn test_should_warn_with_counts_when_truncated() {
        let meta = PaginationMeta {
            truncated: true,
            returned: 1000,
            limit: 1000,
        };
        let warning = truncation_warning(&meta).expect("truncated 必须产生警告");
        assert!(warning.contains("1000"), "警告必须含实际返回条数");
        assert!(warning.contains("--limit"), "警告必须告诉用户如何提高上限");
    }

    #[derive(Serialize)]
    struct TestIssue {
        number: u64,
        title: String,
        state: String,
    }

    #[derive(Serialize)]
    struct TestPr {
        number: u64,
        title: String,
        state: String,
        branch: String,
        draft: bool,
    }

    #[test]
    fn test_should_output_json_format() {
        let issues = vec![TestIssue {
            number: 1,
            title: String::from("测试标题"),
            state: String::from("open"),
        }];
        let result = print_output(&issues, &OutputFormat::Json);
        assert!(result.is_ok());
    }

    #[test]
    fn test_should_output_text_format_for_array() {
        let issues = vec![
            TestIssue {
                number: 1,
                title: String::from("修复登录 bug"),
                state: String::from("open"),
            },
            TestIssue {
                number: 2,
                title: String::from("添加新功能"),
                state: String::from("closed"),
            },
        ];
        let result = print_output(&issues, &OutputFormat::Text);
        assert!(result.is_ok());
    }

    #[test]
    fn test_should_output_text_format_for_object() {
        let pr = TestPr {
            number: 42,
            title: String::from("重构模块"),
            state: String::from("open"),
            branch: String::from("feat/refactor"),
            draft: false,
        };
        let result = print_output(&pr, &OutputFormat::Text);
        assert!(result.is_ok());
    }

    #[test]
    fn test_should_handle_empty_array() {
        let empty: Vec<TestIssue> = vec![];
        let result = print_output(&empty, &OutputFormat::Text);
        assert!(result.is_ok());
    }

    #[test]
    fn test_should_handle_null_value() {
        let null_val: Option<String> = None;
        let result = print_output(&null_val, &OutputFormat::Text);
        assert!(result.is_ok());
    }

    #[test]
    fn test_format_value_null() {
        assert_eq!(format_value(&serde_json::Value::Null), "-");
    }

    #[test]
    fn test_format_value_bool() {
        assert_eq!(format_value(&serde_json::Value::Bool(true)), "true");
    }

    #[test]
    fn test_format_value_number() {
        assert_eq!(format_value(&serde_json::json!(42)), "42");
    }

    #[test]
    fn test_format_value_string() {
        assert_eq!(
            format_value(&serde_json::Value::String(String::from("hello"))),
            "hello"
        );
    }

    #[test]
    fn test_format_value_array() {
        let arr = serde_json::json!(["bug", "enhancement"]);
        assert_eq!(format_value(&arr), "bug, enhancement");
    }

    #[test]
    fn test_pad_right_pads() {
        assert_eq!(pad_right("hi", 5), "hi   ");
    }

    #[test]
    fn test_pad_right_no_truncation() {
        assert_eq!(pad_right("hello", 3), "hello");
    }

    #[test]
    fn test_should_output_toon_format() {
        let issues = vec![TestIssue {
            number: 1,
            title: String::from("test"),
            state: String::from("open"),
        }];
        let result = print_output(&issues, &OutputFormat::Toon);
        assert!(result.is_ok());
    }

    #[test]
    fn test_should_output_auto_format() {
        let issues = vec![TestIssue {
            number: 1,
            title: String::from("test"),
            state: String::from("open"),
        }];
        let result = print_output(&issues, &OutputFormat::Auto);
        assert!(result.is_ok());
    }
}