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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use log::trace;
use petgraph::graph::NodeIndex;
use ra_ap_hir as hir;
use ra_ap_ide::RootDatabase;

pub use crate::options::generate::graph::Options;

use crate::{
    graph::Graph,
    options::generate::graph::LayoutAlgorithm,
    printer::graph::{Options as PrinterOptions, Printer},
};

pub struct Command {
    options: Options,
}

impl Command {
    pub fn new(options: Options) -> Self {
        Self { options }
    }

    #[doc(hidden)]
    pub fn run(
        &self,
        graph: &Graph,
        start_node_idx: NodeIndex,
        member_krate: hir::Crate,
        db: &RootDatabase,
    ) -> anyhow::Result<()> {
        self.validate_options()?;

        if self.options.layout == LayoutAlgorithm::None {
            return Ok(());
        }

        trace!("Printing ...");

        let printer = {
            let printer_options: PrinterOptions = PrinterOptions {
                layout: self.options.layout.to_string(),
                full_paths: self.options.externs,
            };
            Printer::new(printer_options, member_krate, db)
        };

        let mut string = String::new();

        printer.fmt(&mut string, graph, start_node_idx)?;

        print!("{string}");

        Ok(())
    }

    fn validate_options(&self) -> anyhow::Result<()> {
        let options = &self.options;

        if options.externs && !options.uses {
            anyhow::bail!("Option `--externs` requires option `--uses`");
        }

        Ok(())
    }
}