treelog 0.0.6

A highly customizable, optimized, and modular tree rendering library
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
//! Command-line interface for treelog.

use clap::{ArgAction, Parser, Subcommand, ValueEnum};
use std::io::{self, Read};
#[cfg(any(
    feature = "arbitrary-walkdir",
    feature = "arbitrary-cargo",
    feature = "arbitrary-git2",
    feature = "arbitrary-syn"
))]
use std::path::PathBuf;

#[derive(Clone, Debug, ValueEnum)]
pub enum SortMethod {
    Label,
    Depth,
}

#[derive(Clone, Debug, ValueEnum)]
pub enum OutputFormat {
    Text,
    #[cfg(feature = "serde-json")]
    Json,
    #[cfg(feature = "serde-yaml")]
    Yaml,
    #[cfg(feature = "serde-toml")]
    Toml,
    #[cfg(feature = "serde-ron")]
    Ron,
    #[cfg(feature = "export")]
    Html,
    #[cfg(feature = "export")]
    Svg,
    #[cfg(feature = "export")]
    Dot,
}

#[derive(Parser)]
#[command(name = "treelog")]
#[command(about = "A customizable tree rendering library for Rust")]
#[command(version)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,

    /// Tree style
    #[arg(long, global = true, value_enum, default_value = "unicode")]
    pub style: treelog::TreeStyle,

    /// Custom style characters (format: branch,last,vertical,empty)
    #[arg(long, global = true)]
    pub custom_style: Option<String>,

    /// Enable color output
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    pub color: bool,

    /// Disable color output
    #[arg(long, global = true, action = ArgAction::SetTrue)]
    pub no_color: bool,

    /// Output file (use '-' for stdout)
    #[arg(short, long, global = true)]
    pub output: Option<String>,

    /// Output format
    #[arg(long, global = true, value_enum, default_value = "text")]
    pub format: OutputFormat,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Create tree from various sources
    From {
        #[command(subcommand)]
        source: FromSource,
    },
    /// Render a tree (from stdin or file)
    Render {
        /// Input file (use '-' for stdin)
        #[arg(default_value = "-")]
        input: String,
    },
    /// Display tree statistics
    Stats {
        /// Input file (use '-' for stdin)
        #[arg(default_value = "-")]
        input: String,
    },
    /// Search for nodes/leaves matching pattern
    Search {
        /// Search pattern
        pattern: String,
        /// Input file (use '-' for stdin)
        #[arg(default_value = "-")]
        input: String,
    },
    /// Transform tree operations
    #[cfg(feature = "transform")]
    Transform {
        #[command(subcommand)]
        operation: TransformOp,
        /// Input file (use '-' for stdin)
        #[arg(default_value = "-")]
        input: String,
    },
    /// Sort tree children
    Sort {
        /// Sort method
        #[arg(value_enum, default_value = "label")]
        method: SortMethod,
        /// Reverse sort order
        #[arg(short, long)]
        reverse: bool,
        /// Input file (use '-' for stdin)
        #[arg(default_value = "-")]
        input: String,
    },
    /// Compare two trees
    #[cfg(feature = "compare")]
    Compare {
        /// First tree file
        first: String,
        /// Second tree file
        second: String,
    },
    /// Merge two trees
    #[cfg(feature = "merge")]
    Merge {
        /// First tree file
        first: String,
        /// Second tree file
        second: String,
        /// Merge strategy
        #[arg(long, value_enum, default_value = "append")]
        strategy: treelog::merge::MergeStrategy,
    },
    /// Export tree to various formats
    #[cfg(feature = "export")]
    Export {
        #[command(subcommand)]
        format: ExportFormat,
        /// Input file (use '-' for stdin)
        #[arg(default_value = "-")]
        input: String,
    },
}

