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
use crate::Graph;
use std::{collections::HashSet, io, io::Write, str::FromStr};

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Charset {
    Utf8,
    Ascii,
}

impl Default for Charset {
    fn default() -> Self {
        // when operating in a console on windows non-UTF-8 byte sequences are not supported on
        // stdout, See also [`StdoutLock`]
        #[cfg(target_os = "windows")]
        {
            Charset::Ascii
        }
        #[cfg(not(target_os = "windows"))]
        Charset::Utf8
    }
}

impl FromStr for Charset {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "utf8" => Ok(Charset::Utf8),
            "ascii" => Ok(Charset::Ascii),
            s => Err(format!("invalid charset: {s}")),
        }
    }
}

/// Options to configure formatting
#[derive(Debug, Clone, Default)]
pub struct TreeOptions {
    /// The style of characters to use.
    pub charset: Charset,
    /// If `true`, duplicate imports will be repeated.
    /// If `false`, duplicates are suffixed with `(*)`, and their imports
    /// won't be shown.
    pub no_dedupe: bool,
}

/// Internal helper type for symbols
struct Symbols {
    down: &'static str,
    tee: &'static str,
    ell: &'static str,
    right: &'static str,
}

static UTF8_SYMBOLS: Symbols = Symbols { down: "│", tee: "├", ell: "└", right: "─" };

static ASCII_SYMBOLS: Symbols = Symbols { down: "|", tee: "|", ell: "`", right: "-" };

pub fn print(graph: &Graph, opts: &TreeOptions, out: &mut dyn Write) -> io::Result<()> {
    let symbols = match opts.charset {
        Charset::Utf8 => &UTF8_SYMBOLS,
        Charset::Ascii => &ASCII_SYMBOLS,
    };

    // used to determine whether to display `(*)`
    let mut visited_imports = HashSet::new();

    // A stack of bools used to determine where | symbols should appear
    // when printing a line.
    let mut levels_continue = Vec::new();
    // used to detect dependency cycles when --no-dedupe is used.
    // contains a `Node` for each level.
    let mut write_stack = Vec::new();

    for (node_index, _) in graph.input_nodes().enumerate() {
        print_node(
            graph,
            node_index,
            symbols,
            opts.no_dedupe,
            &mut visited_imports,
            &mut levels_continue,
            &mut write_stack,
            out,
        )?;
    }

    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn print_node(
    graph: &Graph,
    node_index: usize,
    symbols: &Symbols,
    no_dedupe: bool,
    visited_imports: &mut HashSet<usize>,
    levels_continue: &mut Vec<bool>,
    write_stack: &mut Vec<usize>,
    out: &mut dyn Write,
) -> io::Result<()> {
    let new_node = no_dedupe || visited_imports.insert(node_index);

    if let Some((last_continues, rest)) = levels_continue.split_last() {
        for continues in rest {
            let c = if *continues { symbols.down } else { " " };
            write!(out, "{c}   ")?;
        }

        let c = if *last_continues { symbols.tee } else { symbols.ell };
        write!(out, "{0}{1}{1} ", c, symbols.right)?;
    }

    let in_cycle = write_stack.contains(&node_index);
    // if this node does not have any outgoing edges, don't include the (*)
    // since there isn't really anything "deduplicated", and it generally just
    // adds noise.
    let has_deps = graph.has_outgoing_edges(node_index);
    let star = if (new_node && !in_cycle) || !has_deps { "" } else { " (*)" };

    writeln!(out, "{}{star}", graph.display_node(node_index))?;

    if !new_node || in_cycle {
        return Ok(())
    }
    write_stack.push(node_index);

    print_imports(
        graph,
        node_index,
        symbols,
        no_dedupe,
        visited_imports,
        levels_continue,
        write_stack,
        out,
    )?;

    write_stack.pop();

    Ok(())
}

/// Prints all the imports of a node
#[allow(clippy::too_many_arguments, clippy::ptr_arg)]
fn print_imports(
    graph: &Graph,
    node_index: usize,
    symbols: &Symbols,
    no_dedupe: bool,
    visited_imports: &mut HashSet<usize>,
    levels_continue: &mut Vec<bool>,
    write_stack: &mut Vec<usize>,
    out: &mut dyn Write,
) -> io::Result<()> {
    let imports = graph.imported_nodes(node_index);
    if imports.is_empty() {
        return Ok(())
    }

    let mut iter = imports.iter().peekable();

    while let Some(import) = iter.next() {
        levels_continue.push(iter.peek().is_some());
        print_node(
            graph,
            *import,
            symbols,
            no_dedupe,
            visited_imports,
            levels_continue,
            write_stack,
            out,
        )?;
        levels_continue.pop();
    }

    Ok(())
}