Skip to main content

j_cli/command/
list.rs

1use crate::config::YamlConfig;
2use crate::constants::DEFAULT_DISPLAY_SECTIONS;
3use crate::md;
4use crate::util::log::capitalize_first_letter;
5
6/// 处理 list 命令: j ls [part]
7pub fn handle_list(part: Option<&str>, config: &YamlConfig) {
8    let mut md_text = String::new();
9    match part {
10        None => {
11            // 默认展示常用 section
12            for s in DEFAULT_DISPLAY_SECTIONS {
13                build_section_md(s, config, &mut md_text);
14            }
15        }
16        Some("all") => {
17            // 展示所有 section
18            for section in config.all_section_names() {
19                build_section_md(section, config, &mut md_text);
20            }
21        }
22        Some(section) => {
23            build_section_md(section, config, &mut md_text);
24        }
25    }
26
27    if md_text.is_empty() {
28        crate::info!("无可展示的内容");
29    } else {
30        md!("{}", md_text);
31    }
32}
33
34/// 将某个 section 的内容拼接到 Markdown 文本中(空 section 跳过)
35fn build_section_md(section: &str, config: &YamlConfig, md_text: &mut String) {
36    use colored::Colorize;
37
38    if let Some(map) = config.get_section(section) {
39        if map.is_empty() {
40            return;
41        }
42        md_text.push_str(&format!("## {}\n", capitalize_first_letter(section)));
43
44        // 计算最大 key 长度用于对齐
45        let max_key_len = map.keys().map(|k| k.len()).max().unwrap_or(0);
46
47        for (key, value) in map {
48            // key 青色显示,右对齐占位,箭头和 value 对齐
49            md_text.push_str(&format!(
50                "- {:width$} → {}\n",
51                key.cyan(),
52                value,
53                width = max_key_len
54            ));
55        }
56        md_text.push('\n');
57    } else {
58        crate::error!("该 section 不存在: {}", section);
59    }
60}