#[derive(Subcommand)]
pub enum FromSource {
    /// Build tree from directory structure
    #[cfg(feature = "arbitrary-walkdir")]
    Dir {
        /// Directory path
        path: PathBuf,
        /// Maximum depth
        #[arg(long)]
        max_depth: Option<usize>,
    },
    /// Build tree from Cargo metadata
    #[cfg(feature = "arbitrary-cargo")]
    Cargo {
        /// Manifest path (default: Cargo.toml in current directory)
        #[arg(default_value = "Cargo.toml")]
        manifest: PathBuf,
        /// Package name (for specific package dependencies)
        #[arg(long)]
        package: Option<String>,
    },
    /// Build tree from Git repository
    #[cfg(feature = "arbitrary-git2")]
    Git {
        /// Repository path (default: current directory)
        #[arg(default_value = ".")]
        path: PathBuf,
        /// Show branches only
        #[arg(long)]
        branches: bool,
        /// Show commit tree only
        #[arg(long)]
        commit: bool,
    },
    /// Build tree from XML/HTML file
    #[cfg(feature = "arbitrary-xml")]
    Xml {
        /// XML/HTML file path (use '-' for stdin)
        file: String,
    },
    /// Build tree from Rust source file (AST)
    #[cfg(feature = "arbitrary-syn")]
    Rust {
        /// Rust source file path
        file: PathBuf,
    },
    /// Build tree from tree-sitter parse
    #[cfg(feature = "arbitrary-tree-sitter")]
    TreeSitter {
        /// Source file path (use '-' for stdin)
        file: String,
        /// Language name (e.g., rust, javascript)
        #[arg(long)]
        language: Option<String>,
    },
    /// Build tree from JSON file
    #[cfg(feature = "serde-json")]
    Json {
        /// JSON file path (use '-' for stdin)
        file: String,
    },
    /// Build tree from YAML file
    #[cfg(feature = "serde-yaml")]
    Yaml {
        /// YAML file path (use '-' for stdin)
        file: String,
    },
    /// Build tree from TOML file
    #[cfg(feature = "serde-toml")]
    Toml {
        /// TOML file path (use '-' for stdin)
        file: String,
    },
    /// Build tree from RON file
    #[cfg(feature = "serde-ron")]
    Ron {
        /// RON file path (use '-' for stdin)
        file: String,
    },
}

#[derive(Subcommand)]
#[cfg(feature = "transform")]
pub enum TransformOp {
    /// Map node labels
    MapNodes {
        /// Transformation expression (e.g., "[{}]")
        expr: String,
        /// Input file (use '-' for stdin)
        #[arg(default_value = "-")]
        input: String,
    },
    /// Map leaf lines
    MapLeaves {
        /// Transformation expression (e.g., "- {}")
        expr: String,
        /// Input file (use '-' for stdin)
        #[arg(default_value = "-")]
        input: String,
    },
    /// Filter tree
    Filter {
        /// Filter pattern
        pattern: String,
        /// Input file (use '-' for stdin)
        #[arg(default_value = "-")]
        input: String,
    },
    /// Prune tree
    Prune {
        /// Prune pattern
        pattern: String,
        /// Input file (use '-' for stdin)
        #[arg(default_value = "-")]
        input: String,
    },
}

#[derive(Subcommand)]
#[cfg(feature = "export")]
pub enum ExportFormat {
    /// Export to HTML
    Html,
    /// Export to SVG
    Svg,
    /// Export to Graphviz DOT
    Dot,
}

fn main() {
    let cli = Cli::parse();

    let result = match &cli.command {
        Commands::From { source } => handle_from(source, &cli),
        Commands::Render { input } => handle_render(input, &cli),
        Commands::Stats { input } => handle_stats(input),
        Commands::Search { pattern, input } => handle_search(pattern, input),
        #[cfg(feature = "transform")]
        Commands::Transform { operation, input } => handle_transform(operation, input, &cli),
        Commands::Sort {
            method,
            reverse,
            input,
        } => handle_sort(method, *reverse, input, &cli),
        #[cfg(feature = "compare")]
        Commands::Compare { first, second } => handle_compare(first, second),
        #[cfg(feature = "merge")]
        Commands::Merge {
            strategy,
            first,
            second,
        } => handle_merge(strategy, first, second, &cli),
        #[cfg(feature = "export")]
        Commands::Export { format, input } => handle_export(format, input),
    };

    if let Err(e) = result {
        eprintln!("Error: {}", e);
        std::process::exit(1);
    }
}

