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
use self::format::Pattern;
use crate::core::compiler::{CompileKind, RustcTargetData};
use crate::core::dependency::DepKind;
use crate::core::resolver::{features::CliFeatures, ForceAllTargets, HasDevUnits};
use crate::core::{Package, PackageId, PackageIdSpec, Workspace};
use crate::ops::{self, Packages};
use crate::util::{CargoResult, Config};
use crate::{drop_print, drop_println};
use anyhow::Context;
use graph::Graph;
use std::collections::{HashMap, HashSet};
use std::str::FromStr;
mod format;
mod graph;
pub use {graph::EdgeKind, graph::Node};
pub struct TreeOptions {
pub cli_features: CliFeatures,
pub packages: Packages,
pub target: Target,
pub edge_kinds: HashSet<EdgeKind>,
pub invert: Vec<String>,
pub pkgs_to_prune: Vec<String>,
pub prefix: Prefix,
pub no_dedupe: bool,
pub duplicates: bool,
pub charset: Charset,
pub format: String,
pub graph_features: bool,
pub max_display_depth: u32,
pub no_proc_macro: bool,
}
#[derive(PartialEq)]
pub enum Target {
Host,
Specific(Vec<String>),
All,
}
impl Target {
pub fn from_cli(targets: Vec<String>) -> Target {
match targets.len() {
0 => Target::Host,
1 if targets[0] == "all" => Target::All,
_ => Target::Specific(targets),
}
}
}
pub enum Charset {
Utf8,
Ascii,
}
impl FromStr for Charset {
type Err = &'static str;
fn from_str(s: &str) -> Result<Charset, &'static str> {
match s {
"utf8" => Ok(Charset::Utf8),
"ascii" => Ok(Charset::Ascii),
_ => Err("invalid charset"),
}
}
}
#[derive(Clone, Copy)]
pub enum Prefix {
None,
Indent,
Depth,
}
impl FromStr for Prefix {
type Err = &'static str;
fn from_str(s: &str) -> Result<Prefix, &'static str> {
match s {
"none" => Ok(Prefix::None),
"indent" => Ok(Prefix::Indent),
"depth" => Ok(Prefix::Depth),
_ => Err("invalid prefix"),
}
}
}
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 build_and_print(ws: &Workspace<'_>, opts: &TreeOptions) -> CargoResult<()> {
let requested_targets = match &opts.target {
Target::All | Target::Host => Vec::new(),
Target::Specific(t) => t.clone(),
};
let requested_kinds = CompileKind::from_requested_targets(ws.config(), &requested_targets)?;
let target_data = RustcTargetData::new(ws, &requested_kinds)?;
let specs = opts.packages.to_package_id_specs(ws)?;
let has_dev = if opts
.edge_kinds
.contains(&EdgeKind::Dep(DepKind::Development))
{
HasDevUnits::Yes
} else {
HasDevUnits::No
};
let force_all = if opts.target == Target::All {
ForceAllTargets::Yes
} else {
ForceAllTargets::No
};
let ws_resolve = ops::resolve_ws_with_opts(
ws,
&target_data,
&requested_kinds,
&opts.cli_features,
&specs,
has_dev,
force_all,
)?;
let package_map: HashMap<PackageId, &Package> = ws_resolve
.pkg_set
.packages()
.map(|pkg| (pkg.package_id(), pkg))
.collect();
let mut graph = graph::build(
ws,
&ws_resolve.targeted_resolve,
&ws_resolve.resolved_features,
&specs,
&opts.cli_features,
&target_data,
&requested_kinds,
package_map,
opts,
)?;
let root_specs = if opts.invert.is_empty() {
specs
} else {
opts.invert
.iter()
.map(|p| PackageIdSpec::parse(p))
.collect::<CargoResult<Vec<PackageIdSpec>>>()?
};
let root_ids = ws_resolve.targeted_resolve.specs_to_ids(&root_specs)?;
let root_indexes = graph.indexes_from_ids(&root_ids);
let root_indexes = if opts.duplicates {
graph = graph.from_reachable(root_indexes.as_slice());
graph.find_duplicates()
} else {
root_indexes
};
if !opts.invert.is_empty() || opts.duplicates {
graph.invert();
}
let pkgs_to_prune = opts
.pkgs_to_prune
.iter()
.map(|p| PackageIdSpec::parse(p))
.map(|r| {
r.and_then(|spec| spec.query(ws_resolve.targeted_resolve.iter()).and(Ok(spec)))
})
.collect::<CargoResult<Vec<PackageIdSpec>>>()?;
print(ws.config(), opts, root_indexes, &pkgs_to_prune, &graph)?;
Ok(())
}
fn print(
config: &Config,
opts: &TreeOptions,
roots: Vec<usize>,
pkgs_to_prune: &[PackageIdSpec],
graph: &Graph<'_>,
) -> CargoResult<()> {
let format = Pattern::new(&opts.format)
.with_context(|| format!("tree format `{}` not valid", opts.format))?;
let symbols = match opts.charset {
Charset::Utf8 => &UTF8_SYMBOLS,
Charset::Ascii => &ASCII_SYMBOLS,
};
let mut visited_deps = HashSet::new();
for (i, root_index) in roots.into_iter().enumerate() {
if i != 0 {
drop_println!(config);
}
let mut levels_continue = vec![];
let mut print_stack = vec![];
print_node(
config,
graph,
root_index,
&format,
symbols,
pkgs_to_prune,
opts.prefix,
opts.no_dedupe,
opts.max_display_depth,
opts.no_proc_macro,
&mut visited_deps,
&mut levels_continue,
&mut print_stack,
);
}
Ok(())
}
fn print_node<'a>(
config: &Config,
graph: &'a Graph<'_>,
node_index: usize,
format: &Pattern,
symbols: &Symbols,
pkgs_to_prune: &[PackageIdSpec],
prefix: Prefix,
no_dedupe: bool,
max_display_depth: u32,
no_proc_macro: bool,
visited_deps: &mut HashSet<usize>,
levels_continue: &mut Vec<bool>,
print_stack: &mut Vec<usize>,
) {
let new = no_dedupe || visited_deps.insert(node_index);
match prefix {
Prefix::Depth => drop_print!(config, "{}", levels_continue.len()),
Prefix::Indent => {
if let Some((last_continues, rest)) = levels_continue.split_last() {
for continues in rest {
let c = if *continues { symbols.down } else { " " };
drop_print!(config, "{} ", c);
}
let c = if *last_continues {
symbols.tee
} else {
symbols.ell
};
drop_print!(config, "{0}{1}{1} ", c, symbols.right);
}
}
Prefix::None => {}
}
let in_cycle = print_stack.contains(&node_index);
let has_deps = graph.has_outgoing_edges(node_index);
let star = if (new && !in_cycle) || !has_deps {
""
} else {
" (*)"
};
drop_println!(config, "{}{}", format.display(graph, node_index), star);
if !new || in_cycle {
return;
}
print_stack.push(node_index);
for kind in &[
EdgeKind::Dep(DepKind::Normal),
EdgeKind::Dep(DepKind::Build),
EdgeKind::Dep(DepKind::Development),
EdgeKind::Feature,
] {
print_dependencies(
config,
graph,
node_index,
format,
symbols,
pkgs_to_prune,
prefix,
no_dedupe,
max_display_depth,
no_proc_macro,
visited_deps,
levels_continue,
print_stack,
kind,
);
}
print_stack.pop();
}
fn print_dependencies<'a>(
config: &Config,
graph: &'a Graph<'_>,
node_index: usize,
format: &Pattern,
symbols: &Symbols,
pkgs_to_prune: &[PackageIdSpec],
prefix: Prefix,
no_dedupe: bool,
max_display_depth: u32,
no_proc_macro: bool,
visited_deps: &mut HashSet<usize>,
levels_continue: &mut Vec<bool>,
print_stack: &mut Vec<usize>,
kind: &EdgeKind,
) {
let deps = graph.connected_nodes(node_index, kind);
if deps.is_empty() {
return;
}
let name = match kind {
EdgeKind::Dep(DepKind::Normal) => None,
EdgeKind::Dep(DepKind::Build) => Some("[build-dependencies]"),
EdgeKind::Dep(DepKind::Development) => Some("[dev-dependencies]"),
EdgeKind::Feature => None,
};
if let Prefix::Indent = prefix {
if let Some(name) = name {
for continues in &**levels_continue {
let c = if *continues { symbols.down } else { " " };
drop_print!(config, "{} ", c);
}
drop_println!(config, "{}", name);
}
}
if levels_continue.len() + 1 > max_display_depth as usize {
return;
}
let mut it = deps
.iter()
.filter(|dep| {
if no_proc_macro {
match graph.node(**dep) {
&Node::Package { package_id, .. } => {
!graph.package_for_id(package_id).proc_macro()
}
_ => true,
}
} else {
true
}
})
.filter(|dep| {
match graph.node(**dep) {
Node::Package { package_id, .. } => {
!pkgs_to_prune.iter().any(|spec| spec.matches(*package_id))
}
_ => true,
}
})
.peekable();
while let Some(dependency) = it.next() {
levels_continue.push(it.peek().is_some());
print_node(
config,
graph,
*dependency,
format,
symbols,
pkgs_to_prune,
prefix,
no_dedupe,
max_display_depth,
no_proc_macro,
visited_deps,
levels_continue,
print_stack,
);
levels_continue.pop();
}
}