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
use super::*; use codeviz_common::ElementFormatter; use std::collections::{HashMap, BTreeSet}; #[derive(Debug, Clone)] pub struct FileSpec { pub package: String, pub elements: Elements, } impl FileSpec { pub fn new(package: &str) -> FileSpec { FileSpec { package: package.to_owned(), elements: Elements::new(), } } pub fn push<E>(&mut self, element: E) where E: Into<Element> { self.elements.push(element); } pub fn format<'a, W>(&'a self, out: &mut W) -> Result<()> where W: ::std::fmt::Write { let mut file = Elements::new(); let mut package = Statement::new(); package.push("package "); package.push(&self.package); package.push(";"); file.push(package); let mut locals: HashMap<String, ClassType> = HashMap::new(); let mut receiver: BTreeSet<ClassType> = BTreeSet::new(); self.elements.imports(&mut receiver); let imports: BTreeSet<ClassType> = receiver.into_iter() .filter(|t| t.package != "java.lang") .filter(|t| t.package != self.package) .map(|t| t.to_raw()) .collect(); if !imports.is_empty() { let mut imported = Elements::new(); for t in imports { if let Some(_) = locals.get(&t.name) { continue; } locals.insert(t.name.clone(), t.to_raw()); let mut import = Statement::new(); import.push("import "); import.push(t.package); import.push("."); import.push(t.name); import.push(";"); imported.push(import); } file.push(imported); } let content: Element = self.elements.clone().join(Spacing).into(); file.push(content); let file: Element = file.join(Spacing).into(); let mut extra = Extra::with_locals(locals); file.format(&mut ElementFormatter::new(out), &mut extra)?; out.write_char('\n')?; Ok(()) } } impl ImportReceiver for BTreeSet<ClassType> { fn receive(&mut self, ty: &ClassType) { self.insert(ty.clone()); } } impl ToString for FileSpec { fn to_string(&self) -> String { let mut s = String::new(); self.format(&mut s).unwrap(); s } }