#[allow(unreachable_code, unused_variables)]
fn handle_from(source: &FromSource, cli: &Cli) -> Result<(), Box<dyn std::error::Error>> {
    #[cfg(not(any(
        feature = "arbitrary-walkdir",
        feature = "arbitrary-cargo",
        feature = "arbitrary-git2",
        feature = "arbitrary-xml",
        feature = "arbitrary-syn",
        feature = "arbitrary-tree-sitter",
        feature = "serde-json",
        feature = "serde-yaml",
        feature = "serde-toml",
        feature = "serde-ron"
    )))]
    {
        return Err("No input source features enabled. Enable at least one feature (arbitrary-walkdir, arbitrary-cargo, arbitrary-git2, arbitrary-xml, arbitrary-syn, arbitrary-tree-sitter, serde-json, serde-yaml, serde-toml, or serde-ron).".into());
    }

    #[allow(unreachable_code)]
    let tree = match source {
        #[cfg(feature = "arbitrary-walkdir")]
        FromSource::Dir { path, max_depth } => {
            if let Some(depth) = max_depth {
                treelog::Tree::from_dir_max_depth(path, *depth)?
            } else {
                treelog::Tree::from_dir(path)?
            }
        }
        #[cfg(feature = "arbitrary-cargo")]
        FromSource::Cargo { manifest, package } => {
            if let Some(pkg) = package {
                treelog::Tree::from_cargo_package_deps(pkg, manifest)?
            } else {
                treelog::Tree::from_cargo_metadata(manifest)?
            }
        }
        #[cfg(feature = "arbitrary-git2")]
        FromSource::Git {
            path,
            branches,
            commit,
        } => {
            use git2::Repository;
            let repo = Repository::open(path)?;
            if *branches {
                treelog::Tree::from_git_branches(&repo)?
            } else if *commit {
                let head = repo.head()?.peel_to_commit()?;
                treelog::Tree::from_git_commit_tree(&repo, &head)?
            } else {
                treelog::Tree::from_git_repo(path)?
            }
        }
        #[cfg(feature = "arbitrary-xml")]
        FromSource::Xml { file } => {
            if file == "-" {
                let mut content = String::new();
                io::stdin().read_to_string(&mut content)?;
                treelog::Tree::from_arbitrary_xml(&content)?
            } else {
                treelog::Tree::from_arbitrary_xml_file(file)?
            }
        }
        #[cfg(feature = "arbitrary-syn")]
        FromSource::Rust { file } => treelog::Tree::from_syn_file(file)?,
        #[cfg(feature = "arbitrary-tree-sitter")]
        FromSource::TreeSitter {
            file: _file,
            language: _language,
        } => {
            return Err("tree-sitter parsing requires language specification. This feature needs implementation.".into());
        }
        #[cfg(feature = "serde-json")]
        FromSource::Json { file } => {
            let content = read_file_or_stdin(file)?;
            treelog::Tree::from_json(&content)?
        }
        #[cfg(feature = "serde-yaml")]
        FromSource::Yaml { file } => {
            let content = read_file_or_stdin(file)?;
            treelog::Tree::from_yaml(&content)?
        }
        #[cfg(feature = "serde-toml")]
        FromSource::Toml { file } => {
            let content = read_file_or_stdin(file)?;
            treelog::Tree::from_toml(&content)?
        }
        #[cfg(feature = "serde-ron")]
        FromSource::Ron { file } => {
            let content = read_file_or_stdin(file)?;
            treelog::Tree::from_ron(&content)?
        }
        #[cfg(not(any(
            feature = "arbitrary-walkdir",
            feature = "arbitrary-cargo",
            feature = "arbitrary-git2",
            feature = "arbitrary-xml",
            feature = "arbitrary-syn",
            feature = "arbitrary-tree-sitter",
            feature = "serde-json",
            feature = "serde-yaml",
            feature = "serde-toml",
            feature = "serde-ron"
        )))]
        _ => {
            return Err("No input source features enabled. Enable at least one feature (walkdir, cargo-metadata, git2, arbitrary-xml, syn, tree-sitter, serde-json, serde-yaml, serde-toml, or serde-ron).".into());
        }
    };

    output_tree(&tree, cli)
}

fn handle_render(input: &str, cli: &Cli) -> Result<(), Box<dyn std::error::Error>> {
    let tree = read_tree(input)?;
    output_tree(&tree, cli)
}

fn handle_stats(input: &str) -> Result<(), Box<dyn std::error::Error>> {
    let tree = read_tree(input)?;
    let stats = tree.stats();
    println!("Tree Statistics:");
    println!("  Depth: {}", stats.depth);
    println!("  Width: {}", stats.width);
    println!("  Node count: {}", stats.node_count);
    println!("  Leaf count: {}", stats.leaf_count);
    println!("  Total lines: {}", stats.total_lines);
    Ok(())
}

fn handle_search(pattern: &str, input: &str) -> Result<(), Box<dyn std::error::Error>> {
    let tree = read_tree(input)?;
    let matches = tree.find_all_nodes(pattern);
    if matches.is_empty() {
        println!("No nodes found matching '{}'", pattern);
    } else {
        println!("Found {} node(s) matching '{}':", matches.len(), pattern);
        for (i, node) in matches.iter().enumerate() {
            println!("  {}. {}", i + 1, node.label().unwrap_or("(no label)"));
        }
    }
    Ok(())
}

