codeviz_python/
file_spec.rs1use codeviz_common::ElementFormatter;
2use std::collections::BTreeSet;
3use super::*;
4
5#[derive(Debug, Clone)]
6pub struct FileSpec {
7 pub elements: Elements,
8}
9
10impl FileSpec {
11 pub fn new() -> FileSpec {
12 FileSpec { elements: Elements::new() }
13 }
14
15 pub fn push<E>(&mut self, element: E)
16 where
17 E: Into<Element>,
18 {
19 self.elements.push(element);
20 }
21
22 fn imports(&self) -> Option<Elements> {
23 let mut imports = BTreeSet::new();
24
25 self.elements.imports(&mut imports);
26
27 let modules: BTreeSet<(String, Option<String>)> = imports
28 .into_iter()
29 .map(|imported| (imported.module, imported.alias))
30 .collect();
31
32 if modules.is_empty() {
33 return None;
34 }
35
36 let mut elements = Elements::new();
37
38 for (module, alias) in modules {
39 let mut s = Statement::new();
40
41 s.push("import ");
42 s.push(&module);
43
44 if let Some(ref alias) = alias {
45 s.push(" as ");
46 s.push(alias);
47 }
48
49 elements.push(s);
50 }
51
52 Some(elements)
53 }
54
55 pub fn format<W>(&self, out: &mut W) -> Result<()>
56 where
57 W: ::std::fmt::Write,
58 {
59 let mut elements = Elements::new();
60
61 if let Some(imports) = self.imports() {
62 elements.push(imports);
63 }
64
65 elements.push(self.elements.clone().join(Spacing));
66
67 let elements: Element = elements.clone().join(Spacing).into();
68 let mut extra = ();
69
70 elements.format(&mut ElementFormatter::new(out), &mut extra)?;
71 out.write_char('\n')?;
72
73 Ok(())
74 }
75}
76
77impl ImportReceiver for BTreeSet<ImportedName> {
78 fn receive(&mut self, name: &ImportedName) {
79 self.insert(name.clone());
80 }
81}
82
83impl ToString for FileSpec {
84 fn to_string(&self) -> String {
85 let mut s = String::new();
86 self.format(&mut s).unwrap();
87 s
88 }
89}