#[allow(unused_variables)]
#[cfg(feature = "transform")]
fn handle_transform(
    operation: &TransformOp,
    input: &str,
    cli: &Cli,
) -> Result<(), Box<dyn std::error::Error>> {
    let tree = read_tree(input)?;
    let transformed = match operation {
        TransformOp::MapNodes { expr, .. } => tree.map_nodes(|label| expr.replace("{}", label)),
        TransformOp::MapLeaves { expr, .. } => tree.map_leaves(|line| expr.replace("{}", line)),
        TransformOp::Filter { pattern, .. } => {
            if let Some(filtered) = tree.filter(|t| match t {
                treelog::Tree::Node(label, _) => label.contains(pattern),
                treelog::Tree::Leaf(lines) => lines.iter().any(|l| l.contains(pattern)),
            }) {
                filtered
            } else {
                return Err("Filter resulted in empty tree".into());
            }
        }
        TransformOp::Prune { pattern, .. } => {
            if let Some(pruned) = tree.prune(|t| match t {
                treelog::Tree::Node(label, _) => label.contains(pattern),
                treelog::Tree::Leaf(lines) => lines.iter().any(|l| l.contains(pattern)),
            }) {
                pruned
            } else {
                return Err("Prune resulted in empty tree".into());
            }
        }
    };
    output_tree(&transformed, cli)
}

fn handle_sort(
    method: &SortMethod,
    reverse: bool,
    input: &str,
    cli: &Cli,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut tree = read_tree(input)?;
    match method {
        SortMethod::Label => {
            tree.sort_by_label();
            if reverse {
                tree.sort_children(&mut |a, b| b.label().cmp(&a.label()));
            }
        }
        SortMethod::Depth => {
            tree.sort_by_depth(reverse);
        }
    }
    output_tree(&tree, cli)
}

#[allow(unused_variables)]
#[cfg(feature = "compare")]
fn handle_compare(first: &str, second: &str) -> Result<(), Box<dyn std::error::Error>> {
    let tree1 = read_tree(first)?;
    let tree2 = read_tree(second)?;

    if tree1.eq_structure(&tree2) {
        println!("Trees have the same structure");
    } else {
        println!("Trees have different structures");
    }

    let diffs = tree1.diff(&tree2);
    if diffs.is_empty() {
        println!("No differences found");
    } else {
        println!("Found {} difference(s):", diffs.len());
        for diff in diffs {
            match diff {
                treelog::compare::TreeDiff::OnlyInFirst { path, content } => {
                    println!("  Only in first (path: {:?}): {}", path, content);
                }
                treelog::compare::TreeDiff::OnlyInSecond { path, content } => {
                    println!("  Only in second (path: {:?}): {}", path, content);
                }
                treelog::compare::TreeDiff::DifferentContent {
                    path,
                    first,
                    second,
                } => {
                    println!("  Different at {:?}: '{}' vs '{}'", path, first, second);
                }
            }
        }
    }
    Ok(())
}

#[allow(unused_variables)]
#[cfg(feature = "merge")]
fn handle_merge(
    strategy: &treelog::merge::MergeStrategy,
    first: &str,
    second: &str,
    cli: &Cli,
) -> Result<(), Box<dyn std::error::Error>> {
    let tree1 = read_tree(first)?;
    let tree2 = read_tree(second)?;
    let merged = tree1.merge(tree2, strategy.clone());
    output_tree(&merged, cli)
}

#[allow(unused_variables)]
#[cfg(feature = "export")]
fn handle_export(format: &ExportFormat, input: &str) -> Result<(), Box<dyn std::error::Error>> {
    let tree = read_tree(input)?;
    let output = match format {
        ExportFormat::Html => tree.to_html(),
        ExportFormat::Svg => tree.to_svg(),
        ExportFormat::Dot => tree.to_dot(),
    };
    println!("{}", output);
    Ok(())
}

#[allow(unused_variables)]
fn read_tree(input: &str) -> Result<treelog::Tree, Box<dyn std::error::Error>> {
    let content = read_file_or_stdin(input)?;

    // Try to deserialize from JSON first
    #[cfg(feature = "serde-json")]
    if let Ok(tree) = treelog::Tree::from_json(&content) {
        return Ok(tree);
    }

    // Try YAML
    #[cfg(feature = "serde-yaml")]
    if let Ok(tree) = treelog::Tree::from_yaml(&content) {
        return Ok(tree);
    }

    // Try TOML
    #[cfg(feature = "serde-toml")]
    if let Ok(tree) = treelog::Tree::from_toml(&content) {
        return Ok(tree);
    }

    // Try RON
    #[cfg(feature = "serde-ron")]
    if let Ok(tree) = treelog::Tree::from_ron(&content) {
        return Ok(tree);
    }

    #[cfg(not(any(
        feature = "serde-json",
        feature = "serde-yaml",
        feature = "serde-toml",
        feature = "serde-ron"
    )))]
    let _ = content; // Suppress unused variable warning when no features enabled

    Err("Could not parse tree. Ensure the input is valid JSON, YAML, TOML, or RON, or enable the appropriate feature.".into())
}

fn read_file_or_stdin(path: &str) -> Result<String, Box<dyn std::error::Error>> {
    if path == "-" {
        let mut content = String::new();
        io::stdin().read_to_string(&mut content)?;
        Ok(content)
    } else {
        std::fs::read_to_string(path).map_err(|e| e.into())
    }
}

fn output_tree(tree: &treelog::Tree, cli: &Cli) -> Result<(), Box<dyn std::error::Error>> {
    let config = build_render_config(cli)?;
    let output = match &cli.format {
        OutputFormat::Text => tree.render_to_string_with_config(&config),
        #[cfg(feature = "export")]
        OutputFormat::Html => tree.to_html(),
        #[cfg(feature = "export")]
        OutputFormat::Svg => tree.to_svg(),
        #[cfg(feature = "export")]
        OutputFormat::Dot => tree.to_dot(),
        #[cfg(feature = "serde-json")]
        OutputFormat::Json => tree
            .to_json_pretty()
            .map_err(|e| format!("Failed to serialize to JSON: {}", e))?,
        #[cfg(feature = "serde-yaml")]
        OutputFormat::Yaml => tree
            .to_yaml()
            .map_err(|e| format!("Failed to serialize to YAML: {}", e))?,
        #[cfg(feature = "serde-toml")]
        OutputFormat::Toml => tree
            .to_toml()
            .map_err(|e| format!("Failed to serialize to TOML: {}", e))?,
        #[cfg(feature = "serde-ron")]
        OutputFormat::Ron => tree
            .to_ron_pretty()
            .map_err(|e| format!("Failed to serialize to RON: {}", e))?,
        #[cfg(not(feature = "export"))]
        OutputFormat::Html | OutputFormat::Svg | OutputFormat::Dot => {
            return Err(
                "Export feature is not enabled. Enable the 'export' feature to use this format."
                    .into(),
            );
        }
        #[cfg(not(feature = "serde-json"))]
        OutputFormat::Json => {
            return Err(
                "JSON feature is not enabled. Enable the 'json' feature to use JSON format.".into(),
            );
        }
        #[cfg(not(feature = "serde-yaml"))]
        OutputFormat::Yaml => {
            return Err(
                "YAML feature is not enabled. Enable the 'yaml' feature to use YAML format.".into(),
            );
        }
        #[cfg(not(feature = "serde-toml"))]
        OutputFormat::Toml => {
            return Err(
                "TOML feature is not enabled. Enable the 'toml' feature to use TOML format.".into(),
            );
        }
        #[cfg(not(feature = "serde-ron"))]
        OutputFormat::Ron => {
            return Err(
                "RON feature is not enabled. Enable the 'ron' feature to use RON format.".into(),
            );
        }
    };

    if let Some(output_path) = &cli.output {
        if output_path == "-" {
            print!("{}", output);
        } else {
            std::fs::write(output_path, output)?;
        }
    } else {
        print!("{}", output);
    }

    Ok(())
}

fn build_render_config(cli: &Cli) -> Result<treelog::RenderConfig, Box<dyn std::error::Error>> {
    use treelog::{RenderConfig, StyleConfig};

    let mut config = RenderConfig::default();

    // Set style
    if let Some(custom) = &cli.custom_style {
        let parts: Vec<&str> = custom.split(',').collect();
        if parts.len() != 4 {
            return Err(
                "Custom style must have 4 comma-separated values: branch,last,vertical,empty"
                    .into(),
            );
        }
        config = config.with_style(StyleConfig::custom(
            parts[0].trim(),
            parts[1].trim(),
            parts[2].trim(),
            parts[3].trim(),
        ));
    } else {
        // cli.style is already a treelog::TreeStyle (Unicode, Ascii, or Box)
        // Custom variant is skipped by ValueEnum, so we can safely use it
        config = config.with_style(cli.style.clone());
    }

    // Set colors
    #[cfg(feature = "color")]
    {
        if cli.color && !cli.no_color {
            config = config.with_colors(true);
        } else if cli.no_color {
            config = config.with_colors(false);
        }
    }

    Ok(config)
}